Kissen
Member
- Joined
- Jun 20, 2019
- Messages
- 13
- Programming Experience
- Beginner
My unity crashes when I run this code and the foodobject is outside of the searchscope of the "player".
The "player" should search for the closest foodobject and if there is none within its scope it should pick a random position and move towards it.
The "player" should search for the closest foodobject and if there is none within its scope it should pick a random position and move towards it.
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: