【问题标题】:Delay in shoot (Unity and C#)拍摄延迟(Unity 和 C#)
【发布时间】:2019-05-09 02:50:47
【问题描述】:

我正在Unity中进行拍摄,我想要的是做一点延迟,例如:能够每0.5秒拍摄一次。检查脚本,我希望我的子弹预制件在 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);
}

【问题讨论】:

标签: c# unity3d game-development


【解决方案1】:

这应该会带你走向正确的方向,当然,这只是其中一种方法。

您可以更改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);
}

【讨论】:

  • 谢谢,没问题。你能给我解释一下 fireElapsedTime 和 fireDelay 变量的作用吗?我是 Unity 和编程新手。
  • 当然 @jolskey , fireElapsedTime 跟踪距离玩家上次开火已经过去了多少时间,fireDelay 是玩家可以再次开火之前的时间量。通过增加/减少延迟,您可以分别减少/增加射速。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
相关资源
最近更新 更多