- Home /
Question by
Penfwasaurus · Dec 28, 2013 at 11:32 PM ·
c#2dmovementai
Simple AI In 2D - C#
Im making a simple free roam spaceship game, and all i need is the alien to move towards me, i only know how to do this in 3d, ive sorted out the rotation bit(with help) so it always points towards me, but how can I make it move towards me, because at the movement im telling it to go foward , but our Z angles are equal?? Can i make it so that it follows my X+Y?? Just Look :
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
private Transform myTransform;
// Use this for initialization
void Awake() {
myTransform = transform;
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update () {
Vector3 dir = target.position - myTransform.position;
dir.z = 0.0f; // Only needed if objects don't share 'z' value
if (dir != Vector3.zero) {
myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
Quaternion.FromToRotation(Vector3.right, dir), rotationSpeed * Time.deltaTime);
}
//Move Towards Target
myTransform.position += myTransform.position * moveSpeed * Time.deltaTime;
}
}
Comment
Best Answer
Answer by robertbu · Dec 28, 2013 at 11:35 PM
Change line 32:
myTransform.position += (target.position - myTransform.position).normalized * moveSpeed * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Why is my character strafing around the mouse (2d) 1 Answer
Unity 2D - Basic Button Movement 1 Answer
aquarium effect for 2d fish 2 Answers
Movement Problems PS4 Controller 0 Answers