Swift-Making an SKNode simply “move forward” on an angle

落花浮王杯 提交于 2019-12-07 15:06:26

To do this, you just need to use some trigonometry!

When zRotation is between 0 and 90, you don't need to do anything to the angle except converting it to radians. Just call tan(radianAngle). Now tan will return how much should the node move in the y axis when it moves by 1 in the x axis. If you learned trigonometry before, you should understand what I'm saying. If you have not learned trigonometry, learn it. :)

Let's say the node's zRotation is 60 degrees, which is π/3 radians. Pass that into tan and you get √3. This means your dx and dy parameters in SKAction must be in the ratio of 1 : √3 in order to make the node move in the direction of 60 degrees.

When zRotation is between 90 and 180, you need to first subtract the angle from 180, then convert it to radians. Again, pass that to tan and the return value is how much your node should move in the y direction when it moves by -1 in the x axis. The dx : dy ratio is now -1 : tan(angleInRadians).

When zRotation is between 180 and 270, subtract 180 from that angle and convert it to radians. The dx : dy ratio is -1 : -tan(angleInRadians).

Lastly, a zRotation bewteen 270 and 360, subtract the angle from 360 and convert it to radians. The dx : dy ratio is 1 : -tan(angleInRadians).

Just before you convert the angle to radians, check if the angle is 90 degrees. If it is, please hard code the dx and dy because tan(M_PI / 2) is undefined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!