Camera Script: Preventing object occlusion
Hey, today I want to share with you a camera script that prevents environment objects from occluding the player.
I’m currently working in a project where the camera follows the player from a fixed distance and angle, independently of the player direction.
ADDING COLLISION DETECTION
The camera initial behaviour was fairly easy to implement. Now, the problem was preventing the player from being occluded by obstacles in the environment. IMAGE1.
The intended behaviour was to position the camera in the collision point with the obstacle and rotate it in order to keep the player in sight. To solve it, I’ve added a trigger to the camera to detect any collision. In this way, I was able to detect when the camera was colliding with another object and position it accordingly: IMAGE2
Now, I just had to stop the camera movement and adjust the rotation in order to keep the player in sight:
public Vector3 ClosestPoint(Vector3 position);
This method, returns the position of the closest point in the collider surface, to the position given in the argument. In this case, I was looking for the closest point to the player position and using it to properly position the camera at the intersection point.
To this point, anytime the camera would collide with any other object, it would move to the surface nearest point to the player and adjust it’s rotation accordingly. This was all going really well, and I thought my job was nearly done. Always an optimistic.
Then the following question hit me:
Linecast to the rescue!
public static bool Linecast(Vector3 start, Vector3 end, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
A linecast casts an invisible line between two points returning true if it’s intersected by any collider.
So, in this case, in addition to the trigger, I’ve added a linecast between the camera and the player position. Every time the cast detects a collider it behaves exactly in the same way as with the trigger.
Then, after a few tweaks to make it work with both systems, I think my camera script is ready. At least a very first version.
As always, all feedback is more than welcome.
Happy coding 🙂