【问题标题】:Unity Object Movement - Object Only Goes Down and Right?Unity 对象移动 - 对象只能向下和向右移动?
【发布时间】:2018-05-25 18:14:37
【问题描述】:

我一直在做一个 Unity 游戏项目,我的精灵只会向下和向右移动。这是我当前的脚本:

#pragma strict
function Update (){
    var ship = GetComponent(Rigidbody2D);
    var speed = 10;
    if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)){
        ship.velocity.y = speed;
    }else {
        ship.velocity.y = 0;
    }
    if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)){
        ship.velocity.x = -1 * speed;
    }else {
        ship.velocity.x = 0;
    }
    if(Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)){
        ship.velocity.y = -1 * speed;
    }else {
        ship.velocity.y = 0;
    }
    if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)){
        ship.velocity.x = speed;
    }else {
        ship.velocity.x = 0;
    }
}

【问题讨论】:

    标签: unity3d sprite unityscript


    【解决方案1】:

    我喜欢使用 Input.GetAxis("Horizo​​ntal") 和 Input.GetAxis("Vertical")) 来避免大量代码,这样会更好。

    而且您不需要实例化刚体2D 组件,只需这样做:

    rigidbody2d.velocity = new Vector2(speed * Input.GetAxis("Horizontal"), speed * Input.GetAxis("Vertical"));

    另外,我没有看到你的代码有任何失败,你的对象中有另一个脚本吗?或者你如何在对象中有你的rigidbody2D?

    【讨论】:

      【解决方案2】:

      我自己想通了,问题是我将速度设置为 0,即使我没有先测试其他键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多