Unity 2D上下鼠标面对武器旋转问题

时间:2018-10-17 01:11:14

标签: unity3d 2d game-development topdown

我正在制作一个自上而下的2D射击游戏,但确实遇到了麻烦。 关键是,每当玩家旋转时,玩家的枪口都会产生怪异的旋转。

我将播放器设置为面对鼠标位置。玩家枪不在子画面的中心。 枪是PlayerHand的预制件,而PlayerHand是Player的子代。 我尝试了很多事情,但仍然找不到解决方法。

public class HandHolder : MonoBehaviour 
{

    [SerializeField] Gun gun;
    [SerializeField] float offsetX;
    [SerializeField] float offsetY = 0.01f;
    Gun playerGun;

    void Awake () 
    {
        playerGun = Instantiate(gun,transform.localPosition,transform.localRotation) as Gun;
    }

    // Update is called once per frame
    void Update () 
    {
        playerGun.transform.position = new Vector3(transform.position.x + offsetX,transform.position.y + offsetY);
        playerGun.transform.rotation = transform.rotation;
        playerGun.Shooting();
    }
}

    void Update() 
    {

        if (!isLocalPlayer)
            return;
        Vector3 position = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * 20f;
        transform.position += position;
        FaceMouse();
    }

    public void FaceMouse() 
    {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        mousePosition.Normalize();
        float rotation_z = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
    }

以下是屏幕截图。我的播放器已经有枪的纹理。但这只是纹理。每当我旋转时,我都希望Gun预制件完全位于Player Sprite枪上。

The issue on screen

2 个答案:

答案 0 :(得分:1)

为您的播放器添加一个空白,将其命名为gunTransform。标记GunTransform,确保前进轴(蓝色)面向玩家的前进方向。

Class Level变量-

Transform guntransform;

Awake()中:

guntransform=this.GameObject.FindObjectWithTag("GunTransform").getComponent<Transform>();

然后代替

playerGun = Instantiate(gun, transform.localPosition, transform.localRotation) as Gun;

致电

playerGun = Instantiate(gun, guntransform.position, guntransform.rotation) as Gun;

答案 1 :(得分:-1)

您尝试过吗:

playerGun.transform.forward = playerHand.tranform.forward;

代替此:

playerGun.transform.rotation = transform.rotation;