2017-03-18 40 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?