iT邦幫忙

2024 iThome 鐵人賽

DAY 23
0
Mobile Development

用Flutter Flame做遊戲!Live!系列 第 25

用「拖曳物件到螢幕邊緣」來移動camera

  • 分享至 

  • xImage
  •  

這裡有一段程式碼,可以用在BodyComponent中,(特別是「DragUpdate」,)這樣就可以一邊移動這個物件、一邊在它「超出螢幕範圍時,移動camera顯示範圍,而且是往超出的方向移動。」


    final visibleRect = camera.visibleWorldRect;
    final topLeft = visibleRect.topLeft.toVector2();
    // final topRight = visibleRect.topRight.toVector2();
    final bottomRight = visibleRect.bottomRight.toVector2();
    // final bottomLeft = visibleRect.bottomLeft.toVector2();

    if(position.x < topLeft.x || position.x > bottomRight.x || position.y < topLeft.y || position.y > bottomRight.y){
      camera.moveBy(event.localDelta);
    }

這段程式碼利用了「BodyComponent都可以取得camera與world」的特性。
所以,如果要用其他框架來擴充BodyComponent的特性,例如製作一套CallBack來特別在BodyComponent外設計對事件的回應方式,最好記得特別處理一下如何取得camera和world的問題。


經過進一步測試和調整後發現:
不要在「DragUpdate」中處理「移動camera」,而是要在「update」中。


  @override
  void onDragUpdate(DragUpdateEvent event) {
    transform(event.localDelta);
    localDelta = event.localDelta;
  }
  
  @override
  void onDragEnd(DragEndEvent event) {
    super.onDragEnd(event);
    localDelta = null;
  }
  
  @override
  void update(double dt) {
    super.update(dt);
    
    if(localDelta != null){
      //請參考上面的範例程式碼
    }
    
  }


「DragUpdate」只會觸發一次,也就是說「螢幕移動」也只會發生一次。
這明顯不是這項設計想要達到的效果。
過去用Kotlin/Java設計Android時,碰到「移動View」時都是使用「TouchListener」,而它的「onTouch」會被持續觸發。
所以上面一開始的構想明顯是忽略了「Drag」的設計比較像「Click」,而不是「Touch」,(而這點很明顯。)


上一篇
繼續講Joint...來做一輛「車子」吧!
下一篇
週末,罷工一下....MouseJoint的垃圾官方範例...
系列文
用Flutter Flame做遊戲!Live!26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言