- Home /
Player move from waypoint to waypoint?
Hey Unity, I'm trying to make the player of my game move from column to column (6 columns in game) in order to dodge obstacles inside the columns. Any ideas for a script? Sorry, I am recently new to Unity and this concept. Thanks in advance! PS: will post pictures of inspector soon, not near computer at the moment.
Please provide more information. Is there any pathfinding involveD? Does the character use a ChracterController or rigidbody? What about physics and collision?
To move a gameobject, you can use Vector3.Lerp or Transform.translate, for example. Look up both in the Unity User $$anonymous$$anual.
As for going from waypoint to waypoint, that's simple. You need three variables: An array of Vector3s which stores the coordinates of you waypoints, an index as and indicator of you current waypoint (int), and a threshold (float).
While the player is moving towards the current waypoint, continually check if the Distance between him and the current waypoint is smaller than the threshold. If it is, then increase the index by one and make the player move to this array position.
Answer by Chris333 · Jan 30, 2015 at 04:20 PM
Hi,
you could use a easy waypoint solution where you have a list of all waypoints stored in a array as GameObjects. You calculate the vector form your current position to the current waypoint of the array and move your player in that direction unless the distance to that waypoint reaches a minValue. Than you switch to the next waypoint in the array. When you reached the end of the array you begin from start. Thats a way how you can achieve a walking path for a guard for instance.
Example code for a 2D-top-down walk path:
public float actualSpeed = 10.0f;
public GameObject[] checkpoints;
int counter = 0;
public float distance = 2.0f; //on which distance you want to switch to the next waypoint
void FixedUpdate ()
{
direction = Vector3.zero;
//get the vector from your position to current waypoint
direction = checkpoints[counter].transform.position - transform.position;
//check our distance to the current waypoint, Are we near enough?
if(direction.magnitude < distance)
{
if(counter < checkpoints.Length-1) //switch to the nex waypoint if exists
{
counter++;
}
else //begin from new if we are already on the last waypoint
{
counter = 0;
}
}
direction = direction.normalized;
Vector3 dir = direction;
GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x * actualSpeed, direction.y * actualSpeed);
}
Your answer
Follow this Question
Related Questions
How do i keep my characters orientation? 0 Answers
How could I add ui images to an instantiated prefab by photon ?? 0 Answers
Play animation with FPS controller? 2 Answers
Wall Jump Scripting Help 2 Answers