Hi,
I would like to make a game object move in a quite random way, on an irregular interval. Thus I decided I’d use the Random.Range method and a Coroutine. However, the object is moving only towards the left/bottom of the screen, never towards the right/top. Moreover, it doesn’t wait some time in a standing position as I wanted it to. Any idea why ?
Here’s the code I used :
public SpriteRenderer spriteRenderer;
public float speed = 4;
private Vector3 targetPosition;
private bool isMoving = false;
void Start()
{
}
void Update()
{
if(isMoving)
{
Move();
} else
{
SetTargetPosition();
}
}
void SetTargetPosition()
{
StartCoroutine(WaitForMove());
float xModifyer = Random.Range(-1, 1);
float yModifyer = Random.Range(-1, 1);
targetPosition = new Vector3(transform.position.x + xModifyer, transform.position.y + yModifyer, transform.position.z);
isMoving = true;
}
void Move()
{
if (targetPosition.x < transform.position.x)
{
spriteRenderer.flipX = true;
}
else
{
spriteRenderer.flipX = false;
}
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
isMoving = false;
}
}
IEnumerator WaitForMove()
{
while(true)
{
int a = Random.Range(10, 15);
yield return new WaitForSeconds(a);
}
}