Random movement in a direction

I’ve been trying to make a simple bouncing simulation. I decided on this code

public class Randmove : MonoBehaviour
{
    public Rigidbody2D RB;
    public Vector2 Velo = new Vector2(0, 0);
    public BoxCollider2D MainColl;
    public float offset;

    // Start is called before the first frame update
    void Start()
    {
        RB = GetComponent<Rigidbody2D>();

    

        MainColl = GetComponent<BoxCollider2D>();


        offset = Random.Range(-1.5f, 1.5f);
   
        Velo.x = offset * Velo.x;
        Velo.y = offset * Velo.y;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        RB.velocity = Velo * Time.deltaTime;

     

     
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (MainColl != null)
        {
          if(collision.gameObject.tag == "VerticalBound")
            {
                Velo.y = Velo.y * -1;
                Debug.Log("Hit ON y");

            }else if(collision.gameObject.tag == "HorizontalBound")
            {
                Velo.x = Velo.x * -1;

                Debug.Log("hit on x");

            }
       

        }
    }

}

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

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.

1 Like