[英]Unity2D C# Randomly Spawn GameObject in an Area over another GameObject
我是Unity2D(Unity 5.0.2f1)的新手,并且一直在寻找一个解决方案,我敢肯定它正盯着我!
我有一个游戏对象(基本上是一条道路),如下所示(DirtTrack1):
我有一个生成GameObjects(车辆)的生成器。 我想在这条路上产生那些车辆。
我尝试使用以下代码来执行此操作,实际上是通过获取道路的底部Y坐标和顶部Y坐标来尝试在道路的Y轴区域内生成车辆。我可以放置车辆的最大垂直位置:
void FixedUpdate() {
// Repeat spawning after the period spawn
// route has finished.
if (!_inSpawningIteration)
StartCoroutine (SpawnVehiclePeriodically());
}
IEnumerator SpawnVehiclePeriodically()
{
// First, get the height of the vehicle and road.
float vehicleHeightHalf = vehiclePreFab.GetComponent<SpriteRenderer>().bounds.size.y / 2f;
float roadHeightHalf = roadObject.GetComponent<SpriteRenderer>().bounds.size.y / 2f;
float roadTopY = roadObject.transform.position.y + roadHeightHalf;
float roadBottomY = roadObject.transform.position.y - roadHeightHalf;
// Next, ensure that maxY is within bounds of this farm vehicle.
roadMaxY = roadTopY - vehicleHeightHalf;
roadMinY = roadBottomY + vehicleHeightHalf;
// Set the position and spawn.
Vector3 newPosition = new Vector3 (Const_RoadItemsPositionX, randomY, 0f);
GameObject vehicle = (GameObject)GameObject.Instantiate (vehiclePreFab, newPosition, Quaternion.identity);
}
这确实是随机产生的,但多数情况下始终不在道路本身内。 它要么在道路上,要么在道路的外部。
我无法弄清楚我在做什么错,但是我敢肯定这很简单!
您正在使用localPosition
。 从文档 :
变换相对于父变换的位置。
如果变换没有父对象,则与
Transform.position
相同。
观察场景,您的道路上有一个父对象,并且您获得的相对位置可能会弄混汽车的生成位置。
勾选车辆的运动学检查,如果不这样做,物理学可能会将其移出道路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.