# Question How to make a turret maintain accuracy when rotating prefab

Discussion in 'Scripting' started by OutDoorsScene, Nov 25, 2022.

Joined:
Sep 9, 2022
Posts:
31
I want to create a helicopter that can maintain accuracy while flying.
Code (CSharp):
1.
2. void TrackTarget()
3. {
4.  Vector3 Relativepos = (CurrentTarget.transform.position + new Vector3(0, 2f, 0)) - this.transform.position;
5.         Quaternion rotation = Quaternion.LookRotation(Relativepos);
6.         Turret.transform.localRotation = Quaternion.Slerp(Turret.transform.localRotation, rotation, TrackingSpeed * Time.deltaTime);
7. }

2. ### orionsyndrome

Joined:
May 4, 2014
Posts:
2,173
What does "maintaining accuracy" mean?
If you mean in the context of aiming with that turret, then you definitely don't need slerp.

Joined:
Sep 9, 2022
Posts:
31
I mean keeping the turret aiming at the small GameObject. even when the helicopter is moving and rotating.

4. ### Hannibal_Leo

Joined:
Nov 5, 2012
Posts:
493
Use
``Transform.rotation``
``Transform.localRotation``
.

Joined:
Sep 9, 2022
Posts:
31
That has improved the accuracy, especially on the y axis. But it still doesn't have the precision of
``transform.LookAt``
.

Is there a way to make
``transform.LookAt``
smooth?

6. ### Hannibal_Leo

Joined:
Nov 5, 2012
Posts:
493
Yea, you calculated the wrong Vector. Also I suggest Quaternion.RotateTowards instead of Quaternion.Slerp or Quaternion.Lerp because it feels more mechanical which I think fits better for a turret.

The "Relativepos" is actually the Vector that your Turret will look at, so you have to calculate it from the position of the turret and not from the origin of the Helicopter because that will lead to an offset.
Seems like you tried correcting this with the
``+ new Vector3(0, 2f, 0)``
- this is no longer required because we are now getting the correct Vector.

Code (CSharp):
1. using UnityEngine;
2.
3. public class LookAt : MonoBehaviour
4. {
5.     public Transform CurrentTarget;
6.     public Transform Turret;
7.     public float TrackingSpeed = 100;
8.
9.     void LateUpdate()
10.     {
11.         TrackTarget();
12.     }
13.
14.     void TrackTarget()
15.     {
16.         Vector3 targetVector = CurrentTarget.position - Turret.position;
17.         Quaternion rotation = Quaternion.LookRotation(targetVector);
18.         Turret.rotation = Quaternion.RotateTowards(Turret.rotation, rotation, TrackingSpeed * Time.deltaTime);
19.
20.         Debug.DrawRay(Turret.position, Turret.forward * 1000, Color.red);
21.     }
22. }
23.

spiney199 likes this.