Search code examples
c#positiontransformdistanceunity-game-engine

making a 2D GameObject react to the position of another 2D GameObject


So, my boss moves in a specific direction when it detects the player. The problem I'm having is how to get the boss to move depending on where the player is within a certain proximity. So if the boss is on the player's left, he'll move to the left. If he's on the player's right, he'll move to the right. But I can't figure out how to make him react based on distance. Right now I'm just doing a Debug.Log to save a few seconds.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class phantom : MonoBehaviour {

private Rigidbody2D rb;
private Animator anim;
public Transform Target;


void Start () 
{
    rb = GetComponent<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
}


void Update ()
{

    if (transform.position.x > Target.position.x ) {
        Debug.Log ("left");
    }
    if (transform.position.x < Target.position.x ) {
        Debug.Log ("right");
    }
}

}


Solution

  • I figured it out. I just made the function not in Update but with an OnTriggerEnterStay2d (Collider2D other). Then I placed a trigger collider on the same GameObject and only when it detects the Target (the player) does the debug come up.