3
I have a problem, I need my character to move a certain distance when I click the button, until then I can do.
The problem is that when I do, he doesn’t "walk" to the point, he sort of "teleports," and that’s not the intention. I need him to automatically travel this distance.
Can someone help me?
using Unityengine; using System.Collections;
public class movement : Monobehaviour {
public float posicao = 2f;
private bool clickBaixo;
private bool clickCima;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
clickBaixo = moveDown.getBaixo();
clickCima = moveUp.getCima();
if(Input.GetKeyDown("up") || clickCima == true){
transform.Translate(0,posicao,0);
}
if(Input.GetKeyDown("down") || clickBaixo == true){
transform.Translate(0,(posicao)*-1,0);
}
}
}
Updated:
using Unityengine; using System.Collections;
public class movement : Monobehaviour {
public float posicao = 2f;
public float vel = 10f;
private bool clickBaixo;
private bool clickCima;
private float novaPosicao;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
clickBaixo = moveDown.getBaixo();
clickCima = moveUp.getCima();
if(Input.GetKeyDown("up") || clickCima == true){
StartCoroutine("moveCima");
}
if(Input.GetKeyDown("down") || clickBaixo == true){
StartCoroutine("moveBaixo");
}
}
IEnumerator moveCima(){
novaPosicao = transform.position.y + posicao;
while(transform.position.y<novaPosicao){
transform.Translate(0, vel*Time.deltaTime, 0);
yield return null;
}
}
IEnumerator moveBaixo(){
novaPosicao = transform.position.y + posicao;
while(transform.position.y<novaPosicao){
transform.Translate(0, (vel*Time.deltaTime)*-1, 0);
yield return null;
}
}
}
Could you edit the question to post the relevant part of your code on it? After all, you can’t tell what’s not working without seeing it.
– Victor Stafusa
As colleague @Victorstafusa mentions, your code is important so someone can point out your error. You are probably changing the
transform.position
from it to the destination position (final), and so occurs the "teleport". If applicable, you should use an alternative such as (1) using physics and applying a force in the direction of fate; (2) point the character’s object in the direction of destiny and gradually translate according to a speed stipulated in that direction every frame (call forupdate
); (3) useLerp
.– Luiz Vieira