Unity中如何让物体在高地(山丘、山地)生成?
仅在山谷与低地区域生成物体的资源生成实现
我制作的场景包含山脉、山谷与山丘,需要实现物体仅在山谷及低地区域生成,无法在山丘上生成,以下是对应的Unity实现代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResourceGenerator : MonoBehaviour { [Header("生成设置")] public GameObject resourcePrefab; public float spawnChance; [Header("射线检测设置")] public float distanceBetweenCheck; public float heightOfCheck = 1000f, rangeOfCheck = 30f; public LayerMask layerMask; public Vector2 positivePosition, negativePosition; private void Start() { SpawnResources(); } void SpawnResources() { for(float x = negativePosition.x; x < positivePosition.x; x += distanceBetweenCheck) { for(float z = negativePosition.y; z < positivePosition.y; z += distanceBetweenCheck) { RaycastHit hit; if(Physics.Raycast(new Vector3(x, heightOfCheck, z), Vector3.down, out hit, rangeOfCheck, layerMask)) { if(spawnChance > Random.Range(0f, 101f)) { Instantiate(resourcePrefab, hit.point, Quaternion.Euler(new Vector3(0, Random.Range(0, 360), 0)), transform); } } } } } }
内容的提问来源于stack exchange,提问作者Florens Kosicek
相关产品推荐
相关产品推荐

