Hello all,
I’m working on modifying a third person camera script to keep objects from occluding the view between the player and the camera. What I’m trying to do is generate a raycast from the camera position to the player position (ignoring the player collider), and if any object collisions are detected, lerp the camera towards the player.
The only problem is, the raycast doesn’t seem to be registering any collisions. I can park a cabin between the player and the camera, and nothing happens. If I tell it not to ignore the player’s collider, the camera will faithfully lerp towards to the player until it hits its minimum distance. The objects in the game world have colliders on them, so I’m not sure what’s going on here.
The relevant code is here:
Vector3 toTarget = targetPoint - cam.transform.position;
float distToTarget = Vector3.Distance(cam.transform.position, targetPoint);
if( Physics.Raycast(cam.transform.position, toTarget, distToTarget, LayerMask.NameToLayer("Player") )) {
distance = Mathf.Clamp((distance - .5f), 3.0f, 15.0f);
print("Occluded!");
}
with the player object assigned to the Player layer, and targetPoint being the player’s position.
Any help is appreciated.
No ideas on this? Does my script at least look kosher?
The main problem that leaps out at me is that you’re not ignoring the player collider’s layer, you’re ignoring everything but that layer. Writing ~ in front of LayerMask.NameToLayer(“Player”) to invert the mask should have the desired effect, although you might need a more specific mask in practice.
Hmm… when I negate it out, it has the same problem of zooming in constantly to the player. I’ll fiddle around with the layers and see if I can get it to work.
Thanks.
Okay, layer problem has been solved. On to the next one~~
The camera lerps correctly when it detects a collision. However, it seems to stop once it gets inside the object it’s colliding with, instead of going all the way through until it passes out of the object. I tried to set a flag that gets set while a collision is happening and only lerping if it’s true, but then it lerps all the way to the player and never stops-- if you zoom the camera out, it just zooms back to the player. If I set the flag to false if it’s not colliding, I’m back to the original problem- it lerps for a bit and then stops when it’s sitting inside the object.
Any ideas on this?
Update: Fixed it, sort of. I used a Linecast instead of a Raycast and it seems to be happier.
Now to make it look less janky…
What was your NameToLayer solution?