2015-09-17 10 views
0

我遇到了一個問題,我的gameObject幾乎跳不出來。我認爲這與moveDirection有關,因爲當我註釋掉p.velocity = moveDirection時,跳躍會起作用。問題讓我的GameObject同時向前移動和正確跳轉

有關如何解決此問題的任何建議?

using UnityEngine; 
using System.Collections; 

public class Controller : MonoBehaviour 
{  
    public float jumpHeight = 8f; 
    public Rigidbody p;  
    public float speed = 1; 
    public float runSpeed = 3; 
    public Vector3 moveDirection = Vector3.zero; 

    // Use this for initialization 
    void Start() 
    { 
     p = GetComponent<Rigidbody>(); 
     p.velocity = Vector3.zero; 
    } 

    // Update is called once per frame 
    void Update() 
    { 
     if (Input.GetKeyDown (KeyCode.Space)) 
     { 
      p.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse); 
     } 

     Move(); 
    } 

    void Move() 
    { 
     if(Input.GetKey(KeyCode.D)) 
     { 
      transform.Rotate(Vector3.up, Mathf.Clamp(180f * Time.deltaTime, 0f, 360f)); 
     } 

     if(Input.GetKey(KeyCode.A)) 
     { 
      transform.Rotate(Vector3.up, -Mathf.Clamp(180f * Time.deltaTime, 0f, 360f)); 
     } 

     moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); 
     moveDirection = transform.TransformDirection(moveDirection); 

     if(Input.GetKey(KeyCode.LeftShift)) 
     { 
      moveDirection *= runSpeed; 
     } 
     else 
     { 
      moveDirection *= speed; 
     } 

     p.velocity = moveDirection; 
    } 
} 
+0

「關於如何解決這個問題的任何建議?」 - 註釋掉'p.velocity = moveDirection'? –

+0

我忘記提到,當我註釋掉p.velocity = moveDirection時,跳躍作品時,對象無法移動。 –

+1

推薦閱讀:[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

回答

0

嘗試爲您的jumpheight變量使用更高的值。我通常會帶着幾百個東西去。

0

因爲剛好在AddForce(...)字面上在同一幀內,您覆蓋的速度與moveDirection。您應該加入當前的速度,而不是完全覆蓋它是這樣:

Vector3 velocity = p.velocity; 
p.velocity = velocity + moveDirection; 

這就是爲什麼Unity warns against messing with velocity directly,你們會有最好只是在做另一AddForce(...)爲您的運動:

p.AddForce(moveDirection * Time.deltaTime); 

編輯:

我不喜歡離開OP的問題離題太遠,但你的新問題可能是因爲你做得太多moveDirection h什麼,我甚至不明白爲什麼ALF但它應該在大多數情況下是這樣的:

moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")).normalized; 
float _speed = Input.GetKey(KeyCode.LeftShift) ? runspeed : speed; 

p.AddForce(moveDirection * _speed * Time.deltaTime); 
+0

好吧,我嘗試了這兩件事情,跳躍的工作正常,但對於第一個對象移動到遠處,當我拿着移動鍵時速度不是恆定的,並且當我擡起它時並沒有完全停止,對象的addForce不會向前移動。 –

+0

對於LOLslowSTi我不明白float_speed行與問號和runpeed:speed; –

0

好吧,我想通了,如何解決它。而不是那些MoveDirection變量我改變它

if(Input.GetKey(KeyCode.W)) { 
     transform.position += transform.forward * Time.deltaTime * speed; 
    } 
    if(Input.GetKey(KeyCode.S)) { 
     transform.position -= transform.forward * Time.deltaTime * speed; 
    } 

現在它工作得很好。

相關問題