unity3d 如何射击鼠标按钮?

kx7yvsdv  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(133)

我试图做我的第一个platformer在统一。并有一些问题的弹丸。我发现了一个教程,如何创建一个弹丸移动,但没有触发器上的消防按钮。这是可能的,以改变这个脚本上的消防按钮?我试图使它与如果语句,但然后弹丸移动只有一个,它不飞:(

public class projectile : MonoBehaviour
{
    public GameObject player;
    public GameObject target;

    private float playerX;
    private float targetX;

    private float dist;
    private float nextX;
    private float baseY;
    private float height;

    public float speed = 10f; 

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        target = GameObject.FindGameObjectWithTag("Enemy");
    }

    void Update()
    {  
       Fire();           
    }

    public static Quaternion LookAtTarget(Vector2 rotation)
    {
        return Quaternion.Euler(0, 0, Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg); 
    }

    private void Fire()
    {       
        playerX = player.transform.position.x;
        targetX = target.transform.position.x;

        dist = targetX - playerX;
        nextX = Mathf.MoveTowards(transform.position.x, targetX, speed * Time.deltaTime);
        baseY = Mathf.Lerp(player.transform.position.y, target.transform.position.y, (nextX - playerX) / dist);
        height = 2 * (nextX - playerX) * (nextX - targetX) / (-0.25f * dist * dist);

        Vector3 movePosition = new Vector3(nextX, baseY + height, transform.position.z);
        transform.rotation = LookAtTarget(movePosition - transform.position);

        if (transform.position == target.transform.position)
        {
              Destroy(gameObject);
            
        }
    }
}
dgiusagp

dgiusagp1#

Update方法中的内容在每一帧都会发生,因此需要创建一个手动触发器(bool isFired)。
其思想是,当isFired为假时,什么也不发生;当isFired变为真时,抛射体开始运动。
您的Fire方法实际上使投射物移动,因此您应该将其重命名为Move,而在Update中,您只在投射物发射时才调用Move

public class projectile : MonoBehaviour
{
    // At the start, the projectile is not fired
    bool isFired = false;

    void Update()
    {
        // If the player presses a button, the projectile is fired
        if (Input.GetMouseButtonDown(0)) isFired = true;
        // Only if the projectile is fired, it should moves
        if (isFired) Move();
    }

    void Move()
    {
        // Here you have the content of your Fire method
    }
}

相关问题