- Home /
How to make a player go to the position of another object?
I have a simple Unity game and want to make it so that when the player hits spikes, he automatically goes to the SpawnPoint empty object. I made it so that it plays a death animation when it hits the spikes but I do not know how to make it so that the player moves to the object, SpawnPoint's, position. I would appreciate it if you could help. Thanks.
Answer by PretzelTail101 · Jun 23, 2020 at 07:21 PM
Use the navmesh agent, and in a script say agent.destination = target.position.
Answer by markythemurloc · Jun 23, 2020 at 09:06 PM
Hey!
Vector3.MoveTowards should do the trick.
Vector3.MoveTowards (transform you want to move.position, target.position, speed);
Note that this should be put in the FixedUpdate (or update) function in order to work.
Example code:
using UnityEngine;
//This script should be attached to the object you want to move.
public class MoveToSpawnPoint: MonoBehaviour
{
private GameObject _spawnPoint;
private void Start()
{
//Find the SpawnPoint by name.
_spawnPoint = GameObject.Find("SpawnPoint");
}
private void FixedUpdate()
{
if (/*State your conditions here*/)
{
//Use Vector3.MoveTowards to move your object to the SpawnPoint position.
transform.position = Vector3.MoveTowards(transform.position, _spawnPoint.transform.position, 50 * Time.deltaTime);
}
}
}
Edit: If you're developing a 2D game you could use Vector2.MoveTowards instead of Vector3.MoveTowards. Works the same.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Creating an app for mobile and browsers 1 Answer
Adapt OnMouseDown to control with Gamepad? 0 Answers
tags on ContactFilter2D? 0 Answers