2014-10-11 56 views
0

我一直在關注pong教程,但是我遇到了問題。鍵盤輸入在Unity中不起作用

當您按下箭頭時球拍不會移動。

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour 
{ 
    // up and down keys (to be set in the Inspector) 
    public KeyCode up; 
    public KeyCode down; 

    void FixedUpdate() 
    { 
     // up key pressed? 
     if (Input.GetKey(up)) 
     { 
      transform.Translate(new Vector2(0.0f, 0.1f)); 
     } 

     // down key pressed? 
     if (Input.GetKey(down)) 
     { 
      transform.Translate(new Vector2(0.0f, -0.1f)); 
     } 
    } 
} 

而且我在檢查員中爲圖像分配了一個鍵。

+0

你試過在ifs裏面調試嗎?嘗試打印某些內容以查看是否進入條件。 – 2014-10-12 01:14:53

回答

0

好的,你需要檢查的是KeyCode是否在你的項目設置中定義。

它最好使用類似下面的代碼來檢測這種按鍵:

void Update() { 
    if (Input.GetButton("Fire1") && Time.time > nextFire) { 
     nextFire = Time.time + fireRate; 
     Instantiate(projectile, transform.position, transform.rotation); 
    } 
} 

來源:http://docs.unity3d.com/ScriptReference/Input.GetButton.html 此外,我建議看下面的教程:https://www.youtube.com/watch?v=JgY5YxNHxtw 這可以解釋這一切非常清楚。

希望它可以幫助你;)

編輯:更改爲void的功能,因爲它好像你正在使用C#

+0

我該怎麼做? – user1627724 2014-10-11 19:34:00

+0

我更新了;)檢查視頻我相信它會有幫助。 – 2014-10-11 19:35:27

0

我覺得我得到你。您不需要在檢查員中分配鍵碼。您可以直接從腳本訪問它們。它應該簡化您的腳本。

取而代之的是:

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour 
{ 
    // up and down keys (to be set in the Inspector) 
    public KeyCode up; 
    public KeyCode down; 

    void FixedUpdate() 
    { 
     // up key pressed? 
     if (Input.GetKey(up)) 
     { 
      transform.Translate(new Vector2(0.0f, 0.1f)); 
     } 

     // down key pressed? 
     if (Input.GetKey(down)) 
     { 
      transform.Translate(new Vector2(0.0f, -0.1f)); 
     } 
    } 
} 

試試這個:

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour 
{ 
     public float speed = 30f; 
     //the speed at which you move at. Value can be changed if you want 

    void Update() 
    { 
     // up key pressed? 
     if (Input.GetKeyDown(KeyCode.W) 
     { 
      transform.Translate(Vector2.up * speed * time.deltaTime, Space.world); 
     } 

     // down key pressed? 
     if (Input.GetKeyDown(KeyCode.S)) 
     { 
      transform.Translate(Vector2.down * speed * time.deltaTime, Space.World); 
     } 
    } 
} 

假設你想使用WASD鍵的運動。如果需要,您可以使用OR修飾符(||)添加更多。另外,對於第二個玩家,一定要更改鍵碼,否則兩個槳將同時移動。

代碼說明: 速度變量是您想要移動的速度。根據您的需求更改它。

在transfor.Translate()中,您希望隨着時間的推移以世界座標(不是本地)的速度向上移動。這就是爲什麼你使用Vector2.up * speed * time.deltaTime。 Vector2.up相同

new Vector2 (0f, 1f); 

你乘它通過速度得到移動的距離,然後通過Time.deltaTime得到的距離在這個框架中移動。由於更新是每幀調用的,因此您將每幀移動距離。

在向下移動,Vector2.down相同

new Vector2(0f, -1f); 

希望這有助於!