- Home /
How do you make enemies rotate to your position in 2d
Hi I am trying to make it so enemies move toward the player in 2d. I already made them able to move but I do not know how to make it so they turn around to face me. Heres what I have so far: private GameObject Player; public Transform target; public float speed = 3f;
void Start()
{
Player = GameObject.Find("Player"); // target
}
void Update()
{
//move towards player
if (Vector3.Distance(transform.position, target.position) > 1f)
{
transform.position = Vector2.MoveTowards(transform.position, Player.transform.position, speed * Time.deltaTime);
}
}
Answer by sean244 · Jan 20, 2019 at 01:14 AM
Here’s the script:
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform target;
public float speed = 3f;
private void Update()
{
if (Vector3.Distance(transform.position, target.position) > 1f)
{
MoveTowardsTarget();
RotateTowardsTarget();
}
}
private void MoveTowardsTarget()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
private void RotateTowardsTarget()
{
var offset = 90f;
Vector2 direction = target.position - transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
}
}
Good point. I dunno why I referenced the player twice. But thanks so much for the answer!
Your welcome. Keep in $$anonymous$$d that at the very beginning, the enemy will instantly snap to the right rotation. If you don't like this, you can have it more smoothly rotate towards it instead. Just create a float called 'rotationSpeed' and replace
transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
with these two lines
Quaternion rotation = Quaternion.AngleAxis(angle + offset, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
I want you to know sir, that you, yes you, are a god among men. I spent HOURS trying to make a fireball rotate in the direction of its path. You saved my night.
Why did you need to normalize? And this variable angle, what calculation does it return?
Answer by tormentoarmagedoom · Jan 20, 2019 at 12:46 AM
Good day.
Did you tried transform.LookAt() ?
Yeah so I just tried adding transform.LookAt(target) to my script and the weirdest thing happens: all of my enemies disappear and fall off the map. $$anonymous$$ust be a glitch with unity
Did u set the correct target? I dont belive its a glitch.
Since is a 2d game, i guess that u are using 2d sprites, if u rotate a sprite 90 degres he desapers, because we dosen't pcupe space in the z axis, like a plan
Your answer
Follow this Question
Related Questions
Follower Airplane problem 1 Answer
Enemy Rotation AI 0 Answers
How do i get this guy to hold his position? 3 Answers
Unity AI Obstacle Avoidance Help 3 Answers