# Question Random movement in a direction

Discussion in 'Physics' started by Sandyea, Nov 28, 2023.

1. ### Sandyea

Joined:
Jul 13, 2023
Posts:
1
I've been trying to make a simple bouncing simulation. I decided on this code
Code (CSharp):
1.
2. public class Randmove : MonoBehaviour
3. {
4.     public Rigidbody2D RB;
5.     public Vector2 Velo = new Vector2(0, 0);
6.     public BoxCollider2D MainColl;
7.     public float offset;
8.
9.     // Start is called before the first frame update
10.     void Start()
11.     {
12.         RB = GetComponent<Rigidbody2D>();
13.
14.
15.
16.         MainColl = GetComponent<BoxCollider2D>();
17.
18.
19.         offset = Random.Range(-1.5f, 1.5f);
20.
21.         Velo.x = offset * Velo.x;
22.         Velo.y = offset * Velo.y;
23.     }
24.
25.     // Update is called once per frame
26.     void FixedUpdate()
27.     {
28.         RB.velocity = Velo * Time.deltaTime;
29.
30.
31.
32.
33.     }
34.
35.     private void OnCollisionEnter2D(Collision2D collision)
36.     {
37.         if (MainColl != null)
38.         {
39.           if(collision.gameObject.tag == "VerticalBound")
40.             {
41.                 Velo.y = Velo.y * -1;
42.                 Debug.Log("Hit ON y");
43.
44.             }else if(collision.gameObject.tag == "HorizontalBound")
45.             {
46.                 Velo.x = Velo.x * -1;
47.
48.                 Debug.Log("hit on x");
49.
50.             }
51.
52.
53.         }
54.     }
55.
56. }
57.
this does work its just that it doesn't stay at a constant speed each load. so if there is any way to do that, I would like to know

### Unity Technologies

Joined:
May 24, 2013
Posts:
11,450
You’re not setting a constant speed. Speed is the magnitude of velocity so when you choose a direction to move, this needs to be normalized and scaled to the speed you want, to give you the resultant velocity.

Sandyea likes this.