Ok so I am sorry because I don’t know how to express my problem in one sentence but here it is:
Im trying to create a 2D top down game. The game will be about a zoo and animals.
My main goal here is to create a prefab of an animal and scatter a few of them inside a fence. So what I want to do is for this prefab to wander around the cage doing random movement.
The prefab has two states. One idle and one walking. My problem is that while I have found a way(through the community) to create a random way to choose between states and displaying them correctly, my 2D sprite won’t move.
enter code here`
void Start()
{
InvokeRepeating("ExecuteAfterTime", 2, 4);
//yield return StartCoroutine(ExecuteAfterTime(2.0F));
animator = GetComponent<Animator>();
}
void ExecuteAfterTime()
{
{
randvalue = Random.value;
if (Random.value >= 0.5)
{
Idle = true;
}
else
Idle = false;
// change to random direction at random intervals
if (Time.time >= tChange)
{
randomX = Random.Range(-2.0f, 2.0f); // with float parameters, a random float
randomY = Random.Range(-2.0f, 2.0f); // between -2.0f and 2.0f is returned
// set a random interval between 0.5f and 1.5f
tChange = Time.time + Random.Range(0.5f, 1.5f);
}
if (Idle != true)
{
isCoroutineExecuting = true;
transform.Translate(new Vector3(randomX, randomY, 0) * moveSpeed * Time.deltaTime);
animator.SetBool("DinoIdle", false); // DInoIdle is my bool which changes the anim states.
}
else
animator.SetBool("DinoIdle", true);
// if object reached any border, revert the appropriate direction
if (transform.position.x >= maxX || transform.position.x <= minX)
{
randomX = -randomX;
}
if (transform.position.y >= maxY || transform.position.y <= minY)
{
randomY = -randomY;
}
// make sure the position is inside the borders
Vector3 temp = transform.position;
temp.x = Mathf.Clamp(transform.position.x, minX, maxX);
temp.y = Mathf.Clamp(transform.position.y, minY, maxY);
moveSpeed = Random.Range(0.5f, 2.0f);
moveSpeed = Random.Range(0.5f, 2.0f);
isCoroutineExecuting = false;
}
}
void Update()
{
if (isCoroutineExecuting)
{
transform.Translate(new Vector3(randomX, randomY, 0) * moveSpeed * Time.deltaTime);
}
}`
I imagine this is happening since the movement takes place inside the coroutine and not inside the update. But if I put the code of the couroutine inside the update function, then the prefab changes states like crazy( which makes sense ) and ruins what I am trying to achieve. Is there any way I can do this? Am I using the wrong approach? I figured I should use Navmesh but I want to be able to click on an animal and force it to go a predefined route (a single target, not wherever the player wants).
My programming skills are not the best but I’m trying.
Thank you for reading this, any help will be great.