简体   繁体   English

如何沿旋转方向移动物体?

[英]How to move an object in the direction it's rotated?

I wanted to ask what would be the right way to move an object in the direction it is rotated? 我想问一下将物体沿旋转方向移动的正确方法是什么?

Right now I have: 现在我有:

    local ang = body:getAngle() * 180 / 3.14      /// get body's rotation in degrees
    local x, y = body:getPosition();      /// get current position
    ang = ang%360

    x = x + math.sin(ang) 
    y = y + math.cos(ang)

    print(ang)

    body:setPosition(x,y)

Yet the body is moving very weird. 然而身体移动得很奇怪。 Any ideas what I'm doing wrong? 有什么想法我做错了吗?

Thanks 谢谢

You need the angle in radians and use the cosine function for the x value and the sine function for the y value. 您需要以弧度为单位的角度,并将余弦函数用作x值,将正弦函数用作y值。 A function (untested) for this in lua would look something like this: lua中的一个函数(未经测试)看起来像这样:

function moveAlongAngle(body, angleInRadians, dt, speedVector)
    local x, y = body:getPosition()
    x = x + math.cos(angleInRadians) * dt * speedVector.x
    y = y + math.sin(angleInRadians) * dt * speedVector.y
    body:setPosition(x,y)
end

This is because you convert the angle from polar to cartesian coordinates: http://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates 这是因为您将角度从极坐标转换为直角坐标: http : //en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates

you are mixing radians and degrees. 您正在混合弧度和度数。 first you transform your angle into radians, but afterwards you try to normalize the degrees using modulo. 首先,您将角度转换为弧度,但是之后,您尝试使用模数对角度进行归一化。 you dont need to normalize, since sin and cos are periodic functions. 您不需要归一化,因为sin和cos是周期函数。

the math.sin and math.cos actually expect the angle in radians and not in degrees, so you need to devide by 180 and multiply by pi. math.sin和math.cos实际上期望的角度是弧度而不是度数,因此您需要除以180并乘以pi。

this is of course assuming your initial variable ang is in degrees. 当然,这是假设您的初始变量ang是度数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM