Your best bet is to have local-only float
variables to represent traverse and elevation, then change and clamp those floats, and finally drive .localRotation
of the parts on their correct Transform axis.
Turret aiming/rotating:
I just did this a few weeks ago for a gun turret system in my Jetpack Kurt Space Flight game, which is getting more combat mode targets.
This is the aiming portion (it’s a partial class):
You should call StartAimer() from Start()
You should call UpdateAiming() from Update()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public partial class TurretBrainAndTargeter
{
// Feel free to make these public, drag them in using the Editor,
// then remember to …
Notes on clamping rotations and NOT using .eulerAngles because of gimbal lock:
Generally never read / write to / from eulerAngles.
The reason is gimbal lock.
Instead track your own float variable that is the heading, adjust and clamp that variable, then “drive” the camera’s rotation each frame.
declare a variable float heading;
adjust it when conditions warrant:
if (conditionToTurn)
{
heading += AdjustmentWhateverYouWant;
}
clamp it
heading = Mathf.Clamp( heading, minimum, maximum);
drive the rotation to the camera transform:
cameraTransform.localRotation = Quaterion.Euler( 0, heading, 0);
How to instantly see gimbal lock for yourself:
Pretty sure this is gimbal lock. To see what I mean:
put a cube in a blank scene
using the inspector, independently rotate it a little bit around x, y, z - works as expected
now set x rotation to 90
try rotate around y and z - note that z works identically to y rotation! You can no longer rotate z!
In the context of your game, I’m not sure what the best solution would be, but there’s a few possibilities. Check out some youtube tutorials on changing gravity controllers…
All about Euler angles and rotations, by StarManta:
https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html
1 Like