Vector2.Distance
Declaration
public static float Distance(Vector2 a, Vector2 b);Параметры
| Параметр | Описание |
|---|---|
| a | Первая позиция для сравнения расстояния. |
| b | Вторая позиция для сравнения расстояния. |
Возвращаемое значение
поплавок Расстояние между двумя позициями, как абсолютное (положительное) значение.
Описание
Возвращает расстояние между a и b.
Расстояние между двумя Vector объектами вычисляется как величина Vector, полученная из vectorA − vectorB. VectorB − vectorA даёт тот же результат. Другими словами, Vector2.Distance(a,b) то же самое, что (a-b).magnitude.
Вы обычно используете этот метод, чтобы найти расстояние между двумя объектами.
Например, здесь враг нападет на игрока, если они попадут в определенную зону. Нижеследующий скрипт должен быть прикреплен к врагу GameObject.
using UnityEngine;
public class DistanceExample_enemy : MonoBehaviour { // Add a reference to the player, which is set in the Inspector window public GameObject player;
// Set the distance at which the enemy attacks public float attackDistanceThreshold = 2f;
void Update() { // Take the position of the player, and the position of this GameObject Vector2 playerPosition = player.transform.position; Vector2 myPosition = transform.position;
// Use Vector2.Distance to obtain the distance between the player position and this GameObject's position float distance = Vector2.Distance(myPosition, playerPosition);
// Check if the player is close enough if(distance < attackDistanceThreshold) { Attack(player); } }
void Attack(GameObject target) { // Insert the attack logic here Debug.Log($"{name} attacks {target.name}"); } }