我一直在研究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;
}
}
答案 0 :(得分:0)
我喜欢使用Input.GetAxis(“Horizontal”)和Input.GetAxis(“Vertical”)),这样可以避免大量代码,而且更好。
您不需要实例化rigidbody2D组件,只需执行:
rigidbody2d.velocity = new Vector2(speed * Input.GetAxis("Horizontal"), speed * Input.GetAxis("Vertical"));
此外,我没有看到您的代码有任何失败,您的对象中是否有另一个脚本?或者你如何在对象中拥有你的刚体2D?
答案 1 :(得分:0)
自己搞清楚,问题是我将速度设置为0,即使我没有先测试其他键。