【问题标题】:Flutter/Flame limiting the drag area in a gameFlutter/Flame 限制游戏中的拖动区域
【发布时间】:2020-09-21 10:35:33
【问题描述】:

我试图通过拖动来移动我的播放器,但我不希望我的播放器离开屏幕。我怎样才能以体面的方式限制它?

void onPanUpdate(DragUpdateDetails details) {
  if(game.screenSize.width >= playerRect.right && playerRect.left >= 0
      && game.screenSize.height >= playerRect.bottom && playerRect.top >= 0) {
    playerRect = playerRect.translate(details.delta.dx, details.delta.dy);
  } else { 
    playerRect = playerRect.translate(-details.delta.dx*4.2, -details.delta.dy*4.2);
  }
}

我想出了这个解决方案,但你知道它并不酷。我感谢任何帮助。

【问题讨论】:

  • 我不认为你的代码那么糟糕,但我认为如果你的播放器在一次更新中设法移动到屏幕之外足够远然后改变方向拖。因为那样它可能会在每次迭代中都出现在 else 情况下。您可以将增量添加到 if-check 以避免这种情况,但可能有更好的方法可以一起比较两个矩形并从那里知道翻译。
  • 这段代码的问题就是你说的。无论负 delta 值是多少,无论如何我的播放器都会离开屏幕。当玩家在屏幕边缘晃动时,这看起来不是很好的体验。如果情况导致玩家移动缓慢,则越多。我对此一无所知。

标签: flutter flame


【解决方案1】:

很高兴看到我们游戏引擎的另一位用户!在检查中还必须考虑增量。像这样的东西应该可以工作:

void onPanUpdate(DragUpdateDetails details) {
  final delta = details.delta;
  final size = game.screenSize
  double translateX = delta.dx;
  double translateY = delta.dy;
  // Make sure that the player never goes outside of the screen in the X-axis
  if (playerRect.right + delta.dx >= size.width) {
      translateX = size.width - playerRect.right; 
  } else if (playerRect.left + delta.dx <= 0) {
      translateX = -playerRect.left; 
  }
  // Make sure that the player never goes outside of the screen in the Y-axis
  if (playerRect.bottom + delta.dy >= size.height) {
      translateY = size.height - playerRect.bottom; 
  } else if (playerRect.top + delta.dy <= 0) {
      translateY = -playerRect.top; 
  }
  playerRect = playerRect.translate(translateX, translateY);
}

如果您有更深入的问题,我建议您也加入我们的 discord: https://discord.gg/pxrBmy4

【讨论】:

  • playerRect.left + delta.dx > 0 和 playerRect.top + delta.dy > 0 应该是 playerRect.top + delta.dy ”。此代码完美运行。非常感谢。
  • 很高兴它起作用了,根据您的评论更新了代码。
猜你喜欢
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 2021-11-19
  • 2023-03-06
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多