Ok, after much trial and error, I finally have a working turret that tracks targets and has a limited turn rate.
What I’d like to do now, is find a way to give some turrets gimbal limits. Either defined as a simple degree cone, or by limiting each axis individually. But I’m not sure how to tackle this.
Here is the working tracking script.
For testing purposes, the target is hard-coded, and the turret only tracks when that target is selected. If the target isn’t selected, the turret tracks back to face forward.
I tried taking AngleAxis and euler formats and converting them to Quaternions to be able to compare them, and vice versa, but I keep getting mismatched objects errors or somesuch.
If it matters, this script is on the parent object (a vehicle) and the turret it a child of the vehicle.
var aimspeed : float;
private var mytarget : GameObject;
mytarget = gameObject.Find("Vehicle1");
private var turret : GameObject;
turret = this.gameObject.Find("Turret");
private var rotation;
function Update () {
if(Scene1.selected == mytarget) {
rotation = Quaternion.LookRotation(mytarget.transform.position - turret.transform.position);
// add gimbal limit test here
} else {
rotation = Quaternion.identity;
}
turret.transform.rotation = Quaternion.RotateTowards(turret.transform.rotation, rotation, aimspeed * Time.deltaTime);
}
This basically fixes the turret angle on the y-axis after the fact using eulerAngles.
The ** line was a beginning attempt to try and limit the rotation of the turret only in the y-axis (it doesn’t seem to use z). The idea being, another part of the turret (an elevator hinge or something) can track in the x-axis by using the same formula but setting y=0 instead. So between the two parts collectively the gun is then pointed at the target.
Doing this has some weird effects though. Some of these things seem to have to do with parent scaling - I’m going to have to start using actual models instead of stretched/scaled primitives.
Still, this seems like a workaround. Is there an easy way to do RotateTowards but limiting the axes affected?
For mh turrets I used the base of the turrets forward vector then checked my enemy position vector in relation to turret forward to get an angle… if it was above my max… turret stops at max and loses target otherwise rotate toward target.
Well, back when I was working in ActionScript I had a complete turret aiming function, but I had to do a lot of messing around with trig.
My feeling was that working in quaternions would yield significantly faster code. Also, it looked like RotateTowards was basically a built-in function to make things easier. The problem is that I don’t know enough about quaternions or Unity to make this happen yet.
If there’s a simple way to do something like RotateTowards on a single axis, this would pretty much solve all my problems at one.