How Do I Have An Enemy Bounce Off Walls?

Hi. I am working on a game where I have these enemies that move horizontally. I want them to go in the opposite direction of that they were going each time they hit a wall. I’ve tried all ways I can think of doing this, but none seem to work. Any ideas?

Thanks,

  • Chris

What have you tried so far? (how it doesnt work?)

How the enemies are moved? Is it 2D, 3D?

I am using UnityScript. I’ve tried setting a pair of boolean variables named canMoveRight and canMoveLeft in the script attached to the enemies. canMoveRight is set to true from the start, while canMoveLeft is false. In the OnCollisionEnter2D function, when the enemy collides with a wall, it will set canMoveRight to false and change canMoveLeft to true.

That is where I get stuck. For the first collision with a wall, it will set canMoveLeft to true, but with the next collision, I want to set canMoveRight back to true.

Think of it like Pong. The ball bounces off the walls. That’s basically what I’m trying to do here.

Everything is in 2D, so 2D Colliders and 2D Rigidbodies.

Do you need a flag? On collision just reverse their velocity ?

basically when the enemy collides just do
speed.x *= -1
Not sure how you’re storing the current speed but this should give you the basic idea.

If you’re totally set on using the boolean system that you described. just do

canMoveRight = !canMoveRight;
canMoveLeft = !canMoveLeft;

it’s worth noting that if canMoveRight and canMoveLeft are always opposite, there’s not much point in having both