- Home /
Movement on roads issue
So I'm trying to get a computer character to follow a road map. Basically it picks a random intersection to move towards, only re-adjusting if it wanders off the road by moving towards the closest road. I spent a few days trying to fix the original problem of it wandering off of the road randomly, but now I have another problem:
The character follows a loose pattern along the road, but doesn't save the closest road; instead it picks a random one far away. Also, the character still isn't moving towards the intersection that it says it's going after. I used a Debug.Log to print the point and it's setting it as just a vague (Object) instead of an actual point...here is the code I have so far:(One note, I excluded the variable initializations)
EDIT: Thanks to superluigi's advice, I started using navmesh...this is the new code in case anybody else needs it.
#pragma strict
var agent: NavMeshAgent;
var target: GameObject;
var moveSpeed : float = 6.0;
var gravity : float = 10.0;//basic stuff
var wayPointsAr: GameObject[] ;
var MyIndex;
var dist:float;
function Awake()
{
agent=GetComponent(NavMeshAgent);
wayPointsAr= GameObject.FindGameObjectsWithTag("waytag");//tags all waypoint objects
MyIndex = Random.Range(0,(wayPointsAr.length - 1));
target=wayPointsAr[MyIndex];
Debug.Log(target.transform.position);
}
function Update()
{
agent.SetDestination(target.transform.position);
dist=Vector3.Distance(target.transform.position,transform.position);
if (dist<50)
{
MyIndex = Random.Range(0,(wayPointsAr.length - 1));
target=wayPointsAr[MyIndex];
Debug.Log(target.transform.position);
}
}
Answer by superluigi · Feb 15, 2014 at 05:08 AM
Why don't you just use navmeshes. You can create the roads and your character will never wander off because it cant. Navmeshes also have built it AI so say for example your character chooses a random spot to go to but there are 3 different paths it can take, it'll automatically choose the shortest path available. There is a tutorial video here on unity's website that does an excellent job of teaching you about navmeshes.
Ah! I'll have to look into that. I was basically creating an object for each piece of the road...pretty primitive stuff, didn't even know there was such a thing. I'll look into it and update it once I try it out. Thanks luigi.
Good news, after a few hours of experimentation the navmesh works. Thanks again.
Your answer
Follow this Question
Related Questions
Npc Movement 0 Answers
How can i synchronize prefab with NetworkTranform? 1 Answer
Unity 2D Scripted Movement 2 Answers
Move multiple objects relative to another objects movement 1 Answer