- Home /
Using tags to move player toward objects
var waypoint : Transform;
//I dont want to code it like this
var waypoint2 : Transform;
var speed : float = 2;
function Start ()
{
}
function Update ()
{
OnMouseDown();
}
function OnMouseDown()
{
if(Input.GetMouseButton(0))
{
//Can i reference the waypoint.position code for all waypoints instead of just the one?
transform.position = Vector3.MoveTowards(transform.position, waypoint.position, speed*Time.deltaTime);
}
//I dont want to use this code
if(Input.GetMouseButton(1))
{
transform.position = Vector3.MoveTowards(transform.position, waypoint2.position, speed*Time.deltaTime);
}
}
This is sample code for a project im working on. I have a player and waypoints, in this example, i have two.
What i would like is for the player to move toward the object i click on without reusing code like i have above. The code above works fine but i know its not efficient. I have all waypoints tagged with "waypoint".
Is there a way i can accomplish this?
Answer by nikroth · Jan 09, 2014 at 08:21 PM
Make an array with your waypoints. And when you reach it remove this waypoint and he will walk to the next one. (if your direction towards the waypoint has changed that means that you have passed it)
Vector3 calcualtedDirectionToPoint = GetDirectionToPoint(waypoints[0]);
if(originalDirectionTowardsWaypoint != calcualtedDirectionToPoint) //we have passed and we should go to the next one
{
Utils.Remove_TheFirstElementFromArray(waypoints);
originalDirectionTowardsWaypoint = GetDirectionToPoint(waypoints[0]); //calculating the new direction for walking
}
else
{
MoveCloserTowardsPoint(waypoints[0]);
}
Your answer
Follow this Question
Related Questions
2D Enemy AI issues... 1 Answer
Using Raycast to detect what's hit and if it's tagged 2 Answers
Object reference not set to an instance of an object 1 Answer
Waypoint Arrow not pointing at tagged object ? 1 Answer
Problem with MoveToWaypoint 1 Answer