Unity,C# - 随机化产生的预制件之间的差距,但不允许它们接触?

时间:2016-06-23 02:21:41

标签: c# random unity3d

好吧,在我的游戏中,我有一个Runner对象,向左移动平台。我成功地在距离最后一个平台半随机距离的地方生成一个随机平台预制件。

我通过在平台上产生一个随机距离间距来实现这一点,该距离是自上一个平台产生以来物体移动的距离。

rebased

public GameObject[] spawnableObjects; private GameObject prefab; private float spacing; // spawns every 2 units/metres public float minY, maxY, minGap, maxGap; private float oldX = 0; // previous camera position private float newX = 0; // current camera position private float distanceTravelled = 0; private Vector3 spawnPos; public Transform player; // getting camera reference public Transform spawnPt; private float currentY, lastY, currentX, lastX; void Start() { //set beginning y pos GameEventManager.GameStart += GameStart; GameEventManager.GameOver += GameOver; spacing = 20; //random between length of last prefab and max gap? lastY = 0; lastX = spawnPt.localPosition.x; //first spawn x pos } void Update () { //Debug.Log (distanceTravelled); newX = player.transform.localPosition.x; distanceTravelled += newX - oldX; // if you are goint to the right // if you're going to the left, do this instead: // distanceTravelled += oldX - newX; oldX = newX; // this is very important if (distanceTravelled >= spacing) { distanceTravelled = 0; spawnNewObject (); } } void spawnNewObject () { // code to spawn. Use the newX + some X offset while declaring your new object's position. int rand = Random.Range (0, spawnableObjects.Length); prefab = spawnableObjects[rand]; currentY = lastY + Random.Range(minY, maxY); currentX = lastX + (prefab.transform.localScale.x + 5f); //randomize 5, 5 is gap spawnPos = new Vector3((spawnPt.localPosition.x), currentY,0f); //Debug.Log ("new x:"+currentX); Instantiate (prefab, spawnPos, Quaternion.identity); lastY = currentY; lastX = currentX; spacing = Random.Range (prefab.transform.localScale.x+3, prefab.transform.localScale.x+5); Debug.Log("spawn now!! spacing="+spacing); } 游戏对象以与Runner相同的加速度/速度移动,因此看起来平台正朝着Runner移动。

出于某种原因,spawnpt是当前正在生成的预制件的长度+ 3或+4,因此平台几乎从不接触。

我在做长度的想法是,如果新平台是从空Random.Range (prefab.transform.localScale.x+3, prefab.transform.localScale.x+5);产生的,如果间距至少是当前预制件的长度,他们就不会触摸。

显然,我的逻辑中存在某些缺陷,就好像我只是触摸了spawnPt.localPosition.x平台一样。我需要一种新方法。

如何让我随机选择的预制件产品与其自身和产生的最后一个预制件之间的随机GAP?我已经尝试了包括物理领域在内的所有内容(不想走那条路)但是不能创造一个我可以改变的差距。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

尝试重叠球体(未经测试):

if (!Physics.CheckSphere(spawnPosition, objectRadius)) {
    //instantiate object
}

objectRadius是对象无法在另一个

中实例化的球面半径

你也可以拥有一个Random.insideUnitSphere:

spawnPosition = previous.transform.position + Random.insideUnitSphere * spawnRadius;

我认为这样可行。