Want to try this Exercise?
Start a free 7-day trial today. It's quick - and you can cancel anytime.
Watch course trailer Start your Free TrialCreating a Fixed Turret
Rules of the Exercise
-
1Allow rotation of turret along base and aiming of the barrels up and down with a clamped range of 40 degrees total
-
2Rotate barrels quickly only while holding down left click
-
3Apply force to nearby Rigidbody objects using a Raycast
Creating Stationary Weapons
Submissions
How To
void BaseRotation () { moveX += Input.GetAxis("Mouse X") * speed; moveX = Mathf.Clamp(moveX,-20,20); baseRotation = Quaternion.Euler(0,moveX,0); turretBase.rotation = Quaternion.Lerp(turretBase.rotation, baseRotation,1f); } void BarrelRotation () { moveY -= Input.GetAxis("Mouse Y") * speed; moveY = Mathf.Clamp(moveY,-20,20); barrelRotation = Quaternion.Euler(0,moveX,moveY); turretBarrels.rotation = Quaternion.Lerp(turretBarrels.rotation,barrelRotation,1f); }
By using Mathf.Clamp we can designate a range of motion for the base and the barrels. Both methods are nearly identical but using different inputs and axes to rotate around.
The second rule was to rotate the barrels while holding down left click. This is done by referencing the x axis of the barrels then using transform.Rotate. See the code snippet down below:
public Transform barrels; barrels.Rotate(Vector3.right, 20f);
Lastly we also wanted to apply a force to objects within line of sight of the turret barrels while holding down left click to mimic the effect of a minigun firing at these objects. We used a Raycast for this, take a look down below to see how this was done:
void Detection () { Debug.DrawRay(barrelTip.position, barrelTip.forward * rayDistance, Color.green); RaycastHit hit; if(Physics.Raycast(barrelTip.position, barrelTip.forward, out hit, rayDistance, rayMask)) { if(hit.rigidbody != null) { hit.rigidbody.AddForceAtPosition(barrelTip.forward * appliedForce, hit.point); } } }
We check to see if the object we hit has a rigidbody, if it does then we can apply a force at the impact point of where the raycast hit. Any additional mechanics added in the exercise are optional. Take a look at the completed project files in the downloads tab for full code and assets.