using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
[SerializeField]
private Transform[] firePoints;
[SerializeField]
private Rigidbody projectilePrefab;
[SerializeField]
private float launchForce = 700f;
[SerializeField]
private Animator anim;
[SerializeField]
private bool automaticFire = false;
private void Start()
{
anim.SetBool("Shooting", true);
}
public void Update()
{
if (Input.GetButtonDown("Fire1") && automaticFire == false)
{
if (anim.GetBool("Shooting") == true)
{
anim.Play("SHOOTING");
LaunchProjectile();
}
}
if(automaticFire == true)
{
anim.Play("SHOOTING");
LaunchProjectile();
}
}
private void LaunchProjectile()
{
foreach (var firePoint in firePoints)
{
Rigidbody projectileInstance = Instantiate(
projectilePrefab,
firePoint.position,
firePoint.rotation);
projectileInstance.AddForce(new Vector3(0,0,1) * launchForce);
projectileInstance.gameObject.AddComponent<BulletDestruction>().Init();
}
}
}
如果是自动的:
if(automaticFire == true)
{
anim.Play("SHOOTING");
LaunchProjectile();
}
这是不停地射击,但看起来像一颗子弹。 例如,如果我希望它不间断射击但每次只发射一颗子弹?还是射出许多子弹,但它们之间有一定间隔?
在每个子弹上,我都添加了这个销毁脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletDestruction : MonoBehaviour
{
// Start is called before the first frame update
public void Init()
{
StartCoroutine(DestroyBullet());
}
IEnumerator DestroyBullet()
{
yield return new WaitForSeconds(0.2f);
Destroy(gameObject);
}
}
但这也是一个问题。如果我将销毁延迟设置为0.2,则子弹射击距离非常短,但是如果我将延迟时间设置为例如5,则子弹的射击距离会更长,但是同样会出现很多子弹在同一时间。
销毁和自动模式的逻辑是什么?而我应该如何在脚本中完成呢?
答案 0 :(得分:2)
您可以尝试以下方法:
float attackRate = 100;
float timer = 0;
public void Update()
{
timer -= Time.deltaTime;
if(automaticFire && timer <=0)
{
Shoot();
timer = 1/ attackRate;
}
}