I am pretty new to unity but i have a basic FPS game made, when holding a gun, i would like to make it so when your player turns, the item in hands rotates to show turning. For example, when playing call of duty, the gun rotates when you rotate your character. This is the code i have but it is not working

    void Update(){
    this.rotateEquppedOnTurn();
}
private void rotateEquppedOnTurn(){
    if(this.equippedItem != null){
        InteractEquppableItem equip = this.equippedItem.gameObject.GetComponent<Interaction>() as InteractEquppableItem;
        if(equip.rotatesWhenTurn){
            float rotX = Input.GetAxis("Mouse X");
            float rotY = Input.GetAxis("Mouse Y");
            Quaternion tempRot = new Quaternion();
            Quaternion tempCam = GameObject.Find("PlayerCamera").transform.rotation;
            tempRot.x = tempCam.x + rotX;
            tempRot.y = tempCam.y + rotY;
            tempRot.z = tempCam.z;
            this.equippedItem.gameObject.transform.rotation = tempRot;
        }
    }
}

when turning the character with this code, the gun just rotates in a weird way, its not quite what i expected from the rotation script

有帮助吗?

解决方案

  1. Quaternions are not vectors.
  2. I suggest you start by watching the vector tutorial on Unity's web site.
  3. The last bit of the tutorial goes over what cross products are and why you would use them - specifically, you can use them to obtain a relative axis around which you may want to rotate something.

其他提示

Don't directly assign rotation like this.

this.equippedItem.gameObject.transform.rotation = tempRot;

instead of that use something like this

this.equippedItem.gameObject.transform.Rotate(new Vector3(x,y,z));

you can derive x,y,z using mouse motion

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top