Search code examples
c#unity-game-enginegame-development2d-games

Why is the bullet ricocheting at different speeds every time it touches a wall?


I am making a game in Unity 2D and i wanted the bullet the player shoots from his gun to bounce after it hits a wall. The script i made for the bullet is this:

public float speed = 40f;
public Rigidbody2D rb;

private Vector2 direction;
public void Start()
{
    rb.velocity = transform.right * speed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
    Vector2 inNormal = collision.contacts[0].normal;
    direction = Vector2.Reflect(rb.velocity, inNormal);

    rb.velocity = direction * speed;
}

I put a 2D physics material on the colliders which has 1.15 friction and 0.1 bounciness to make the ball bounce (as it wouldn't bounce before without the material) but now the ball bounces off the wall with a different speed every time I shoot it. Sometimes the speed of the bullet is so high it passes through the wall and that is not intended at all. Instead I wanted the ball to bounce with the same speed from wall to wall, but I don't know how to fix this problem. Can someone help me?


Solution

  • You don't need this onCollision part of code to have it bounce, thats a point of having rigidbody, collider and material. unity does calculations for you.

    Make bullet dynamic body, if it moves too fast to detect colision change Collision detection" in Rigidbody(on wall but perhapsalso on bullet) from discrete to continous. And it should bounce. If angle and speed is always the same result will also always be the same. I suspect you have wieird results becouse you are ovverriding actual colision.