# Move sprite in the direction its facing when pressing key

So i have the sprite rotating based on the position of the mouse with this code:

``````void Update () {
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}
``````

Now how do i get the sprite to move in the direction its facing whenever i press a key, such as W, in order to get it to move around?

Iâ€™d have a look at some of the unity 2D platformer tutorials to get a handle on how that movement systems works, then modify it so instead of using Axis, you look out for the key you care about. You already have the direction of the object to your mouse, so iâ€™d store that direction in your game object script in a global variable. Your movement script could just apply a force using that direction?

The reason iâ€™ve suggested the 2D platformer tutorial is when i ran through it myself there was code that also aided in making the player stop when the key was released. If you were making an asteroid style game, you can ignore that part of the code if you want the player to float away.

It looks like your sprite is rotating to face the Y axis towards the mouse.

So you can move him towards his local Y axis using transform.up.

``````public float speed;

void Update() {
if(Input.GetKey(KeyCode.W)) {
transform.Translate(Vector2.up * speed * Time.deltaTime, Space.Self);
// or
transform.Translate(Vector2.up * speed * Time.deltaTime, transform);
// or
transform.Translate(transform.up * speed * Time.deltaTime);
// or
transform.position += transform.up * speed * Time.deltaTime;
}
}
``````

I believe all those options in Update will do the same thing, and Iâ€™m sure there are even more ways. They all move the object relative to the local axis directions.

It is important to note that â€śtransform.Translateâ€ť is powerful because it can move something relative to anything else in one step. You could supply any transform into the â€śrelativeToâ€ť parameter (in the second option i pass this objectâ€™s transform), and the object will move based on that objectâ€™s local axes.

1 Like