2017-05-20 48 views
0

我對Unity 5非常陌生,對接口有基本的瞭解。我從來沒有編碼過任何特別的東西。沒有教程我什麼都做不了。但是前段時間我發現了一個教程,似乎符合我的需求。如何在Unity C#中將角色添加到我的角色中?

基本上是這樣,是我想增加動力到球員將有的hitbox(立方體)。當你按下W鍵時,你將建立速度,然後達到終點速度。我怎麼做到這一點?

我試圖做一些工作,並且我覺得我非常接近(因爲我覺得它好像是一個工作塊),但我無法弄清楚它放在哪裏或錯誤是什麼在說,所以我來到這個網站。

這裏是代碼:https://pastebin.com/dmSuJR7m

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class CharacterControls : MonoBehaviour { 

public float speed = 3.0F; 

// Use this for initialization 
void Start() { 
    Cursor.lockState = CursorLockMode.Locked; 
} 



// Update is called once per frame 

void Update() { 

    if (Input.GetKeyDown("w")) for > (deltaTime * 4) { 
    public float speed = 6.0F 
    } 

    float translation = Input.GetAxis("Vertical") * speed; 
     float strafe = Input.GetAxis("Horizontal") * speed; 
     translation *= Time.deltaTime; 
     strafe *= Time.deltaTime; 

     transform.Translate(strafe, 0, translation); 

     if (Input.GetKeyDown("escape")) 
      Cursor.lockState = CursorLockMode.None; 
    } 
} 

我並不需要立即回答,但你應該考慮當你看到這個回答。

+0

嘛'如果(Input.GetKeyDown( 「W」))爲>(*的DeltaTime 4)'沒有任何意義。你想在這裏完成什麼? – Draco18s

回答

0

嘗試此代碼:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class CharacterControls : MonoBehaviour { 

    public float base_speed = 3.0f; 
    public float max_speed = 6.0f; 
    private float current_speed; 

    // Use this for initialization 
    void Start() { 
     current_speed = base_speed; 
     Cursor.lockState = CursorLockMode.Locked; 
    } 

    // Update is called once per frame 
    void Update() { 

     if (Input.GetKey(KeyCode.W) && current_speed < max_speed) { 
      current_speed += 1 * Time.deltaTime; 
     } else if (!Input.GetKey(KeyCode.W) && current_speed > base_speed) { 
      current_speed -= 1 * Time.deltaTime; 
     } 

     float translation = Input.GetAxis("Vertical") * current_speed; 
     float strafe = Input.GetAxis("Horizontal") * current_speed; 
     translation *= Time.deltaTime; 
     strafe *= Time.deltaTime; 

     transform.Translate(strafe, 0, translation); 

     if (Input.GetKeyDown("escape")) 
      Cursor.lockState = CursorLockMode.None; 
    } 
} 

該代碼將採取base_speed(起始量,在這種情況下,我也使用用於正常量),並將其設置到用於操縱current_speed你的當前速度不會失去基礎速度(保持參考起始金額,如果我們沒有這個,我們不知道何時停止加速並且必須對它進行硬編碼,這從來都不是好的)。

當你按下W而沒有完全加速時,如果你沒有按下W並加​​速,你將開始加速,開始減速直到達到基本速度。

您的代碼甚至不會編譯因爲

if (Input.GetKeyDown("w")) for > (deltaTime * 4) 

適當的for循環看起來是這樣的:

for (int i = 0; i < 10; i++) { } 

,你不能用它if語句內。

閱讀thisthis

相關問題