# How can I change the direction of movement each time a key is pressed?

I would like change randomly the movement of an object every time I press Q.

It seems like the code should be like this, but it does not change the direction of movement as expected:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class translate_random : MonoBehaviour {

public float moveSpeed = 5f;

void Update () {

transform.Translate ( Time.deltaTime * moveSpeed, Time.deltaTime * moveSpeed,Time.deltaTime * moveSpeed);

if (Input.GetKeyDown (KeyCode.Q)) {

int random_trajectory_x = Random.Range (-10, 10);
int random_trajectory_y = Random.Range (-10, 10);
int random_trajectory_z = Random.Range (-10, 10);

//aucun effet:la nouvelle transformation n'est pas appliquée
//no effect: the new transformation is not applied.
transform.Translate(
random_trajectory_x*Time.deltaTime * moveSpeed,
random_trajectory_y*Time.deltaTime * moveSpeed,
random_trajectory_z*Time.deltaTime * moveSpeed
);
}
}
}

• What do you mean with "it does not work"? What exactly do you expect this script to do and what does it do instead? What error messages do you find in the Unity console? And can you translate the comments in your code to English? – Philipp Apr 11 '19 at 16:02

Remember that Update() is called once each frame your game runs. Each time Update() is run, it's a completely separate operation from the last run. It has no memory or persistent state beyond what you save explicitly in variables.

So if you want Update() to remember your randomly-generated direction to keep moving in that direction next frame, and the frame after, then you need to save that information and read it to decide which way to move.

Here, we'll make a Vector3 variable called direction to store the direction of travel. We'll make it a unit vector (always length 1), so our speed of movement is always exactly the value we provided via the speed field, and we don't speed up or slow down based on our random selection.

public class RandomMover : MonoBehaviour {
public float speed = 5f;
Vector3 direction;

void Start() {
direction = (Vector3.one).normalized;
}

void Update() {
if(Input.GetKeyDown(KeyCode.Q))
direction = Random.onUnitSphere;

transform.Translate(direction * speed * Time.deltaTime)
}
}