首页 > 解决方案 > How to shoot multiple bullets at the same time in different directions?

问题描述

I'd like to know how could I shoot multiple bullets in diffent directions at the same time?

I have this gameobject as you can see in the image below, and it has 4 spawn points which spaws the bullets.

this image

So when this gameobject is hit by a specific enemy, it shoots at the four directions at the same time. I've already tried something like this, but it's not working. I'm pretty new at Unity. This script is attached to this gameobject.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DanoCruz : MonoBehaviour
{
    public float Damage = 1f;

    public GameObject Projetil;
    public GameObject SpawnProjetil1;
    public GameObject SpawnProjetil2;
    public GameObject SpawnProjetil3;
    public GameObject SpawnProjetil4;

    public float ProjetVelocity = 1f;


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.transform.tag == "projetil")
        {
          GameObject tiro = Instantiate(Projetil,SpawnProjetil1.transform.position,SpawnProjetil1.transform.rotation);// it spawns on the left

            tiro = Instantiate(Projetil, SpawnProjetil2.transform.position, SpawnProjetil2.transform.rotation);// it spawns on the right
            tiro = Instantiate(Projetil, SpawnProjetil3.transform.position, SpawnProjetil3.transform.rotation);// it spawns behind
            tiro = Instantiate(Projetil, SpawnProjetil4.transform.position, SpawnProjetil4.transform.rotation);// it spawns in the front

            Destroy(other.gameObject);

        }
    }
}

The bullets don't move. How could I solve it?

标签: c#unity3d

解决方案


您的答案似乎有很多重复的代码。我们可以清理一下

if (other.transform.tag == "projetil")
{
    List<GameObject> tiros = new List<GameObject>
    {
        Instantiate(Projetil, SpawnProjetil1.transform.position, SpawnProjetil1.transform.rotation),
        Instantiate(Projetil, SpawnProjetil2.transform.position, SpawnProjetil2.transform.rotation),
        Instantiate(Projetil, SpawnProjetil3.transform.position, SpawnProjetil3.transform.rotation),
        Instantiate(Projetil, SpawnProjetil4.transform.position, SpawnProjetil4.transform.rotation),
    };

    foreach (GameObject tiro in tiros)
    {
        Rigidbody rigiProj = tiro.GetComponent<Rigidbody>();
        rigiProj.velocity = tiro.transform.forward * ProjetVelocity * Time.deltaTime;
    }
}

这样,您就不必检查生成的射弹的标签,因为它们永远不会改变。


推荐阅读