Why is my Rigidbody2D not moving? (C#)

Hi all, I’m wondering if anyone knows what’s wrong with my script, I’ve been experimenting with this for a while, I had it half working with transform.position and a random value for both y and x in the one ‘direction’ value, but I needed to separate the x and y so I could manipulate the direction it would go when it hit the barriers (Y_Max, Y_Min etc).

Basically I need my objects to bounce off the wall realistically, so if it’s moving left and downwards when it hits the Min_Y, I need it to maintain it’s X direction but reverse it’s Y direction, and so on for the rest of the other walls.

Here is my current code, it doesn’t include my other attempts because I feel this is the closest I’ve gotten, the only issue is they don’t move anywhere even on Start().

Rigidbody2D rb;

public float xRandom;
public float yRandom;

private float xDirection;
private float yDirection;

public float Y_Min = -8f;
public float Y_Max = 8f;
public float X_Min = -8f;
public float X_Max = 8f;

void Start()
{
    rb = GetComponent<Rigidbody2D>();

    xRandom = Random.Range(-1.0f, 1.0f);
    yRandom = Random.Range(-1.0f, 1.0f);

    xDirection = xRandom;
    yDirection = yRandom;

}

void Update()
{

    rb.velocity = (new Vector2(xDirection, yDirection)) * moveSpeed * Time.deltaTime;

    if (rb.velocity.y > Y_Max)
    {
        yDirection -= yDirection;
    }

    if (rb.velocity.x > X_Max)
    {
        xDirection -= xDirection;
    }

    if (rb.velocity.y < Y_Min)
    {
        yDirection -= yDirection;
    }

    if (rb.velocity.x < X_Min)
    {
        xDirection -= xDirection;
    }
}

Thanks all, I appreciate any help you can offer!

Currently I cannot test your code, but there are a few things that seem a bit off.

Usually you wouldn’t change the velocity of a rigidbody directly, rather add a force to the rigidbody to get it to move.

You are using Random with values of -1 to 1 to get the direction, which are very small amounts and can random to a value like 0 or 0.1 which you almost won’t be able to see when applied to an object that isn’t currently moving.

You are using X_Max, X_Min, Y_Max and Y_Min as variables to store “Barriers”, but you are not comparing the rigidbody’s x and y position to them, you are comparing them to the rigidbody’s velocity, which will never be greater or smaller than your min and max values.

Also, just something small, when creating a “barrier”, test for equal as well. It is not such a big issue, just something to look out for.