Задержка в съемке (Unity и C #) - PullRequest
1 голос
/ 08 мая 2019

Я делаю стрельбу в 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);
}

1 Ответ

2 голосов
/ 08 мая 2019

Это должно привести вас в правильном направлении, конечно, это только один из способов сделать это.

Вы можете изменить 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);
}
...