Answer the question
In order to leave comments, you need to log in
How to implement random movement of objects with breaks in Unity?
I'm trying to script an object with a sprite, it should move along the x-axis in random directions and periodically (again randomly) should stop. I tried to do it through Coroutine but I did some kind of game, help me figure out what I'm doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Villager : MonoBehaviour
{
[SerializeField] private float speed = 1f; //villager speed
[SerializeField] private int lives = 3; // villager lives
private Animator anim;
private SpriteRenderer sprite;
private States State
{
get { return (States)anim.GetInteger("State"); }
set { anim.SetInteger("State", (int)value); }
}
private void Awake()
{
anim = GetComponent<Animator>();
sprite = GetComponentInChildren<SpriteRenderer>();
}
private void Start()
{
State = States.idle;
StartCoroutine(Walk());
}
private void Update()
{
}
IEnumerator Walk()
{
State = States.walk;
StartCoroutine(WalkRight());
yield return new WaitForSeconds(5f);
StartCoroutine(WalkLeft());
}
IEnumerator WalkRight()
{
Vector3 direction = transform.right * 3f;
transform.position = Vector3.MoveTowards(transform.position, transform.position + direction, speed * Time.deltaTime);
sprite.flipX = transform.position.x > 0.0f;
yield return new WaitForSeconds(4f);
}
IEnumerator WalkLeft()
{
Vector3 direction = transform.right * -3f;
transform.position = Vector3.MoveTowards(transform.position, transform.position + direction, speed * Time.deltaTime);
sprite.flipX = transform.position.x < 0.0f;
yield return new WaitForSeconds(5f);
}
public void GetDamage()
{
lives -= 1;
Debug.Log("Villager" + lives);
}
public enum States
{
idle,
walk
}
}
Answer the question
In order to leave comments, you need to log in
- Now the Walk coroutine will be executed only once. Repetition is needed for periodicity.
- I do not see an attempt to implement random movement. Now you just walk to the right once and, after a break, once to the left.
I advise you to first clearly define what behavior of the object you want to achieve, and break the task into subtasks.
I see your problem like this:
1. moving a random distance in a random direction
2. pauses of random duration after moving
3. 2 the previous operations are repeated over and over again.
For the first and second points: use Random.Range along the X axis.
For the third point: create a cycle in the coroutine with the number of repetitions of movements + pauses.
Good luck!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question