Version: 5.3 (switch to 5.4b)
IdiomaEnglish
  • C#
  • JS

Idioma de script

Selecciona tu lenguaje de programación favorito. Todos los fragmentos de código serán mostrados en este lenguaje.

NavMesh.SamplePosition

Sugiere un cambio

¡Éxito!

Gracias por ayudarnos a mejorar la calidad de la documentación de Unity. A pesar de que no podemos aceptar todas las sugerencias, leemos cada cambio propuesto por nuestros usuarios y actualizaremos los que sean aplicables.

Cerrar

No se puedo enviar

Por alguna razón su cambio sugerido no pudo ser enviado. Por favor <a>intente nuevamente</a> en unos minutos. Gracias por tomarse un tiempo para ayudarnos a mejorar la calidad de la documentación de Unity.

Cerrar

Cancelar

Cambiar al Manual
public static function SamplePosition(sourcePosition: Vector3, out hit: NavMeshHit, maxDistance: float, areaMask: int): bool;
public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask);

Parámetros

sourcePosition The origin of the sample query.
hit Holds the properties of the resulting location.
maxDistance Sample within this distance from sourcePosition.
areaMask A mask specifying which NavMesh areas are allowed when finding the nearest point.

Valor de retorno

bool True if a nearest point is found.

Descripción

Finds the closest point on NavMesh within specified range.

The function samples the NavMesh to find the closest point on the NavMesh.

The closest point is returned based on distance to the query point. The function does not check for obstruction in the world. For example, you the sourcePosition is on the ceiling, a point on the second floor will be returned (if there is NavMesh there), instead of floor position on the first floor.

The function can get quite expensive if the search radius is really big. A good starting point for the maxDistance is 2 times the agent height.

If you are trying to find a random point on the NavMesh, it is better to use recommended radius and do try multiple times instead of using one very large radius.


        
// RandomPointOnNavMesh.cs
using UnityEngine;
using System.Collections;
public class RandomPointOnNavMesh : MonoBehaviour {
	public float range = 10.0f;
	bool RandomPoint(Vector3 center, float range, out Vector3 result) {
		for (int i = 0; i < 30; i++) {
			Vector3 randomPoint = center + Random.insideUnitSphere * range;
			NavMeshHit hit;
			if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas)) {
				result = hit.position;
				return true;
			}
		}
		result = Vector3.zero;
		return false;
	}
	void Update() {
		Vector3 point;
		if (RandomPoint(transform.position, range, out point)) {
			Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
		}
	}
}