Quantcast
Channel: Answers for "Make the turret automatically rotate to look at where the crosshair is aimed at."
Viewing all articles
Browse latest Browse all 4

Answer by DarthDisembowel

$
0
0
Here's some C# code I use for spaceship turrets. I feel this could be simplified a bit but I was never able to get it to work without saving the local rotation and reapplying them to the axes I don't want to rotate. Works no matter how the vehicle is oriented. The barrels need to be a child of the rotating turret base. The script is a component of the turret base. This code is in the update function (I declare all the variables beforehand to reduce garbage collection). The turret will traverse on the local Y-axis, and the barrels will pitch on the local X-axis. //rotate turret tmpRotation = transform.localRotation; //preserves the local rotation since we only want to rotate on local Y axis leadTargetPosition = FirstOrderIntercept(transform.position,Vector3.zero,laserParticleLeft.particleEmitter.localVelocity.z,target.transform.position,target.rigidbody.velocity); targetPointTurret = (leadTargetPosition - transform.position).normalized; //get normalized vector toward target targetRotationTurret = Quaternion.LookRotation (targetPointTurret, parent.transform.up); //get a rotation for the turret that looks toward the target transform.rotation = Quaternion.Slerp(transform.rotation, targetRotationTurret, Time.deltaTime * turnSpeed); //gradually turn towards the target at the specified turnSpeed transform.localRotation = Quaternion.Euler( tmpRotation.eulerAngles.x, transform.localRotation.eulerAngles.y, tmpRotation.eulerAngles.z); //reset x and z rotations and only rotates the y on its local axis //rotate barrels tmpRotation = barrels.transform.localRotation; //preserves the local rotation since we only want to rotate on local x axis targetPointBarrels = (leadTargetPosition - barrels.transform.position).normalized; //get a normalized vector towards the target targetRotationBarrels = Quaternion.LookRotation (targetPointBarrels, parent.transform.up); //get a rotation that looks at the target barrels.transform.rotation = Quaternion.Slerp(barrels.transform.rotation, targetRotationBarrels, Time.deltaTime * turnSpeed); //gradually turn towards the target as the specified turnSpeed barrels.transform.localRotation = Quaternion.Euler( barrels.transform.localRotation.eulerAngles.x, tmpRotation.eulerAngles.y, tmpRotation.eulerAngles.z); //reset y and z rotations and only rotates the x on its local axis

Viewing all articles
Browse latest Browse all 4

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>