如何使一个对象去特定的点顺序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);   
}  
}
}

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

假设你的movespot是有序的,你只需要摆脱你的随机操作,并获得数组中的下一个项目

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;
}

最新更新