I’m working on a top-down movement script, I have the desired heading as a float in absolute degrees (0.0f should always go towards the top of the screen, 180.0f should go straight down), and likewise I have the desired speed as a float.
Is there anything in the API that would translate my heading in degrees to a Vector2, so I could apply both settings by calling something like RigidBody2.AddForce(headingAsVector * speed)?
First, the formula you used is for when the angle is measured anti-clockwise from the positive direction of the x axis. For your way of measuring the angle, you’d need to swap the trig functions over.
Second, the trig functions need the angle in radians.
I always like my function names to be fully descriptive so I don’t accidentally misuse them. So I’ve also renamed it…
void Update() {
// Clamp it to prevent any potential errors
heading = Mathf.Clamp(heading, 0f, 180f);
// Offset it by 90 degrees and invert it to go from 0d...180d heading to 90d...-90d angle
headingRadians = (heading - 90f) * -1 * Mathf.Deg2Rad;
headingToVector = new Vector2 (Mathf.Cos (headingRadians),
Mathf.Sin (headingRadians));
myRigidBody2D.AddForce (headingToVector * speed);
}