基森
会员
- 已加入
- 2019年6月20日
- 留言内容
- 13
- 编程经验
- Beginner
当我运行此代码并且foodobject不在搜索范围的搜索范围内时,我的单位崩溃"player".
的"player"应该搜索最接近的食物对象,如果没有食物对象,则应该选择一个随机位置并朝该位置移动。
的"player"应该搜索最接近的食物对象,如果没有食物对象,则应该选择一个随机位置并朝该位置移动。
C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
public float scope = 10;
public float speed = 1;
Vector2 randomPos;
bool Notarget = true;
bool canChoose = true;
// Update is called once per frame
void Update()
{
FindClosestConsumable();
}
void FindClosestConsumable()
{
float distance = Mathf.Infinity;
consumable closestConsumeable = null;
consumable[] AllConsumables = GameObject.FindObjectsOfType<consumable>();
foreach(consumable currentConsumable in AllConsumables)
{
float distanceToFood = (currentConsumable.transform.position - this.transform.position).sqrMagnitude;
if(distanceToFood < distance)
{
distance = distanceToFood;
closestConsumeable = currentConsumable;
}
}
Debug.DrawLine(this.transform.position, closestConsumeable.transform.position);
if(Mathf.Sqrt(Mathf.Pow((this.transform.position.x - closestConsumeable.transform.position.x),2) + Mathf.Pow(this.transform.position.y-closestConsumeable.transform.position.y,2)) < scope)
{
Notarget = false;
this.transform.position = Vector2.MoveTowards(this.transform.position, closestConsumeable.transform.position, speed*Time.deltaTime);
}
else
{
Notarget = true;
while (Notarget)
{
if (canChoose)
{
float Height = Random.Range(-4.5f, 4.5f);
float Width = Random.Range(-7f, 7f);
randomPos = new Vector2(Width, Height);
canChoose = false;
}
this.transform.position = Vector2.MoveTowards(this.transform.position, randomPos, speed * Time.deltaTime);
}
}
}
}
Last edited: