- Home /
Movimento de personagem de um ponto a outro.
How to make a character move from side to side in looping, every time he reaches a certain point he turns and goes back to the other side?
public class Teste_plataforma : MonoBehaviour {
public Animator RenaAnima1;
[SerializeField] private float speedMove;
[Header("Objeto a ser movido")]
[SerializeField] private GameObject platform;
[Header("Pontos de referencia")]
[SerializeField] private Transform pointerA, pointerB;
[Header("Rota para onde ir")]
[SerializeField] private Transform route;
[SerializeField] private int routeCurrent;
private void Start () {
routeCurrent = 0;
platform.transform.position = pointerA.position;
route.position = pointerB.position;
}
private void Update ()
{
float step = speedMove * Time.deltaTime;
platform.transform.position = Vector3.MoveTowards (platform.transform.position, route.position, step);
if (platform.transform.position == route.position) {
if (routeCurrent == 0) {
transform.Rotate (Time.deltaTime, 180, 0);
routeCurrent = 1;
route.position = pointerA.position;
} else if (routeCurrent == 1) {
route.position = pointerB.position;
routeCurrent = 0;
transform.Rotate (Time.deltaTime, 180, 0);
}
}
}
}
This way it even works, but when I get to the points it stops, it calls an animator, and then it goes back to the other point, it's a movement like a soldier doing patrol.
Answer by eskivor · Jul 22, 2017 at 01:06 AM
In your update add a check of the distance between the character to his objective, if it's under a certain amount, you can consider your character is on his objective spot :
void Update ()
{
//Your last stuff here
float distance = Vector3.Distance (yourCharacterPosition, hisObjectivePosition);
if (distance <= 1f) //example amount
{
//Call an animator, etc.
}
}
Also, I recommand you to use a navmesh to manage your character moves (for example if the player move somewhere inside the patrol, the character will bypass it instead of being stuck or pushing the player out if his patrol)
To do that : build a NavMesh
on your scene (in the Navigation
window, after putting your level to static
to build the NavMesh
), use a NavMeshAgent
component on your character, then to move it in a script, get your NavMeshAgent
component and use its method SetDestination (hisObjectivePosition);