Я создаю стрелку сверху вниз и пытаюсь вести непрерывный огонь, чтобы пули следовали за перекрестием.
Я использовал метод непрерывного огня из игры космических захватчиков, над которой я работал, используя corountines. ,я также использую rewired для отображения моего контроллера.
public class PlayerController : MonoBehaviour
{
[SerializeField] float moveSpeed = 1;
[SerializeField] float bulletSpeed = 1;
[SerializeField] float fireRate = 1;
public int playerId = 0;
public GameObject crossHair;
public GameObject arrowPrefab;
private Player player;
Coroutine firingCoroutine;
private void Awake()
{
player = ReInput.players.GetPlayer(playerId);
}
void Start()
{
}
void Update()
{
Vector3 movement = new Vector3(Input.GetAxis("MoveHorizontal"), Input.GetAxis("MoveVertical"), 0.0f);
AimAndShoot();
transform.position = transform.position + movement * moveSpeed * Time.deltaTime;
}
private void AimAndShoot()
{
Vector3 aim = new Vector3(player.GetAxis("AimHorizontal"), player.GetAxis("AimVertical"), 0.0f);
//Vector2 shootingDirection = new Vector2(player.GetAxis("AimHorizontal"), player.GetAxis("AimVertical"));
if (aim.magnitude > 0.0f)
{
aim.Normalize(); //makes the crosshair move 1 unit from player
aim *= 0.4f; // moves the crosshair closer to player.
crossHair.transform.localPosition = aim;
crossHair.SetActive(true);
Fire();
}
else
{
crossHair.SetActive(false);
}
}
private void Fire()
{
if (player.GetButtonDown("Fire"))
{
if (firingCoroutine == null)
{
firingCoroutine = StartCoroutine(FireContinuously());
}
}
if (player.GetButtonUp("Fire"))
{
if (firingCoroutine != null)
{
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
}
IEnumerator FireContinuously()
{
Vector2 shootingDirection = new Vector2(player.GetAxis("AimHorizontal"), player.GetAxis("AimVertical"));
while (true)
{
GameObject arrow = Instantiate(arrowPrefab, transform.position, Quaternion.identity); // create/bullet/at player/no rotation
arrow.GetComponent<Rigidbody2D>().velocity = shootingDirection * bulletSpeed;
arrow.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(shootingDirection.y, shootingDirection.x) * Mathf.Rad2Deg);
// AudioSource.PlayClipAtPoint(shootSFX, Camera.main.transform.position, shootSFXVolume);
yield return new WaitForSeconds(fireRate);
Destroy(arrow, 1.5f);
}
}
IEnumerator FireRate()
{
yield return new WaitForSeconds(0.5f);
}
}
Проблема, с которой я сталкиваюсь, заключается в том, что когда я удерживаю спусковой крючок, он непрерывно стреляет в направлении, на которое я изначально нацелился, пока я не отпущу спусковой механизм. Пули / стрелы не стреляют в следующую точку, к которой я стремлюсь, если я не отпущу курок и не выстрелю снова.