- Home /
RayCasting from camera to player
I'm creating a game with a 3th person view. The camera follows the player throughout the map. But if I get to the very bottom of the map, the boundary (box) stops the player. The camera is following from a small distance, resulting the camera to be found at the other side of the wall (not seeing the player).
I'm trying to solve this problem by casting a Raycast to the Player GameObject. If the player is not seen, the camera should move along the y-axis (up) untill he sees the player again.
In the current code I have, I try to raycast and get information about the hitted object. The camera always looks at the player object. Even though, sometimes I get the message "Block" and sometimes the message "Plane", but never "Player", "Sphere" (which is the player's hull) or "Boundary". What is required for the raycast to see/hit them?
Current code:
var hit: RaycastHit;
var ray: Ray = camera.ScreenPointToRay(target.transform.position);
if (Physics.Raycast(ray, hit)) {
var objectHit: Transform = hit.transform;
Debug.Log(objectHit);
}
Answer by Nanorock · Jan 24, 2013 at 12:56 PM
ScreenPointToRay needs a Screen position, not the target transform. http://docs.unity3d.com/Documentation/ScriptReference/Camera.ScreenPointToRay.html
I would try :
var screenPos : Vector3 = camera.WorldToScreenPoint (target.transform.position);
var ray: Ray = camera.ScreenPointToRay(screenPos);
Debug.DrawRay (ray.origin, ray.direction * 50, Color.yellow);
Answer by KoningStoma · Jan 24, 2013 at 12:40 PM
I would do it the other way around.
Cast a ray from the player in the direction of the camera. If the ray hits a wall that's closer to the player than the preferred camera distance, move the camera towards the player.
Your answer
Follow this Question
Related Questions
Problem With Raycasts, Interaction Script. 1 Answer
A node in a childnode? 1 Answer
How do I check if the mouse is over a VISIBLE vertex? 1 Answer
Raycast From Camera to Object 1 Answer