c# - 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.
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?
解决方案
您的答案似乎有很多重复的代码。我们可以清理一下
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;
}
}
这样,您就不必检查生成的射弹的标签,因为它们永远不会改变。
推荐阅读
- parameters - 如何在 PyTorch 中给出单个数字参数?
- python - Python,从列表附加到依赖于列表中的值
- wordpress - 404 错误分页在 Wordpress 中不起作用
- javascript - 生成 X、Y 着色的等距房间
- java - 输出不正确/无法进入第二个输入
- python - 如何从字符串列表中删除重复的子字符串?
- python - 如何以这种方式使用 discord.py 使用 on_message?
- deep-learning - RuntimeError: mat1 和 mat2 形状不能相乘(1x2000 和 500x128)
- c# - 如何在 Visual Studio C# 中找到源文件
- kotlin - Ktor 默认池