c# - 如何使对象按顺序转到特定位置 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);
}
}
}
那么,我怎样才能让它先到一个点,然后另一个呢?帮助!
解决方案
假设您的 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;
}
推荐阅读
- vba - 从 VBA 在 IE 中启动 JavaScript 查询
- python-3.x - 课堂上的sklearn方法
- r - 计算元素出现次数和平均值的列
- wcf - .net 核心的 SecurityBindingElement.EnableUnsecuredResponse 等价物?
- powershell - 通过 Powershell 破坏格式字符串进行 SSAS 部署
- delphi - 如何通过右键单击在 TTabControl 中选择选项卡
- powershell - 使用 DOMAIN\USERNAME 时 New-PSSession 失败,但使用 USERNAME@DOMAIN.com 有效?
- java - Android Studio 运行警告:W/:无法打开“/system/framework/WfdCommon.jar”:没有这样的文件或目录
- html - 基于 URL 参数的动态文本
- angular - 如何在 Angular 应用程序中使用 Puppeteer