2017-02-21 47 views
0

到左邊,但不斷前進,有什麼可能的方法來解決這個問題。球員的跑動腳本當我按住'w'並移動相機時,播放器將不會在相機方向上移動,例如,如果我向前移動相機並將其向左移動,它將不會移動到相機所面對的位置

public float movementspeed = 5.0F; 

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

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

    float translation = Input.GetAxis("Vertical") * movementspeed; 
    float straffe = Input.GetAxis("Horizontal") * movementspeed; 
    translation *= Time.deltaTime; 
    straffe *= Time.deltaTime; 

    transform.Translate(straffe, 0, translation); 
} 

}

和照相機查看腳本

public float xMoveThreshold = 1000.0f; 
public float yMoveThreshold = 1000.0f; 

public float yMaxLimit = 50.0f; 
public float yMinLimit = -50.0f; 


float yRotCounter = 0.0f; 
float xRotCounter = 0.0f; 

Transform player; 

void Start() 
{ 
    player = Camera.main.transform; 
} 

// Update is called once per frame 
void Update() 
{ 
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime; 
    yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime; 
    yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit); 
    //xRotCounter = xRotCounter % 360;//Optional 
    player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0); 
} 

}

Picture 1

Picture 2

+0

我將第一個腳本附加到相機,第二個腳本爲空gameobject。我能夠移動和旋轉相機。移動很好。它總是移動到相機所面對的方向。你有什麼問題? – Programmer

+0

說我向左看,然後按'w'它不會向左走。移動方向不會隨着相機而改變,並且無論我面對什麼樣的方式都會以特定方式進行,就像如果我向前看並按下'w'並且不接觸相機,它將會移動筆直的,但如果我把相機往回看並按下'w'它會倒退 – Johnny

+1

隨着您在問題中更新的圖像,**請勿**將相機放在GameObject下。以相反的方式去做。使該播放器成爲相機的子節點,然後將兩個腳本附加到相機,相機現在是播放器的父對象。 – Programmer

回答

0

您需要使用de相機轉換才能做到這一點。類似於:

public float movementspeed = 5.0F; 
public Transform cameraTransform; 

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

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

    float translation = Input.GetAxis("Vertical") * movementspeed; 
    float straffe = Input.GetAxis("Horizontal") * movementspeed; 
    translation *= Time.deltaTime; 
    straffe *= Time.deltaTime; 

    Vector3 movement = cameraTransform.Forward * translation + cameraTransform.Right * straffe; 
    transform.position = transform.position+ movement; 
}