I’m making an Animal Crossing fan game for one of my classes and currently I’m taking models from New Leaf, putting them in Mixamo to get some idle and walk animations and then putting them into the scene. I want them to walk around the environment randomly, stop on collision, and then keep walking in a different direction. I’ve got the animations and everything working properly, I just need a working script to make the models move and stop when they hit something.
This could do the trick!
[SerializeField]
private float minX, maxX;
[SerializeField]
private float minY, maxY;
[SerializeField]
private float speed;
private bool isMoving = true;
private Vector2 targetPosition;
private Vector2 GetRandomTarget()
{
return new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
}
void Start()
{
targetPosition = GetRandomTarget();
}
private void OnTriggerEnter2D(Collider2D collision)
{
isMoving = false;
}
void Update()
{
if (isMoving)
{
if ((Vector2)transform.position == targetPosition)
{
targetPosition = GetRandomTarget();
}
else
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, step);
}
}
}
You should probably leverage Unity’s NavMesh for that, especially if it’s a 3D game.
It’s really simple to do what you are trying with it, you just need a couple of function calls.