卡在 Unity 中的生成对象

本文关键字:对象 Unity 卡在 | 更新日期: 2023-09-27 18:34:22

我正在Unity中制作一个'运行'游戏,我正在制作一个带有球的原型,该球有其他球跟随他。如果追随者击中了一个物体,他们会在一段时间后被摧毁。为了不让你用完敌人,我制作了一个触发器,可以生成新的敌人。在代码中,这是函数Addzombies

  1. 如果我现在运行它们,我如何使它们不在同一点上生成从彼此开始,然后像爆炸一样弹跳。
  2. 如何在空中开始一些,我试过了,但他们没有产卵。

我的代码:

using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
    public float InputForce;
    public GUIText guiText;
    public float rotationHorizontal;
    public AudioClip ACeffect2;
    public GameObject zombiePrefab;
    void FixedUpdate() {
        rigidbody.AddForce( Camera.main.transform.right * Input.GetAxis("Horizontal") * InputForce);
        rigidbody.AddForce( Camera.main.transform.forward * Input.GetAxis("Vertical") * InputForce);
        transform.position += Vector3.forward *InputForce * Time.deltaTime;
        rotationHorizontal = Input.GetAxis("Horizontal") * InputForce;
        rotationHorizontal *= Time.deltaTime;
        rigidbody.AddRelativeTorque (Vector3.back * rotationHorizontal);
    }
    void OnCollisionEnter(Collision col){
        if (col.gameObject.name == "Zombie") {
            Debug.Log ("Player geraakt, nu ben je eigenlijk dood");
        }
        if (col.gameObject.name == "Obstakel1") {
            Debug.Log ("Obstakel1 geraakt");
            audio.PlayOneShot(ACeffect2);
            InputForce = 0;
        }
        if (col.gameObject.name == "Obstakel2") {
            Debug.Log ("Obstakel2 geraakt");
        }
    }
    void AddZombies(int aantal){
        for (int i = 0; i < aantal; i++){
            GameObject go = GameObject.Instantiate(zombiePrefab, transform.position - new Vector3(0, 0, 7 + i),Quaternion.identity) as GameObject;
            Zombie zb = go.GetComponent<Zombie>();
            zb.target = gameObject.transform;
        }
    }
    void OnTriggerEnter(Collider col) {
        Debug.Log ("Enter" +col.name);
        if (col.tag == "AddZombies"){
            AddZombies(4);
        }
    }
    void OnTriggerExit(Collider col) {
        Debug.Log ("Leaving with" +col.name);
    }
}

卡在 Unity 中的生成对象

我会就如何做事提供建议,但您必须进行更改以使其适合您的要求

public Transform zombiePrefab; // From the editor drag and drop your prefab

void addZombies()
{   
    // as you need them to be not on the same point
    int randomX = Random.Range(-10.0F, 10.0F);
    for (int i = 0; i < aantal; i++){
        // make a transform
        var zombieTransform = Instantiate(zombiePrefab) as Transform; 
        zombieTransform.position = new Vector3(randomX, 0, 7 + i);
        transform.GetComponent<Rigidbody>().enabled = false;            
        // make it enable when you need and add force to make them fall     
    }
} 

我建议传递要传递的僵尸数量,以及一个表示它们可以生成的空间范围的整数。然后只需使用UnityEngine.Random为每个僵尸提供上述整数,即可生成几个不同的坐标来生成僵尸。

至于让它们在空中生成,只需在实例化僵尸时增加 y 坐标即可。