Hi all,
Been struggling with this one for a while and was hoping someone may have an answer. Using a Turret Rotation script that is working great for my 3d Space Project. I have several turrets on the player ship and when the player selects a target each turret turns towards the target, using a raycast to establish a line of sight. Here is the issue, when the line of sight is broken I would like the turret to return to its 0 position and 0 rotation so that its facing forward on the ship. With this being a 3d space game and the ship being all over the place this has turned out to be quite a challenge with my turret models ending up inside the ship or other rather awkward positions. :(. Ive tried using Quaternion.Idenity and other tranform.position, and transform.rotation ways but none seem to help.
Here is the turret rotation code I have;
void Update ()
{
//If theres a target lets rotate the gun to the target
if (target != null)
{
RaycastHit hit;
if (Physics.Raycast(this.transform.position, target.position - this.transform.position, out hit) && hit.transform.tag != "Player")
{
float distanceToPlane = Vector3.Dot(trans.up, target.position - trans.position);
Vector3 planePoint = target.position - trans.up * distanceToPlane;
qTurret = Quaternion.LookRotation(planePoint - trans.position, transform.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTurret, turretDegreesPerSecond * Time.deltaTime);
Vector3 v3 = new Vector3(0.0f, distanceToPlane, (planePoint - transform.position).magnitude);
qGun = Quaternion.LookRotation(v3);
if (Quaternion.Angle(qGunStart, qGun) <= maxGunAngle)
{
gun.localRotation = Quaternion.RotateTowards(gun.localRotation, qGun, gunDegreesPerSecond * Time.deltaTime);
}
else
{
//If the gun goes beyond max angle
gun.localRotation = Quaternion.RotateTowards(gun.localRotation, qGunStart, gunDegreesPerSecond * Time.deltaTime);
}
lineofsight = true;
}
else
{
//If raycast is broken
lineofsight = false;
gun.localRotation = Quaternion.RotateTowards(gun.localRotation, qGunStart, gunDegreesPerSecond * Time.deltaTime);
}
}
else
{
gun.localRotation = Quaternion.RotateTowards(gun.localRotation, qGunStart, gunDegreesPerSecond * Time.deltaTime);
lineofsight = false;
}
}