【问题标题】:Unity 2D - Moving Any Object Between Two (or more) SpacesUnity 2D - 在两个(或更多)空间之间移动任何对象
【发布时间】:2021-09-23 02:35:40
【问题描述】:

Unity 新人,以及一般的新编码员。我试图让一个物体在两个点之间来回移动。我现在有它从第 1 点到第 2 点,但它停止了。我尝试了一个 do 循环,并再次回调 Move() 函数,但它只是冻结了 Unity。

我猜我需要某种循环,但不确定在哪里做?我也不介意能够添加更多的点。我在 Unity 本身中有航点,与对象相关联。谢谢!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ZombiePathing : MonoBehaviour
{
    [SerializeField] List<Transform> waypoints;
    [SerializeField] float moveSpeed = 2f;
    int waypointIndex = 0;

    
 
    void Start()
    {
        transform.position = waypoints[waypointIndex].transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    private void Move()
    {
        if (waypointIndex <= waypoints.Count -1)
        {
             var targetPosition = waypoints[waypointIndex].transform.position;
             var movementThisFrame = moveSpeed * Time.deltaTime;
            transform.position = Vector2.MoveTowards
                (transform.position, targetPosition, movementThisFrame);
            if (transform.position == targetPosition)

            {
                waypointIndex++;
            }


        }
        
         
     }
} 

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: c# unity3d


【解决方案1】:

只需添加一个等于 1 或 -1 的索引取决于当前的变换, 我很快就编写了这段代码,所以它没有排序,我尽我所能通过一些编辑使它与你的代码非常接近。

  using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ZombiePathing : MonoBehaviour
    {
        [SerializeField] List<Transform> waypoints;
        [SerializeField] float moveSpeed = 2f;
        Vector3 targetPosition;
        int waypointIndex = 0;
        int index = 1;
        void Start()
        {
            transform.position = waypoints[waypointIndex].position;
            UpdateTransform();
        }
        void Update()
        {   transform.position = Vector2.MoveTowards
            (transform.position, targetPosition, moveSpeed * Time.deltaTime);
            if (transform.position == targetPosition) UpdateTransform();
        }
    
        private void UpdateTransform()
        {
             waypointIndex += index;
             targetPosition = waypoints[waypointIndex].position;
             if (waypointIndex >= waypoints.Count -1) index = -1;
             else if (waypointIndex <= 0 && index == -1)index = 1;
        }
    } 

【讨论】:

  • 谢谢!做到了 :) 更好的是,我可以添加更多航点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
相关资源
最近更新 更多