I have several interior levels in my game. But my camera, which follows the main character, can go through walls and such. Is there any way I can prevent this?
Hey MrPenguin,
I had the same problem with my Celestial Sphere game, except that was exterior, but the concept should be the same.
My camera was always focused at my player GameObject so what I did was cast a ray backwards from the position of my player GameObject (setting the ray collision layer to ignore the player of course) through the position of my camera, and setting the ray’s distance to a tiny bit greater than the distance the camera usually keeps away from the player.
Then, if the ray hit anything, looking at hitInfo.point and your player GameObject’s position, you can calculate the distance at which there was a collision, and place your camera in front of that collision point, closer to your player GameObject.
I believe that for Raycasts to work you need to add Colliders to the objects should “collide” with the camera. It’s also a good idea to create a new Layer so that you can specify certain objects to be blocking and others to be non-blocking by using the layer mask on a Raycast.
Simply attaching a rigidbody collider to your camera might work too, although I’ve never actually tried it.
Good luck.
The suggestions above are great for detecting a collision between your camera and a wall (use a collider for the camera), or for detecting a “blocked view” state (raycasting to see if a model lies between the camera and the object of focus), but they don’t help with the “what to do next” part of the problem. And I’m afraid that I don’t have a specific suggestion to offer as it all depends on your game and your environments. This is a bit of a black art and it will take a lot of fine tuning and adjustment to get the results you’d like.
-
You can consider moving the camera into a non-colliding or non-blocked position.
-
You can consider making any objects that block your view semi-transparent.
-
You can combine both.
I’m sorry that I don’t have something definitive to share but this is a sticky issue that as mentioned, will take some fine tuning.
I am detecting the camera collision by doing a RayCast FROM the target (Player) to the Camera. First collision I come to, I force the camera to that position and compute my distance.
This doesn’t always work. For whatever reason, if it collides with the ground, it just keep trucking towards the player, passed the player and goes off into never neverland.
See my code at http://forum.unity3d.com/viewtopic.php?p=129508#129508
Any help would be good. It’s 95% done!
To fix this, give the ground a tag like “Ground” then check the collision marker, if it is “Ground” move to player but keep distance of X away from player in meters, once this distance is met, stop the movement to the player.
That’s cool and I can see how that would work, but what if I walked inside a building that was in a tree? I cannot label the floor with a “Ground” tag…
Or can I?