- Home /
Random 2D NPC within defined area
I really need help. I need to be able to define an area, or use collision. And have an NPC with an idle and walk cycle using a blend tree. I just want the character to idle then walk for a bit to a random spot, idle... And so on forever. I have looked everywhere for this! Please help.
Answer by kaosermail · Dec 12, 2018 at 11:27 AM
You can use Navigation for this: https://docs.unity3d.com/Manual/Navigation.html
First define an area to be walkable. Then asign a nav agent to the NPC. Also add to the nav agent a script where you change his destination every random seconds.
// MoveTo.cs
using UnityEngine;
using System.Collections;
public class MoveTo : MonoBehaviour {
public Transform goal;
float time;
float randomSeconds;
void Start () {
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;
randomSeconds = Random.Range(3, 10));
time = Time.time;
}
void Update () {
if (time - Time.time > randomSeconds)
{
agent.destination = new Vector2 ( Random.Range(-1000, 1000), Random.Range(-1000, 1000));
randomSeconds = Random.Range(3, 10));
time = Time.time;
}
}
}
This way, he will stop when he reaches the end of the navigation walkable area.
Answer by paulson_101 · Dec 31, 2018 at 11:59 PM
I am still struggling with this basic concept. So I have a 2d NPC Sprite with an animation control. I also have a 2d Room, with collision on the walls. I jsut want the character to randomly walk around, using collision, and stopping on occassion. Why is this so hard for me to figure out! haha @kaosermail
The hard part of using Navigation is that you would need to use it as it was 3D (placing the plane horizontally....). If you think that it is too dificult I would suggest you to use the move function and stop every x seconds or when onTriggerEnter is activated and then change direction/ wait x seconds.
Your answer
Follow this Question
Related Questions
How can I change player sprite based on mouse position relative to the player? 2 Answers
How to Change a sprite mesh at a certain frame in an animation clip without script? 1 Answer
Making a 2d sprite play its animation at given waypoint. 1 Answer
Are sprite sheets treated like sparse textures in texture streaming, what size can I use? 0 Answers
How to flip hitboxes if my 2D Sprite is Flipped in AnimationsEditor ? [Unity2D] 1 Answer