- Home /
Problem with Clamping Values for Object's Rotation
I'm having trouble clamping the barrel's degrees plus its parent's(the tank's hull) degrees as well so I can get the same result like it does right of the picture below.
So the script is simple it rotates the barrel(turretBarrel) with the Y_Mouse Input and rotates the upperPart(turret) of the tank with the X_Mouse Input, along with barrel stabilization. Script
//Note this.transform is the tanks hull
public Transform turret;
public Transform turretBarrel;
float xRot;
float angleY;
float rotY;
float minTurretRotY;
float maxTurretRotY;
Vector3 mRot;
Vector3 rot;
public void Update(){
xRot = Input.GetAxis("Mouse X") * 0.5f;
turret.transform.localRotation *= Quaternion.Euler(turret.transform.localRotation.x, xRot, turret.transform.localRotation.z);
angleY -= Input.GetAxisRaw("Mouse Y") * 0.5f;
angleY = Mathf.Clamp(angleY, minTurretRotY, maxTurretRotY);
mRot = turret.transform.rotation.eulerAngles;
rot = turretBarrel.transform.rotation.eulerAngles;
rotY = angleY;
rotY = Mathf.Clamp(rotY, minTurretRotY, maxTurretRotY);
// I'm using Quaternion.Euler for barrel Stabilization
turretBarrel.transform.rotation = Quaternion.Euler(new Vector3(rotY, mRot.y, mRot.z));
//Debug.Log(rotY +" | " + angleY + "/ Min : " + minTurretRotY+ " ; Max : " + (maxTurretRotY));
}
Answer by AaronXRDev · Nov 11, 2018 at 12:11 AM
In a case like this you should look at using localEulerAngles instead of rotation. localRotation and localEulerAngles both apply to the object as it exists in relation to the parent object. The standard rotation relates to the world, and can have odd results.
Try using turretBarrel.transform.localEulerAngles
@EgoAnt It kind of works but it does not rotate the turret(UpperPart) of the tank just the barrel.
I manage to make it work with "turretBarrel.transform.localEulerAngles = new Vector3(rotY, this.transform.rotation.y, this.transform.rotation.z);" How ever now the stabilization no longer works for the barrel, which is important considering thats what actual tanks have.
more or less when the hull rotates positive on the x axis and then the barrel rotates down on the x axis so it is stable which I have been having trouble with and way to do it was with "turretBarrel.transform.rotation = Quaternion.Euler(new Vector3(rotY, mRot.y, mRot.z));" because it used world space rotation. Would you know how to do this?
Can you send a picture that shows the structure of the GameObjects in the hierarchy window?