I am working on a 2D game in which there is a monster type who, upon instantiation, is supposed to move slowly toward the player. As the player moves and changes direction, the enemy should change course. The player is faster than the enemy, so staying ahead of it won’t be a problem as long as the player is paying attention and there aren’t too many enemies on the board.
All of the code for the player running, jumping, etc. works just fine, but the enemy isn’t moving at all. Here is the code I have:
using UnityEngine;
using System.Collections;
public class Monster3AI : MonoBehaviour {
public Transform player;
private Vector3 playerLocation;
private float pursueSpeed = 200f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update () {
player = GetComponent<Transform>();
playerLocation = new Vector3 (player.position.x, player.position.y, player.position.z);
Debug.Log ("playerLocation: "+playerLocation);
transform.position=Vector3.MoveTowards(transform.position,playerLocation,pursueSpeed*Time.deltaTime);
}
}
This script is attached to a GameObject called Monster3 that is instantiated from time to time. In the inspector, the Player reference says “Player (Transform)”, but when I look at the Debug Log, it’s showing the location where the Monster3 object was instantiated. I know that using GetComponent() in the Update section is a big performance hit, but I was just trying to get the system to update with the latest location.
I’ve tried both MoveTowards and Lerp, but neither seems to work.
I’m sure I’m missing something obvious, but if anyone could help, I’d appreciate it!