unity场景中使用Cube随机生成多段墙壁障碍,创建模型Sphere, 使用鼠标设置目标点,Sphere避开Cube到达目标位置代码
时间: 2024-04-11 11:28:41 浏览: 166
unity 场景
下面是一个示例代码,用于在Unity场景中使用Cube随机生成多段墙壁障碍,创建模型Sphere,并使用鼠标设置目标点,使Sphere避开Cube到达目标位置:
```csharp
using UnityEngine;
public class CubeGenerator : MonoBehaviour
{
public GameObject cubePrefab;
public int cubeCount = 10;
public Vector3 minSize = new Vector3(1f, 1f, 1f);
public Vector3 maxSize = new Vector3(3f, 3f, 3f);
public Vector3 minPosition = new Vector3(-5f, 0f, -5f);
public Vector3 maxPosition = new Vector3(5f, 0f, 5f);
private void Start()
{
GenerateCubes();
}
private void GenerateCubes()
{
for (int i = 0; i < cubeCount; i++)
{
GameObject cube = Instantiate(cubePrefab);
cube.transform.position = GetRandomPosition();
cube.transform.localScale = GetRandomSize();
}
}
private Vector3 GetRandomPosition()
{
float x = Random.Range(minPosition.x, maxPosition.x);
float y = Random.Range(minPosition.y, maxPosition.y);
float z = Random.Range(minPosition.z, maxPosition.z);
return new Vector3(x, y, z);
}
private Vector3 GetRandomSize()
{
float x = Random.Range(minSize.x, maxSize.x);
float y = Random.Range(minSize.y, maxSize.y);
float z = Random.Range(minSize.z, maxSize.z);
return new Vector3(x, y, z);
}
}
public class SphereMovement : MonoBehaviour
{
public Transform target;
public float avoidanceForce = 5f;
public float rayDistance = 2f;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
SetTargetPosition();
}
AvoidObstacles();
}
private void SetTargetPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
target.position = hit.point;
}
}
private void AvoidObstacles()
{
Vector3 desiredVelocity = (target.position - transform.position).normalized;
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, rayDistance))
{
Vector3 avoidanceDirection = Vector3.Reflect(transform.forward, hit.normal);
desiredVelocity += avoidanceDirection * avoidanceForce;
}
rb.velocity = desiredVelocity;
}
}
```
在Unity中,创建一个空的GameObject,并将`CubeGenerator`脚本和`SphereMovement`脚本分别附加到该GameObject上。然后,指定Cube的预制体(cubePrefab)、生成的Cube数量(cubeCount)、Cube的最小和最大尺寸(minSize和maxSize)、以及Cube的最小和最大位置(minPosition和maxPosition)。
还需要在场景中创建一个Sphere对象,并将`SphereMovement`脚本附加到该对象上。设置避让力(avoidanceForce)和射线距离(rayDistance)。
运行场景后,你可以使用鼠标点击场景中的位置,设置Sphere的目标点。Sphere将会避开Cube墙壁障碍物,通过射线检测来调整移动方向,以到达目标位置。
希望这个示例对你有所帮助!
阅读全文