我需要在更改旋转后更改对象速度。
function love.update(dt)
if car['speed'] > 0 then
car['x'] = car['x'] + math.cos(car['angle'])
car['y'] = car['y'] + math.sin(car['angle'])
end
if love.keyboard.isDown("w") then
car['speed'] = car['speed'] + dt
end
if love.keyboard.isDown("a") then
car['angle'] = car['angle'] - (1 * dt)
end
if love.keyboard.isDown("d") then
car['angle'] = car['angle'] + (1 * dt)
end
end
在我改变" w"我希望它能改变汽车的速度(x,y)。 但是,当我试图添加速度时,它只是改变旋转并破坏它..
答案 0 :(得分:2)
所需的更改非常简单:只需按车速缩放cos
和sin
:
if car['speed'] > 0 then
car['x'] = car['x'] + car['speed'] * math.cos(car['angle'])
car['y'] = car['y'] + car['speed'] * math.sin(car['angle'])
end
此外,在Lua中,car['speed']
相当于car.speed
(syntactic sugar)。有些人发现这更容易阅读。上面的代码可以写成:
if car.speed > 0 then
car.x = car.x + car.speed * math.cos(car.angle)
car.y = car.y + car.speed * math.sin(car.angle)
end
PS:别忘了放慢车速;)