- Home /
How can I get my 2D enemy to rotate to look at my player?
This is the code i have so far
Vector3 dir = player.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
enemy.rotation = Quaternion.Euler(0f, 0f, rotation.z);
if (timeBtwShots <= 0)
{
//GameObject Bullet = Instantiate(projectile, Firepoint.position, Quaternion.identity);
//timeBtwShots = startTimeShots;
//Destroy(Bullet, 3f);
}
else
{
timeBtwShots -= Time.deltaTime;
}
hi @Charlie010903 , you can use look at function
Vector3 targetPos = target.transform.position;
Vector3 targetPosFlattened = new Vector3(targetPos.x, targetPos.y, 0);
transform.LookAt(targetPosFlattened);
Answer by JackhammerGaming · Apr 14, 2020 at 07:51 AM
@Charlie010903 I usually take a way to different approach the code is a bit noob like but works very well
Transform Player; Quaternion ang_Left; Quaternion ang_Right; void Start(){ ang_Left.y = 180; } void Update(){ if (Player.position.x - transform.position.x <= 0){ transform.SetPositionAndRotation(transform.position , ang_Left); } else{ transform.SetPositionAndRotation(transform.position , ang_Right); } }
for this to make sure your game object is set to y rotation at 0 and is facing right side else change the ang_Left and ang_Right variables
Answer by qobion · Apr 14, 2020 at 08:12 AM
public transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
void Update()
{
transform.LookAt(player);
}