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

时间:2017-01-07 11:42:56

标签: lua 2d box2d game-physics love2d

我正在Lua开发带有LOVE2D的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

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

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

1 个答案:

答案 0 :(得分:1)

我无法告诉您代码有什么问题,但希望这会对您有所帮助。

-- these are the coordinates of the point to which your object should be facing
local playerx, playery = 100, 100
-- these are the current coordinates of the object that needs to have its facing changed
local shipx, shipy = 200, 200

-- the angle to which your object should be rotated is calculated
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)

还要注意前面的&#39;你的船/身体/物体沿着x轴向右。换句话说,角度是从x轴计算的,0表示物体朝右。