c# - 尝试在半随机位置一遍又一遍地生成预制件
问题描述
所以我编写了这段代码,试图开始制作一个脚本,在我的场景中随机生成灌木对象,但是在运行时它只会产生第一个灌木。这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BushSpawner : MonoBehaviour
{
public GameObject bush;
private float x = 0f;
private float y = -.47f;
private float z = 0f;
private int bushCount = 0;
private Vector3 origPos;
private bool xPlus = false;
private bool xMinus = false;
private bool zPlus = false;
private bool zMinus = false;
// Use this for initialization
void Start()
{
SpawnBushes();
}
// Update is called once per frame
void Update()
{
}
void SpawnBushes()
{
Vector3 startPos = new Vector3(x, y, z);
Instantiate(bush, startPos, Quaternion.identity);
bushCount += 1;
while (bushCount < 100)
{
Vector3 checkPos = new Vector3(x, y, z);
Collider[] intersecting = Physics.OverlapSphere(checkPos, 1f);
if (intersecting.Length == 0)
{
//code to run if nothing is intersecting as the length is 0
Instantiate(bush, checkPos, Quaternion.identity);
bushCount += 1;
}
else
{
//code to run if something is intersecting it
RollPos();
}
}
}
void RollPos()
{
if (xPlus == true
&& xMinus == true
&& zPlus == true
&& zMinus == true)
{
int newRoll = Random.Range(1, 4);
if (newRoll == 1)
{
x += 10f;
}
else if (newRoll == 2)
{
x -= 10f;
}
else if (newRoll == 3)
{
z += 10f;
}
else if (newRoll == 4)
{
z -= 10f;
}
xPlus = false;
xMinus = false;
zPlus = false;
zMinus = false;
}
else
{
int roll = Random.Range(1, 4);
if (roll == 1)
{
if (xPlus == false)
{
x += 2f;
xPlus = true;
}
else
{
RollPos();
}
}
if (roll == 2)
{
if (xMinus == false)
{
x -= 2f;
xMinus = true;
}
else
{
RollPos();
}
}
if (roll == 3)
{
if (zPlus == false)
{
z += 2f;
zPlus = true;
}
else
{
RollPos();
}
}
if (roll == 4)
{
if (zMinus == false)
{
z -= 2f;
zMinus = true;
}
else
{
RollPos();
}
}
}
}
}
我尝试将 SpawnBushes 放入 Update 以在 bool 为真时运行,然后在 SpawnBushes 完成时使其为假,但这会创建第一个灌木,然后在它旁边的一个随机位置创建 99 个其他灌木。
如果有人能指出我正确的方向或告诉我我完全不在基地,我将非常感激!
解决方案
Ron Beyer 指出我在 RollPos() 中的 Random.Range 中没有足够大的范围。再次感谢罗恩!
推荐阅读
- android - 为什么 android:background="@null" 在应用 pro-guard 规则时导致问题?
- google-api - 使用 Google API 的页面令牌无效 - 状态 400
- c++ - 不可移动的 C++17 唯一指针
- xamarin - Xamarin android 以 px 为单位获取屏幕大小
- sql-server - 使用存储过程删除与记录关联的行
- javascript - 如何在星期几同时添加连字符
- android - 如何在android中将drawable设置为位图?
- python - 如何在 Python 中绘制 e^(-t^2) 从 x=0 到 x=3 的积分?
- php - Get total permissions from users & roles belongsToMany
- hyperledger-fabric - 如何在超级账本结构中检索数据库?