make a tracking turrent in unity in csharp

Here's a basic example of how to create a tracking turret in Unity:

  1. First, create a new empty game object in the hierarchy and name it "Turret".

  2. Add a 3D model of your turret to the Turret game object, and position it at the location where you want your turret to start.

  3. Add a script to the Turret game object (or create a new script if you haven't already) in C#.

  4. In the script, create a public variable for the target object (usually the player) and a public variable for the turret's rotation speed.

main.cs
public GameObject target;
public float rotationSpeed = 5.0f;
61 chars
3 lines
  1. In the Update() function, get the direction from your turret to your target, and calculate the angle between the turret's forward vector and that direction.
main.cs
Vector3 targetDir = target.transform.position - transform.position;
float angle = Vector3.Angle(targetDir, transform.forward);
127 chars
3 lines
  1. Create a Quaternion using the Quaternion.LookRotation() function to point your turret at the target.
main.cs
Quaternion targetRotation = Quaternion.LookRotation(targetDir);
64 chars
2 lines
  1. Use Quaternion.Slerp() to smoothly rotate your turret towards the target.
main.cs
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
107 chars
2 lines
  1. Save the script and attach it to the Turret game object in the Inspector.

Now your turret will track the target object smoothly in 3D space!

gistlibby LogSnag