我注意到您的代码存在一些问题。
deg2 = math.rad(0) -- desired rotation
0 弧度等于 0 度,所以看起来deg2
总是为零,因此
for i = deg1, deg2 do
只会在deg1
等于或小于零时运行,这可能意味着它没有按您的预期运行。
其次,任何不需要离开其作用域的变量都应该本地化。这是 Lua 的最佳实践。您的函数可以用本地人重写,例如:
function rotatePlayer(dt)
local deg1 = player.rot -- player's current rotation
local step = 0 -- ! Any reference to a "step" variable within the scope of this function will always refer to this particular variable.
local deg2 = 0 -- desired rotation
step = (math.deg(deg1) - math.deg(deg2))*dt
for i = deg1, deg2 do
player.rot = player.rot - math.rad(step)
step = step - dt
end
end
dt
由于先前确定deg2
的始终为零的事实,以下行等效于将玩家旋转的度数乘以 delta 。
step = (math.deg(deg1) - math.deg(deg2))*dt
以下几行相当于将玩家的原始旋转度数乘以 delta ( step
) 并减去玩家当前旋转的弧度版本,然后dt
从step
值中减去 delta,在循环内执行我可能会添加单个游戏框架。我不确定您是否知道循环在一帧内运行。
player.rot = player.rot - math.rad(step)
step = step - dt
我不确定您对这些操作的意图是什么,但也许您可以告诉我更多信息。
至于实现更流畅的动画,您需要按比例缩小速率并调整旋转的执行方式。我已将您的函数重写如下,并希望它作为示例阐明如何更好地编写它:
function rotatePlayer(dt) -- dt is seconds since last update
local current = player.rot -- player's current rotation in radians
local target = 0 -- desired angle in radians
local difference = target - current
if difference == 0 then -- nothing to be done here
return
end
local rate = math.pi / 4 -- radians turned per second (adjust as necessary)
local change = rate * dt -- r/s * delta(change in time)
if difference < 0 then
-- make change negative, since difference is as well
change = change * -1
-- If (current + change > target), settle for the lesser difference.
-- This keeps us from "overshooting" the player's rotation
-- towards a particular target.
change = math.max(change, difference)
else
change = math.min(change, difference)
end
player.rot = current + change
end
请让我知道这是否能解决您的问题,如果您还有其他问题。