2015-04-23 144 views
3

我需要從我的玩家角色,到我的相機raycast的命中對象進行raycast,但我不能讓我的代碼工作,它似乎總是偏移。Raycasting第三人稱射擊

 void Update() { 

    RaycastHit hit; 
    Ray playerAim = playerCamera.GetComponent <Camera>().ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2)); 
    Physics.Raycast(playerAim, out hit); 
    Debug.DrawRay(playerAim.origin, playerAim.direction * hit.distance, Color.green); 

    if (Physics.Raycast(playerAim, out hit)){ 
     // something was hit 
     RaycastHit playerHit; 
     Physics.Raycast(transform.position, hit.transform.position, out playerHit); 
     Debug.DrawRay(transform.position, playerHit.transform.position, Color.red); 

     Debug.Log ("Distance from camera: "+ hit.distance); 
     Debug.Log ("Distance from player: "+ playerHit.distance); 
    } 
} 

http://i.stack.imgur.com/HzdVU.jpg

我想Debug.DrawRay(transform.position, playerHit.transform.position, Color.red);應該吸取我的球員到綠線攝像機命中點的最後一根紅線,而是過去拍攝到地面。

回答

3

將Debug.DrawRay更改爲Debug.DrawLine!

Debug.DrawRay需要一個Vector3作爲原點,一個Vector3作爲方向,而不是第二個「目標」位置。

這是我的解決方案!

enter image description here

void FixedUpdate() { 

    RaycastHit cameraHit; 
    Ray cameraAim = playerCamera.GetComponent <Camera>().ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2)); 
    Physics.Raycast(cameraAim, out cameraHit, 100f); 
    Debug.DrawLine(cameraAim.origin, cameraHit.point, Color.green); 
    Vector3 cameraHitPoint = cameraHit.point; 
    float cameraDistance = cameraHit.distance; 

    if (Physics.Raycast(cameraAim, out cameraHit)){ 
     // something was hit 
     RaycastHit playerHit; 
     Physics.Raycast(transform.position + new Vector3 (0f, 1.8f, 0f), cameraHitPoint-transform.position - new Vector3 (0f, 1.8f, 0f), out playerHit, 100f); 
     Debug.DrawRay(transform.position + new Vector3 (0f, 1.8f, 0f), cameraHitPoint-transform.position - new Vector3 (0f, 1.8f, 0f), Color.red); 

     float playerDistance = playerHit.distance; 
     Debug.Log ("Distance from player: "+ playerDistance); 
     Debug.Log ("Distance from camera: "+ cameraDistance); 
    } 

}