Raycasting for a third person shooter
I need to do a raycast from my player character, to my walkie talkie hit object, but I can't get my code to work, it always seems to be biased.
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
I thought I Debug.DrawRay(transform.position, playerHit.transform.position, Color.red);
should draw a red line from my player to the end of the green line when the camera hit the point, instead it pushes past to the floor.
+3
source to share
1 answer
Change Debug.DrawRay to Debug.DrawLine!
Debug.DrawRay requires Vector3 as the origin and Vector3 as the direction, not a second "target" position.
Here's my solution!
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);
}
}
+3
source to share