- Home /
Help with tower defense game using LookRotation
void LookAtEnemy()
{
GameObject[] enemies;
enemies = GameObject.FindGameObjectsWithTag("Enemy");
float speed = 0.05f;
foreach (GameObject enemy in enemies)
{
Vector3 enemyPos = enemy.transform.position;
enemyPos.y = transform.position.y;
Vector3 relativePos = enemyPos - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
float distance = Vector3.Distance(enemyPos, transform.position);
if (distance < range)
{
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed);
}
}
}
Here is the script which makes a turret to look at enemies. It's kind of working, but not accurate. A turret looks at enemies AND spaces between enemies. I don't want it, and I have no idea what to do. If you want more detailed information, please comment.
Answer by N-8-D-e-v · Sep 11, 2020 at 12:05 AM
when dealing with look rotation, you need to get a directional vector. So, in the line where you declare the vector3 called relativePos, change it to this
Vector3 relativePos = (enemyPos - transform.position).normalized;
This should fix it, if you have other questions or would like me to explain more then just ask!
Answer by unity_Ms0xAEdw2qrBBg · Sep 11, 2020 at 12:14 AM
Thank you very much for kind reply. I tried, however, it's not still working. Nothing has changed. I will explain more. There are 3 enemies spawning. A turret looks at the first enemy when it enters the range, and if it leaves, a turret looks the middle between the first enemy and the second enemy. Then looks at the second one, and so on. What's wrong with that?
you are using Quaternion.Slerp, which will sphereically interpolate between two rotations, meaning that to get from one rotation to another, it will have to smoothly (or not so smoothly) rotate between them, so just change transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed);
to transform.rotation = rotation
Also, when using Slerp, make sure to multiply speed by Time.deltaTime to make it frame-rate-independent
Your answer
Follow this Question
Related Questions
Smooth LookAt OnTriggerEnter for static enemies 1 Answer
Quaternion Slerp 180 Away from target 1 Answer
How to make character rotate in the direction of movement and direction of the camera? 1 Answer
Rotating gameObject to aim at target using Quaternion 1 Answer
Quaternion.Slerp() behaves weirdly when turning to look at moving object 2 Answers