2017-03-18 39 views
0

所以我一直在努力为Unity游戏项目,我的精灵只会向下移动和向右。这里是我当前的脚本:统一性对象Movment - 对象只变为向下和向右?

#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; 
    } 
} 

回答

0

想通了自己的问题是,我设置速度甚至当我在其他键第一个没有测试0。

0

我喜欢用Input.GetAxis(“水平”)和Input.GetAxis(“垂直”))这样,你避免了大量的代码和它的更好。

而且你不需要实例化rigidbody2D组件,只是做:

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

另外,我没有看到你的代码的任何故障,你有其他脚本在你的对象?或者你如何在对象中拥有你的rigidbody2D?