简体   繁体   English

拍摄延迟(Unity和C#)

[英]Delay in shoot (Unity and C#)

I am making shooting in Unity, what I want is to make a little delay, for example: to be able to shoot in every 0.5 seconds. 我正在Unity中进行拍摄,我想要做些延迟,例如:能够每0.5秒拍摄一次。 Check the script, I want my bullet prefab to appear (instantiate) after 0.5 sec delay. 检查脚本,我希望我的子弹预制件在0.5秒的延迟后出现(实例化)。

private Rigidbody2D rb2d;
private float h = 0.0f;
public float Speed;
public Transform firePoint;
public GameObject bulletPrefab;


    // Start is called before the first frame update
void Start()
{
    rb2d = GetComponent<Rigidbody2D>();

}

// Update is called once per frame
void Update()
{
    h = Input.GetAxisRaw("Horizontal");
    if (h != 0.0f)
    {
        rb2d.velocity = new Vector2(h * Speed, rb2d.velocity.y);
    }
    if (h == 0.0f)
    {
        rb2d.velocity = new Vector2(0, rb2d.velocity.y);

    }

    if (Input.GetKeyDown(KeyCode.Space))
    {
        Shoot();
    }
}


void Shoot()
{
    Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}

This should take you in the right direction, of course, this is only one of the ways to do it. 当然,这应该带您正确的方向,但这只是实现此目标的方法之一。

You can change fireDelay to change the rate of fire. 您可以更改fireDelay来更改射速。

private Rigidbody2D rb2d;
private float h = 0.0f;
public float Speed;
public Transform firePoint;
public GameObject bulletPrefab;

float fireElapsedTime = 0;
public float fireDelay = 0.2f;


    // Start is called before the first frame update
void Start()
{
    rb2d = GetComponent<Rigidbody2D>();

}

// Update is called once per frame
void Update()
{
    h = Input.GetAxisRaw("Horizontal");
    if (h != 0.0f)
    {
        rb2d.velocity = new Vector2(h * Speed, rb2d.velocity.y);
    }
    if (h == 0.0f)
    {
        rb2d.velocity = new Vector2(0, rb2d.velocity.y);

    }

    fireElapsedTime += Time.deltaTime;

    if (Input.GetKeyDown(KeyCode.Space) && fireElapsedTime >= fireDelay)
    {
        fireElapsedTime = 0;
        Shoot();
    }
}


void Shoot()
{
    Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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