按下某个键时,Unity3D会移动一个精灵

时间:2014-04-06 15:58:39

标签: unity3d sprite game-physics

我在点击w键时尝试移动精灵。我一直在使用我在YouTube上找到的教程,但我似乎无法使其工作。这是代码。也许我对变换有问题;我可以看到x位置递增但精灵没有做任何事情。

#pragma strict

var startPoint : Vector3;
var endPoint : Vector3;
var speed : float;
private var increment : float;
var isMoving : boolean;

function Start ()
{
    startPoint = transform.position;
    endPoint = transform.position;
}

function Update ()
{
    if (increment <= 1 && isMoving == true) {
        increment += speed/100;
        Debug.Log("Moving");

    }
    else {
        isMoving = false;
        Debug.Log("Stopped");

    }

    if (isMoving == true)
        transform.position = Vector3.Lerp(startPoint, endPoint, increment);

    if (Input.GetKey("w") && isMoving == false) {
        increment = 0;
        isMoving = true;
        startPoint = transform.position;
        endPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1);

    }
    if (Input.GetKey("s") && isMoving == false) {
        increment = 0;
        isMoving = true;
        startPoint = transform.position;
        endPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z - 1);
    }
}

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

function Update () {

    if (Input.GetKeyDown(KeyCode.W)) {
        increment += speed / 100;
        transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.forward, increment);
    }

    if (Input.GetKeyDown(KeyCode.Z)) {
        increment += speed / 100;
        transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.back, increment);
    }
}

另外,检查检查员中的速度是否为0。如果你想连续移动,请将Input.GetKeyDown更改为Input.GetKey。