I am trying to make a Player GameObject bounce off of another object with a tag “Obstacle”.
- Player: Dynamic 2D Rigidbody + Circle Collider 2D
- Obstacle: Tilemap Collider 2D
- Collision is detected, however the velocity doesn’t seem to change.
Issue: The Player GameObject doesn’t seem to bounce off. I tried placing print statement that shows the velocity of the rigidbody at the start and end of the OnCollisionEnter2D method, but they both show (0.00, 0.00).
What could I possibly be doing wrong?
Here’s my code in the PlayerMove Script:
Start
void Start(){ rb = gameObject.GetComponent<Rigidbody2D>();}
FixedUpdate
private void FixedUpdate(){
rb.MovePosition(rb.position + moveDir * playerStats.PLAYERSPEED * Time.fixedDeltaTime);
}
OnCollisionEnter2D
private void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.CompareTag("Obstacle")) {
//print rb.velocity #1
float _speed = rb.velocity.magnitude;
Vector2 _objectNormal = other.contacts[0].normal.normalized;
moveDir = Vector2.Reflect(rb.velocity, _objectNormal);
rb.velocity = moveDir * _speed;
//print rb.velocity #2
}
}