- Home /
Tank urret rotation - Need help.
Hi guys,
for 3 three hours I try to rotate a tank turret now... And I only get it to smoothly look to the target. But the problem is how can I fix the Z axis of the turret after looking/slerping to the target?
Here is an example:
After this phase of rotation I want that the local rotation of the turret gets to the same level as the tank hull again. Can anyone help me please? I tried so many experiments on my own with this stupid tank :D
Here is my latest code experiment:
// The Important snippet from the Weapon.cs Script
//
// Transform weaponHolder = <turret set via inspector>
// The parent of the turret is the hull.
Vector3 direction = target.transform.position - transform.position;
Quaternion toRotation = Quaternion.LookRotation(direction);
Quaternion newRotation = Quaternion.Slerp(weaponHolder.transform.rotation, toRotation, Time.deltaTime * 1.5);
weaponHolder.rotation = newRotation;
weaponHolder.localEulerAngles = new Vector3(weaponHolder.localEulerAngles.x,
weaponHolder.localEulerAngles.y,
weaponHolder.parent.localEulerAngles.z);
Answer by robertbu · Apr 11, 2014 at 08:51 PM
Take a look at my answer here:
http://answers.unity3d.com/questions/562443/turret-slerp-rotation-and-clamping.html
You will need to open up the comments at the bottom of my answer and scroll down. The code is just below the link to a package that demonstrates the script.
Hi... Can you pls help me pls modify my code here it is
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class TurretRotater : MonoBehaviour { // e.g. 0.2 = slow, 0.8 = fast, 2 = very fast, Infinity = instant [Tooltip("If rotationSpeed == 0.5, then it takes 2 seconds to spin 180 degrees")] [SerializeField] [Range(0, 10)] float rotationSpeed = 0.5f;
[Tooltip("If isInstant == true, then rotationalSpeed == Infinity")]
[SerializeField] bool isInstant = false;
Camera _camera = null; // cached because Camera.main is slow, so we only call it once.
void Start()
{
_camera = Camera.main;
}
void Update()
{
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
Quaternion targetRotation = Quaternion.LookRotation(ray.direction);
if (isInstant)
{
transform.rotation = targetRotation;
}
else
{
Quaternion currentRotation = transform.rotation;
float angularDifference = Quaternion.Angle(currentRotation, targetRotation);
// will always be positive (or zero)
if (angularDifference > 0) transform.rotation = Quaternion.Slerp(
currentRotation,
targetRotation,
(rotationSpeed * 180 * Time.deltaTime) / angularDifference
);
else transform.rotation = targetRotation;
}
}
}