首页 > 解决方案 > 如何使对象按顺序转到特定位置 Unity C#

问题描述

所以我设置了它,以便回旋镖去一个随机点。这是我的代码:

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

public class Patrol : MonoBehaviour
{
    public float speed;

    public float range;
    private float distToPlayer;

    public Transform player;
  
    public Transform[] moveSpots;
    private int randomSpot;

    private float waitTime;
    public float startWaitTime;
    
    void Start()
    {
        waitTime = startWaitTime;
        randomSpot = Random.Range(0, moveSpots.Length);
    }       

    void Update()
    {                                             //start            //finish
        transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);

        if (Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
        {
            if (waitTime <= 0)
            {
                randomSpot = Random.Range(0, moveSpots.Length);
                waitTime = startWaitTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }

        distToPlayer = Vector2.Distance(transform.position, player.position);

        if (distToPlayer < range)
        {  
            Destroy(gameObject);   
        }  
    }
}

那么,我怎样才能让它先到一个点,然后另一个呢?帮助!

标签: c#unity3d

解决方案


假设您的 moveSpots 是有序的,您只需要摆脱随机操作,并获取数组中的下一项

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

public class Patrol : MonoBehaviour
{
    public float speed;

    public float range;
    private float distToPlayer;

    public Transform player;
  
    public Transform[] moveSpots;
    // Start at index 0
    private int nextSpot = 0;

    private float waitTime;
    public float startWaitTime;
    
    void Start()
    {
        waitTime = startWaitTime;

    }       

    void Update()
    {                                             //start            //finish
        transform.position = Vector2.MoveTowards(transform.position, moveSpots[nextSpot].position, speed * Time.deltaTime);

        if (Vector2.Distance(transform.position, moveSpots[nextSpot].position) < 0.2f)
        {
            if (waitTime <= 0)
            {
                // Set to the next index
                nextSpot ++;
                waitTime = startWaitTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }

        distToPlayer = Vector2.Distance(transform.position, player.position);

        if (distToPlayer < range)
        {  
            Destroy(gameObject);   
        }  
    }
}

那么当你到达列表的末尾时,你必须决定你想做什么?他们停下来吗?你会回到第一个位置吗?

// If you want to go back to the first spot you could check the length and reset to 0
nextSpot++;
if (nextSpot > moveSpots.Length)
{
    nextSpot = 0;
}

推荐阅读