Unity move towards как работает
Перейти к содержимому

Unity move towards как работает

  • автор:

Vector3.MoveTowards

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Your name Your email Suggestion * Submit suggestion

Declaration

public static Vector3 MoveTowards (Vector3 current , Vector3 target , float maxDistanceDelta );

Parameters

current The position to move from.
target The position to move towards.
maxDistanceDelta Distance to move current per call.

Returns

Vector3 The new position.

Description

Calculate a position between the points specified by current and target , moving no farther than the distance specified by maxDistanceDelta .

Use the MoveTowards member to move an object at the current position toward the target position. By updating an object’s position each frame using the position calculated by this function, you can move it towards the target smoothly. Control the speed of movement with the maxDistanceDelta parameter. If the current position is already closer to the target than maxDistanceDelta, the value returned is equal to target ; the new position does not overshoot target . To make sure that object speed is independent of frame rate, multiply the maxDistanceDelta value by Time.deltaTime (or Time.fixedDeltaTime in a FixedUpdate loop).

Note that if you set maxDistanceDelta to a negative value, this function returns a position in the opposite direction from the target .

using UnityEngine;

// Vector3.MoveTowards example.

// A cube can be moved around the world. It is kept inside a 1 unit by 1 unit // xz space. A small, long cylinder is created and positioned away from the center of // the 1x1 unit. The cylinder is moved between two locations. Each time the cylinder is // positioned the cube moves towards it. When the cube reaches the cylinder the cylinder // is re-positioned to the other location. The cube then changes direction and moves // towards the cylinder again. // // A floor object is created for you. // // To view this example, create a new 3d Project and create a Cube placed at // the origin. Create Example.cs and change the script code to that shown below. // Save the script and add to the Cube. // // Now run the example.

public class Example : MonoBehaviour < // Adjust the speed for the application. public float speed = 1.0f;

// The target (cylinder) position. private Transform target;

void Awake() < // Position the cube at the origin. transform.position = new Vector3(0.0f, 0.0f, 0.0f);

// Create and position the cylinder. Reduce the size. var cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder); cylinder.transform.localScale = new Vector3(0.15f, 1.0f, 0.15f);

// Grab cylinder values and place on the target. target = cylinder.transform; target.transform.position = new Vector3(0.8f, 0.0f, 0.8f);

// Position the camera. Camera.main.transform.position = new Vector3(0.85f, 1.0f, -3.0f); Camera.main.transform.localEulerAngles = new Vector3(15.0f, -20.0f, -0.5f);

// Create and position the floor. GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane); floor.transform.position = new Vector3(0.0f, -1.0f, 0.0f); >

void Update() < // Move our position a step closer to the target. var step = speed * Time.deltaTime; // calculate distance to move transform.position = Vector3.MoveTowards(transform.position, target.position, step);

// Check if the position of the cube and sphere are approximately equal. if (Vector3.Distance(transform.position, target.position) < 0.001f) < // Swap the position of the cylinder. target.position *= -1.0f; >> >

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright ©2024 Unity Technologies. Publication Date: 2024-04-25.

Vector3.MoveTowards

Благодарим вас за то, что вы помогаете нам улучшить качество документации по Unity. Однако, мы не можем принять любой перевод. Мы проверяем каждый предложенный вами вариант перевода и принимаем его только если он соответствует оригиналу.

Ошибка внесения изменений

По определённым причинам предложенный вами перевод не может быть принят. Пожалуйста попробуйте снова через пару минут. И выражаем вам свою благодарность за то, что вы уделяете время, чтобы улучшить документацию по Unity.

Ваше имя Адрес вашей электронной почты Предложение * Разместить предложенное

public static function MoveTowards ( current : Vector3, target : Vector3, maxDistanceDelta : float): Vector3;

public static Vector3 MoveTowards (Vector3 current , Vector3 target , float maxDistanceDelta );

Параметры

Описание

Moves a point current in a straight line towards a target point.

The value returned by this function is a point maxDistanceDelta units closer to a target/ point along a line between current and target . If the target is closer than maxDistanceDelta/ then the returned value will be equal to target (ie, the movement will not overshoot the target). Negative values of maxDistanceDelta can be used to push the point away from the target.

// The target marker. var target: Transform; // Speed in units per sec. var speed: float; function Update () < // The step size is equal to speed times frame time. var step = speed * Time.deltaTime; // Move our position a step closer to the target. transform.position = Vector3.MoveTowards(transform.position, target.position, step); >
using UnityEngine; using System.Collections;

public class ExampleClass : MonoBehaviour < public Transform target; public float speed; void Update() < float step = speed * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, target.position, step); > >

Vector2.MoveTowards в корутине

Суть: 2D бесконечный раннер, игрок не успел среагировать, препятствие «отодвинуло» персонажа. И дабы всю игру персонаж не бежал где-то сбоку, через время возвращать его назад на середину экран, тобеж на нулевую координату по X. У препятствий тег «Barrier». По коду, приведенному ниже, ничего не происходит. Сама корутина запускается (проверено посредством Debug.Log), а MoveTowards не срабатывает. Скрипт висит на персонаже.

public float returnSpeed; [SerializeField] private Transform target; public void Start() < target = transform; target.position = new Vector2(0f, 0f); >public void OnCollisionExit2D(Collision2D other) < if (other.gameObject.CompareTag("Barrier") && (transform.position.x < 0)) < StartCoroutine("ReturnPositionToZero"); >> private IEnumerator ReturnPositionToZero()

Отслеживать
Intelligent
задан 21 сен 2020 в 16:35
Intelligent Intelligent
15 4 4 бронзовых знака

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

  1. returnSpeed Нигде не инициализирован и равен нулю, а значит и step == 0.
  2. ReturnPositionToZero Выполнится всего один раз через 3 секунды и движение может быть незаметно(зависит от returnSpeed).

Нужно примерно так:

returnSpeed = 5;// подбери нужное число private IEnumerator ReturnPositionToZero() < yield return new WaitForSeconds(3);//хз зачем int iteration = 0;// просто что бы случайно не уйти в бесконечный цикл(тогда редактор просто зависнет, а игра упадет) float delta = 0.1f;// или любая дельта while (Vector2.Distance(transform.position,target.position) >delta && iteration < 100) < iteration++; var step = returnSpeed * Time.deltaTime; transform.position = Vector2.MoveTowards(transform.position, target.position, step); yield return new WaitForEndOfFrame();//ждем конца кадра >> 

Отслеживать
ответ дан 21 сен 2020 в 17:46
Valera Kvip Valera Kvip
2,677 11 11 серебряных знаков 24 24 бронзовых знака

Спасибо, сразу не срабатывало правда. Но сделал target не Transform’ом, а Vector2 и все работает. Только персонаж очень сильно дергается при возвращении в нулевую координату

Почему Vector3.MoveTowards перемещает неточно?

в инспекторе я задал, что speed = 5, xOffset = 1, но почему когда я двигаю кубом на кнопки, оно сдвигается неточно, оно сдвигается на 1 целых и еще десятые или сотые, но в моем случае это критично, как это можно исправить?

  • Вопрос задан более трёх лет назад
  • 320 просмотров

Комментировать

Решения вопроса 0

Ответы на вопрос 0

Ваш ответ на вопрос

Войдите, чтобы написать ответ

c#

  • C#
  • +1 ещё

Ошибка Unity Editor — Unity 2023.3.0b7_ebadad6d577d что делать?

  • 1 подписчик
  • вчера
  • 29 просмотров

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *