Search code examples
swiftxcodeangleskactionsknode

Swift-Making an SKNode simply "move forward" on an angle


I've already asked this question in a different way here; Swift-Setting a physics body velocity by angle but the three attempts to answer it were unfortunately not exactly what I'm looking for, although I'm grateful for what they taught me anyway. I decided that I should simply rephrase my question with an example and further explanation instead of perpetuating a discussion via comments. So here it is.

Imagine I have an SKNode positioned in the centre of the screen. Let's say this is a ball, so any rotation action on it is not visible. I would need a way to have a random angle selected, and have said SKNode rotate to it, and then continuously move in the direction determined by the aforementioned angle from its original position in the centre of the screen, until, say, the edge of the screen.

I know how to determine the random angle, have the SKNode rotate to it, and have it stop at the edge of the screen. Hopefully with this example what I need is clearer, a way to simply have an SKNode move forward, but on an angle determined by a single variable, and not a velocity determined by two, dx and dy.

Thanks in advance.


Solution

  • 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.