How do you make a bullet ricochet off a vertical wall?

Posted by Bagofsheep on Game Development See other posts from Game Development or by Bagofsheep
Published on 2014-04-17T15:31:54Z Indexed on 2014/06/03 3:44 UTC
Read the original article Hit count: 206

Filed under:
|
|
|
|

First things first. I am using C# with XNA. My game is top-down and the player can shoot bullets. I've managed to get the bullets to ricochet correctly off horizontal walls. Yet, despite using similar methods (e.g. http://stackoverflow.com/questions/3203952/mirroring-an-angle) and reading other answered questions about this subject I have not been able to get the bullets to ricochet off a vertical wall correctly. Any method I've tried has failed and sometimes made ricocheting off a horizontal wall buggy.

Here is the collision code that calls the ricochet method:

//Loop through returned tile rectangles from quad tree to test for wall collision. If a collision occurs perform collision logic.
for (int r = 0; r < returnObjects.Count; r++)
    if (Bullets[i].BoundingRectangle.Intersects(returnObjects[r]))
        Bullets[i].doCollision(returnObjects[r]);

Now here is the code for the doCollision method.

    public void doCollision(Rectangle surface)
    {
        if (Ricochet) doRicochet(surface);
        else Trash = true;
    }

Finally, here is the code for the doRicochet method.

    public void doRicochet(Rectangle surface)
    {
        if (Position.X > surface.Left && Position.X < surface.Right)
        {
            //Mirror the bullet's angle.
            Rotation = -1 * Rotation;
            //Moves the bullet in the direction of its rotation by given amount.
            moveFaceDirection(Sprite.Width * BulletScale.X);
        }
        else if (Position.Y > surface.Top && Position.Y < surface.Bottom)
        {
        }
    }

Since I am only dealing with vertical and horizontal walls at the moment, the if statements simply determine if the object is colliding from the right or left, or from the top or bottom. If the object's X position is within the boundaries of the tile's X boundaries (left and right sides), it must be colliding from the top, and vice verse. As you can see, the else if statement is empty and is where the correct code needs to go.

© Game Development or respective owner

Related posts about XNA

Related posts about c#