Move character up to point in Unity3D

2

I have a problem, I need my character to move a certain distance when I click the button, until then I can do it.

The problem is that when I do, he does not "walk" to the point, he kind of "teleports", and that's not the intention. I need him to automatically walk this distance.

Can anyone 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;
    }
}

}

    
asked by anonymous 17.07.2015 / 22:51

1 answer

2

You need to know what effect you want when walking with your character because there are several solutions. And they all depend on what you want to do. The easiest ones are.

The first is to use a force, you apply a force on the rigidybody and Unity takes care of changing the position for you. link

The second is you add small steps updating the position to get from one point to the other. Do not use while inside an Update, try to use a Coroutine. In this one I use MoveTowards link

The third is to use Lerp , just like MoveToward, remember to use a time variation to smooth transition link

There is also a need to take care where you place your loops and what you place where. For there is a big difference in the calls of Update and FixedUpdate . link

    
18.07.2015 / 03:57