I’m trying to get an object to choose a random position, go to said random position, and then repeat the process. The problem is when it goes to the second location it chose, it starts to jitter in all directions which I think is it constantly finding a new position and moving towards it
This is the code I used
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public float x;
public float y;
public Vector2 randompos;
[SerializeField] private float speed = 1.5f;
[SerializeField]
public void FindNewLocation()
{
randompos = new Vector2(Random.Range(-5f, 5f), Random.Range(-5f, 5f));
}
// Start is called before the first frame update
void Start()
{
FindNewLocation();
}
// Update is called once per frame
void Update()
{
if (transform.position.x == randompos.x && transform.position.y == randompos.y);
{
Invoke("FindNewLocation", 3f);
}
transform.position = Vector2.MoveTowards(transform.position, randompos, speed * Time.deltaTime);
}
}
your code for detecting if it reached the destination is bad, you should instead do something like this:
if(Vector3.Distance(transform.position, newTarget.position) < 0.1f){
//It is within ~0.1f range, do stuff
}
in addition its bad that you are using invoke because it will invoke 1000s FindNewLocation(), you shouldnt use invoke, or add a check that makes sure that you only called invoke once
I was able to use the detection code you suggested, but it didn’t resolve the issue. I think it’s the Invoke function that’s causing the problem, but how would I go about adding a check to make sure it is only called once? (I tried just calling the function normally but it didn’t help)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public float x;
public float y;
public Vector2 randompos;
public bool searching = false;
[SerializeField] private float speed = 1.5f;
[SerializeField]
public void FindNewLocation()
{
randompos = new Vector2(Random.Range(-5f, 5f), Random.Range(-5f, 5f));
searching = true;
}
// Start is called before the first frame update
void Start()
{
FindNewLocation();
}
// Update is called once per frame
void Update()
{
if (transform.position.x == randompos.x && transform.position.y == randompos.y&& searching==true);
{
searching = false;
Invoke("FindNewLocation", 3f);
}
if(searching==true){
transform.position = Vector2.MoveTowards(transform.position, randompos, speed * Time.deltaTime);
}
}
}
you can also just look at the inspector and see what is going wrong with your variables
I implemented the code, but the same issue came up. In the inspector, the variables change all the time after 3 seconds which probably means Invoke is being called constantly but I don’t know why.
Edit: It turns out the issue was that I kept on putting a semicolon after the if statement, thus ending the statement and not applying the conditions to the call. Thank you for your time and attention helping me.