简体   繁体   中英

Problem with Clamping Values for Object's Rotation - Unity C#

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));
}

在此处输入图片说明

You need to change the min and max Y according to the Y rotation of the main body(tank) also. Update like this:

minY = YRotationOfParent;
maxY = YRotationOfParent + someOffSet;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM