Search Unity

How do I make enemy switch the other way when bouncing off collider?

Discussion in '2D' started by FriedRiceAzn, May 27, 2017.

  1. FriedRiceAzn

    FriedRiceAzn

    Joined:
    May 19, 2017
    Posts:
    4
    I am trying to make a top down game where the enemy continuously moves up and down. This is my code so far.

    using UnityEngine;
    using System.Collections;

    public class EnemyRandomMovement : MonoBehaviour {


    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
    transform.position = new Vector3 (transform.position.x, transform.position.y - 0.1f, 0f);
    }
    }

    I'm actually unsure what to do now. (I'm a beginner)
    I just need the enemy to bounce off the background box collider and switch directions.
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Please use the "Insert code" option when you post code on the forums. Or use code tags. There is a pinned thread on this, for more details :)

    As for your situation, I'm pretty sure that you could put a kinematic rigidbody on your enemy (or the backgroundbox) along with a trigger collider and use the OnTriggerEnter callback to switch the enemy's direction.

    This is a tutorial on colliders as triggers: https://unity3d.com/learn/tutorials/topics/physics/colliders-triggers?playlist=17120