我使用Unity 3D引擎制作2D游戏。我想创造无休止的重复地形。我让它无缝重复,除了有时两个地形会立刻产卵的事实。它是随机发生的,没有任何正当理由。有什么帮助吗?
这是我的地形重生代码:
using UnityEngine;
using System.Collections;
using PlayerPrefs = GamePlayerPrefs;
public class SelfTerrainSpawn : MonoBehaviour {
// terrain references
public GameObject first;
public GameObject second;
public GameObject third;
public GameObject fourth;
public GameObject fifth;
public GameObject sixth;
public GameObject seventh;
public float spawnXPos = 0.0f;
public float respawnCoordinate = 30.4f;
public float respawnTriggerCoordinate = -21.7f;
public bool canSpawn = true;
public bool starting = true;
public float random;
void Start() {
this.gameObject.transform.position = new Vector2 (0.0f, 31.4f);
this.gameObject.transform.eulerAngles = new Vector3 (0, 0, 90.0f);
}
void Update()
{
// if the camera is farther than the number last position minus 16 terrain is spawned
// a lesser number may make the terrain 'pop' into the scene too early
// showing the player the terrain spawning which would be unwanted
if (this.gameObject.transform.position.y <= respawnTriggerCoordinate && canSpawn)
{
// turn off spawning until ready to spawn again
random = Random.Range(0,18);
SpawnTerrain (random);
canSpawn = false;
}
if (this.gameObject.transform.position.y <= respawnTriggerCoordinate - 10) {
Destroy (this.gameObject);
}
}
void SpawnTerrain(float rand) {
if ((rand == 0)) {
Instantiate (first, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 1) && (rand <= 4)) {
Instantiate (second, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 5) && (rand <= 8)) {
Instantiate (third, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 9) && (rand <= 10)) {
Instantiate (fourth, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 10) && (rand <= 13)) {
Instantiate (fifth, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 13) && (rand <= 15)) {
Instantiate (sixth, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
if ((rand >= 15) && (rand <= 18)) {
Instantiate (seventh, new Vector3 (respawnCoordinate, spawnXPos, 0), Quaternion.Euler (0, 0, 0));
}
}
}
此脚本附加到游戏内部的第一个地形部分:
Click here to see an image of the game screen
它还附加在另外两个预制件上。这些预制件中的每一个都有一个脚本,可以慢慢地将它们向下移动到屏幕上。基本上,当一个人的顶部到达相机的顶部时,另一个应该在相机上方产生。然后它向下移动并重复。看到我使用了canSpawn变量来确保它只产生一次。然而,随机地,两个地形会相互叠加。有人能帮我解决这个问题吗?
答案 0 :(得分:2)
当rand
为10,13或15时,您将生成两个地形,因为您的范围检查会重叠这些值。