在2D游戏的寻路(寻找)行为中改变实体的角度(旋转)

我正在使用LOVE2D在Lua中开发2D太空射击游戏,由于我不是数学和物理专家,因此在实现敌人的寻路行为时遇到了一些问题。

我最终成功实现了敌人寻找玩家的行为,效果如下:

让其工作的代码(公式取自此答案-https://stackoverflow.com/a/2561054/2117550):

function Enemy:seek ()
  local dx = self.player.x - self.x - self.xvel
  local dy = self.player.y - self.y - self.yvel

  -- normalize
  local len = math.sqrt(dx * dx + dy * dy)
  dx, dy = dx / len, dy / len

  return dx, dy
end

然后在update函数中使用seek函数:

function Enemy:update (dt)
  -- seeking acceleration
  local dx, dy = self:seek()

  -- what is the proper way of calculating enemies rotation?
  -- self.rotation = math.atan2(dx, dy) + ANGLE_ACCELERATION * dt

  -- update velocity
  self.xvel = self.xvel + dx * MAX_SPEED * dt -- * math.cos(self.rotation) it's not needed anymore?
  self.yvel = self.yvel + dy * MAX_SPEED * dt -- * math.sin(self.rotation) it's not needed anymore?

  -- moving entity in camera
  _.checkWorldBounds(self)

  local futureX = self.x + self.xvel * dt
  local futureY = self.y + self.yvel * dt
  local nextX, nextY, collisions, len = self.world:move(self, futureX, futureY, self.collisionFilter)

  self.x = nextX
  self.y = nextY
  self.xvel = self.xvel * 0.99
  self.yvel = self.yvel * 0.99
end

所以现在唯一的问题是敌人的旋转不会改变,尽管飞船的前部应始终朝向玩家的方向。

我尝试了math.atan2(dx,dy),但它会使实体不断旋转。

我缺少什么或我做错了什么?

我不是在寻求有人为我编写代码(尽管这将非常不错),但是一些公式或建议将受到高度赞赏。

如果您感兴趣,源代码可在以下位置找到-https://github.com/voronianski-on-games/asteroids-on-steroids-love2d

点赞
用户6575359
用户6575359

我无法告诉你代码错在哪里,但是希望这可以帮助你解决问题。

-- 这些是你的物体应该朝向的点的坐标
local playerx, playery = 100, 100
-- 这些是需要改变面向的物体的当前坐标
local shipx, shipy = 200, 200

-- 计算应该旋转的角度
angle = math.atan2(playery - shipy, playerx - shipx)

注意,使用 body:setAngle(angle)('body' 是你的物体的身体)你的物体将立即旋转到给定的角度。如果你想让它们以一定的速度旋转,你可以使用:

local currentAngle = body:getAngle()
local adjustedAngle

if currentAngle > angle then
  adjustedAngle = currentAngle - rotationSpeed * dt
elseif currentAngle < angle then
  adjustedAngle = currentAngle + rotationSpeed * dt
else
  adjustedAngle = currentAngle
end
body:setAngle(adjustedAngle)

还要注意,你的船/身体/物体的“前方”是沿着 x 轴向右的。换句话说,角度是从 x 轴计算的,0 表示物体向右面对。

2017-01-16 20:22:37