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!