如何在unity中实例化左侧的玩家子弹

本文关键字:玩家 子弹 实例化 unity | 更新日期: 2023-09-27 18:05:03

在我的unity 2D游戏中,我用玩家方向实例化子弹,但是子弹在玩家的右侧实例化,我尝试在玩家的左侧实例化。这是我的播放器子弹

public Rigidbody2D playerWeapon;

void Start(){
    InvokeRepeating ("PlayerWeapon",1.0f,1.0f);
}
void PlayerWeapon()
{
        Rigidbody2D bPrefab = Instantiate (playerWeapon, new Vector3 (transform.position.x, transform.position.y, transform.position.z), Quaternion.identity) as Rigidbody2D;
}

如何在unity中实例化左侧的玩家子弹

使用transform.forward应该可以做到。你也可以使用偏移量来修改子弹从玩家的距离中产生的距离。试试下面的代码:

public Rigidbody2D playerWeapon;
void Start()
{
    InvokeRepeating("PlayerWeapon", 1.0f, 1.0f);
}
void PlayerWeapon()
{
    float offset = 5;
    Vector3 plyrPos = transform.position;
    Quaternion plyrRot = transform.rotation;
    Vector3 plyrDir = transform.forward;
    Vector3 spawnPos = plyrPos + plyrDir * offset;
    Rigidbody2D bPrefab = Instantiate(playerWeapon, spawnPos, plyrRot) as Rigidbody2D;
}

编辑:

你也可以这样做:

void PlayerWeapon()
{
    float shootSpeed = 10f;
    float offset = 5;
    Rigidbody2D bPrefab = Instantiate(playerWeapon, transform.position + (offset * transform.forward), transform.rotation) as Rigidbody2D;
    bPrefab.velocity = transform.forward * shootSpeed;
}

如果它仍然在错误的方向上,将shootSpeed的值翻转到-10,再试一次,也将offset翻转到-5