I’m afraid this might be more rudimentary arithmetic than programming, but vector math has me really
confused. Currently I have the following:
Vector3 currentPosition;
float currentHeading; //value clamped between 0-360
float currentSpeed; //measured in Unity Units per second
Every update, I need to move currentPosition in the direction of currentHeading at a rate of currentSpeed. I know the movement itself can be achieved by converting heading and speed into some vector newPosition, and multiplying (currentPositionnewPositionTime.deltaTime), but how do I actually convert heading and speed into a single vector?
@Sendatsu_Yoshimitsu It’s trigonometry. Assuming your heading is from up 0, right 90 degrees. You need the sin and cos functions
x = Mathf.Sin(angle * Mathf.Deg2Rad),
y = Mathf.Cos(angle * Mathf.Deg2Rad),
Vector2 movement = new Vector2(x,y) * speed * Time.deltaTime
A more Unity-style way is to use the built-ins. The first line takes an arrow pointing north (forward) and spins it around y by your angle (it handles the sin/cos math for you):
// length 1 in proper direction:
Vector3 v1 = Quaternion.Euler(0,currentHeading,0)*Vector3.forward;
// correct speed (same as last line in Downstream's example):
v1=v1*currentSpeed;
For fun, since you claim to be confused about vector math in general, I put something (almost a book, but small chapters) at Vector math and rotation notes
Given the OP has currentHeading
as a float, I’m guessing this is 2D. Here’s my solution:
// Calculate the currentHeading as a rotation about z axis
Quaternion headingRotation = Quaternion.AngleAxis(currentHeading, Vector3.forward);
// Apply that rotation to a vector scaled to the currentSpeed
Vector2 velocity = headingRotation * Vector2.up * currentSpeed;