Gameobject移动并生成预制件

时间:2015-02-01 19:36:01

标签: c# ios unity3d

我有一个向前移动的游戏对象并且每隔一秒左右产生一个预制件。唯一的问题是产卵似乎是不均匀的,有时物体相距很远,有时它们会重叠。我可以通过改变spawntime和距离来解决这个问题,但是当我在ios上测试它时它再次破裂。

我尝试创建一个脚本,将游戏对象从另一个对象中推出,但它将其推出然后对象命中,另一个对象反射出来。

我希望能够做到的是让产卵者向前移动并放置一个预制件,以便预制件不会重叠。我需要这个在ios上工作。

我认为它可能会被打破

这是生成的脚本:

using UnityEngine;
using System.Collections;

public class SpawnScript : MonoBehaviour {

    public GameObject[] obj;
    //public float spawnMin = 1;
    //public float spawnMax = 1;
    //public float spawnDistance = 0.1f;
    //private float barDisplay = 3; 
    public float timeLeft = 0.1f;  
    static bool finishTimer = false; //i made this global so you can access from other scripts 
    static bool timerStarted = false;

    //private GameObject GroundSpawner;

    // Use this for initialization
    void Start () {
        timerStarted = true;

    }

    void Update(){
        Timer ();

        transform.Translate(Vector3.forward * 0.1f);


    }

    void Timer(){

        if (timerStarted == true) {         
            timeLeft -= Time.deltaTime;          
            if (timeLeft <= 0.0f) {        
                Spawn ();
                timerStarted = false;
            }
        }
    }

    void Spawn(){
        //GroundSpawner = GameObject.Find ("Ground Spawner");

        //if (GroundSpawner.transform.position) {
                    //Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
                    Invoke ("Spawn", 1.75f);

                    Instantiate (obj [Random.Range (0, obj.Length)], transform.position, Quaternion.identity);

        //  }
    }
}

这是推出另一个游戏对象脚本的理由:

using UnityEngine;
using System.Collections;

public class GroundHittingSelf : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

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

    }

    void OnCollisionEnter(Collision other) {
        Debug.Log("Hitting Ground without tag");
        if (other.gameObject.tag == "Ground") {
            //transform.position += new Vector3(0, 0, 0.1f);
            Debug.Log("Hitting Ground with tag");

        }
    }
}

1 个答案:

答案 0 :(得分:1)

实例化预制件之间的不均匀空间来自于SpawnScript的游戏对象随着速度的变化而移动。

这是因为您在transform.Translate函数中使用Update更改了排名,而没有考虑deltatime。 Update会在一秒钟内被调用多次,因为运行代码的计算机可以调用它。例如,如果计算机正在执行某些后台工作,则Update的调用次数会减少。在这种情况下,gameObject将减速。或者更糟糕的是,如果在不同的机器上运行相同的代码,它将快得多/慢。

可以通过考虑deltatime来解决这个问题:

transform.Translate(Vector3.forward * Time.deltaTime * 3.0f);

Deltatime通常是非常小的数字,因此需要再次设置常量。例如,如果你有30fps的速度,那么3.0f就是那个,因为3.0f *(1.0f / 30.0f)= 0.1f

相关问题