0
\$\begingroup\$

enter image description here

I'm working on a tank game where bullets are reflected off of walls. The formula for a reflection is:

$$ r=d−2d⋅n∥n∥2n $$

where \$d\$ is the incoming vector and \$n\$ is the normal of a wall.

My bullets stick to the walls and then "bounce" off at the corners; an undesirable effect. I'm honestly questioning my formula implementation at this point.

This is my current implementation:

func collision():
    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.is_in_group(globals.wall_group):
            var normal = collision.normal
            velocity = velocity - ((2 * velocity.dot(normal)) / normal.length_squared()) * normal
            rotation = velocity.angle() + PI

If I use the is_on_wall() function and simply negate the velocity this does produce a bouncing effect but not a correct one. I still need the normal.

I originally used rigid bodies as seen in the image above. But I have switched to kinematic bodies.

\$\endgroup\$
1
  • \$\begingroup\$ Correct me if I'm wrong but, is what you want any different front the built in mechanic? \$\endgroup\$
    – Kolt Penny
    Aug 18, 2020 at 8:08

1 Answer 1

0
\$\begingroup\$

I've figured out a solution:

func collision():
    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.is_in_group(globals.wall_group):
            var normal = collision.normal
            velocity = velocity - ((2 * velocity.dot(normal)) / normal.length_squared()) * normal
            rotation = velocity.angle() + PI
            return

Returning after detecting a single collision point ensures that it does not get stuck on the walls and bounces off correctly.

\$\endgroup\$
1
  • \$\begingroup\$ If this solution worked for you, remember to mark it as "accepted". \$\endgroup\$
    – DMGregory
    Sep 2, 2021 at 18:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .