Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How Do I Have An Enemy Bounce Off Walls?

Discussion in 'Scripting' started by Blue Bean Apps, Feb 23, 2015.

  1. Blue Bean Apps

    Blue Bean Apps

    Joined:
    Aug 10, 2014
    Posts:
    261
    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
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,937
    What have you tried so far? (how it doesnt work?)

    How the enemies are moved? Is it 2D, 3D?
     
  3. Blue Bean Apps

    Blue Bean Apps

    Joined:
    Aug 10, 2014
    Posts:
    261
    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.
     
  4. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
    Do you need a flag? On collision just reverse their velocity ?
     
  5. TheValar

    TheValar

    Joined:
    Nov 12, 2012
    Posts:
    760
    basically when the enemy collides just do
    Code (CSharp):
    1. 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
    Code (CSharp):
    1. canMoveRight = !canMoveRight;
    2. canMoveLeft = !canMoveLeft;
    it's worth noting that if canMoveRight and canMoveLeft are always opposite, there's not much point in having both