- Home /
Issue with object not bouncing around screen correctly
I am creating a game where squares bounce around the screen maintaining the same velocity. Currently, they are bouncing around just fine with my code, however, if it collides exactly at a corner, the square doesn't bounce back.
Here is my code:
public class BasicEnemy : MonoBehaviour
{
public float speedX;
public float speedY;
private Rigidbody2D rb;
public Vector2 lastVelocity;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speedX, speedY);
}
// Update is called once per frame
void Update()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "LeftWall" || collision.gameObject.tag == "RightWall")
{
rb.velocity = new Vector2(lastVelocity.x * -1f, lastVelocity.y);
} else if (collision.gameObject.tag == "BottomWall" || collision.gameObject.tag == "TopWall")
{
rb.velocity = new Vector2(lastVelocity.x, lastVelocity.y * -1f);
}
}
}
Answer by JMasterBoi · Jul 22, 2020 at 09:01 PM
because you are using rb.velocity = new Vector2(lastVelocity.x * -1f, lastVelocity.y);
to change direction it takes a second to apply the force the other way.
EDIT: I am not completely sure of this
I was using this code before to bounce my object around the screen. It still did the same thing:
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
rb.velocity = direction * $$anonymous$$athf.$$anonymous$$ax(speed, 0f);
Your answer
Follow this Question
Related Questions
Best way to manually calculate collision between GameObjects and a Tilemap without using physics 1 Answer
Setting a Prefab Clone as the Child of another Object on Collision (2D) 1 Answer
How can I make walls with Collider2D components for a top-down game in Unity 2018? 1 Answer
2D Custom Bouncing Diagonal 0 Answers