I have this script for development in 3D.
the enemy follows the player, but it does not work well for a 2d game.
How do you change in 2d so that the enemy follows the player, using the x-axis?
script:
using UnityEngine;
using System.Collections;
public class EnemyInseguePlayer : MonoBehaviour {
public Transform player;
public float playerDistance;
public float rotationSpeed;
public float moveSpeed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
playerDistance = Vector3.Distance (player.position, transform.position);
if(playerDistance < 15f)
{
LookAtPlayer ();
}
if(playerDistance < 12f)
{
chase ();
}
}
void LookAtPlayer()
{
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationSpeed);
}
void chase()
{
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
}
If it has to be restrained to the X-axis with code, try making a new Vector2 to specify the position, then plug that into the MoveTowards. Make sure your playerXAxis is being updated frequently. Just tested this and it works for me.