Im trying to rotate my enemy to point towards the player and then move in that direction. This is a 2 d project.
Im trying to work this code below with no luck. Can you help me? what is the trick im missing.
using UnityEngine;
using System.Collections;
public class MoveEnemyTowardsPlayer : MonoBehaviour {
public Transform Tplayer;
public GameObject Player;
public float velocity = 1.0f;
// Update is called once per frame
void FixedUpdate ()
{
transform.Translate(Vector2.MoveTowards (Tplayer.transform.position, transform.position,1.0f) * velocity * Time.deltaTime);
}
}
so i’m assuming you already know how to move towards the target using MoveTowards… and you can rotate your enemy facing to the player using this script that I found in google
var dir = (target.position - transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Debug.Log(Mathf.Atan2(dir.y, dir.x));
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
just adjust the angle by increasing or decreasing the variable if you have the problem with the facing direction.
Hope this helps
It seems that code above is old code thats not supported anymore.
What kind of variable is dir, and angle. They need a type correct?
This is where im at and i have multiple errors that i dont quite understand.
using UnityEngine;
using System.Collections;
public class MoveEnemyTowardsPlayer : MonoBehaviour {
public Transform Tplayer;
public Transform dir;
void Start ()
{
dir = (Tplayer.position - transform.position);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Debug.Log(Mathf.Atan2(dir.y, dir.x));
}
// Update is called once per frame
void FixedUpdate ()
{
transform.rotation = Quaternion.AngleAxis(angle, Vector2.forward);
}
}
No, it’s just var… just variable in C#… var can be any type of data type.
And don’t change the Vector3.forward to Vector2.forward because there is no z axis in Vector2
Try to make a method for you behaviour object like this :
void Update(){
LookAtObject();
}
void LookAtObject(){
var dir = (target.position - transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Debug.Log(Mathf.Atan2(dir.y, dir.x));
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}