This site uses strictly necessary cookies. More Information

X# How do I convert speed and heading to a vector?

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 (currentPosition*newPosition*Time.deltaTime), but how do I actually convert heading and speed into a single vector?

**Answer** by Downstream
·
Oct 23, 2016 at 12:26 PM

@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

Ooh, thank you very much! To confirm, once I have the movement vector, I would apply it with Vector3.Scale(), right? Like the following?

Vector3 vesselPosition = Vector3.Scale(vesselPosition, movement);

That's what I'm doing in update right now, what ends up happening is the X and Y values quickly lerp back to 0 regardless of heading or speed.

**Answer** by Owen-Reynolds
·
Oct 23, 2016 at 04:03 PM

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 taxesforcatses.com/vectorW/TOC.html

**Answer** by paul-masri-stone
·
Feb 16 at 10:26 PM

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;
```

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.