- Home /
Top down camera lock
i have tried the solution in: http://answers.unity3d.com/questions/473917/how-to-prevent-camera-from-moving-through-meshes.html
my clip camera to the target so far is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraClip : MonoBehaviour
{
[SerializeField]
Transform target;
float yoffset = 20;
float xoffset = -10;
float zoffset = -10;
void LateUpdate()
{
transform.position = new Vector3(target.position.x + xoffset, target.position.y + yoffset, target.position.z + zoffset);
}
}
However, even though i have a collider and this clip on a parent to the main camera...the parent still goes right through collisions...the solution at the bottom of that link did not work. what is i missing to stop the camera from going through walls? I've uploaded a pic to show the problem
Answer by Ziron999 · Mar 01, 2017 at 09:27 AM
I have figured out a way to lock it myself:
public float lockxmin;
public float lockzmin;
[SerializeField]
float lockxmax;
[SerializeField]
float lockzmax;
if (transform.position.x < lockxmin || transform.position.x > lockxmax)
{
var temp = transform.position;
temp.x = Mathf.Clamp(temp.x, lockxmin, lockxmax);
transform.position = temp;
}
if (transform.position.z < lockzmin || transform.position.z > lockzmax)
{
var temp = transform.position;
temp.z = Mathf.Clamp(temp.z, lockzmin, lockzmax);
transform.position = temp;
}
This would restrict the camera to stay within a region specified by your $$anonymous$$ and max values not actually prevent the clipping issue of camera by it passing through other objects.
Right it essentially defines a map size which is all that's needed for the edges of terrain. The #1 issue is i can't clip terrain so I've been trying to find a way around that issue. That is why i had the question the way it is...Also the other answer only works for a 3rd person camera which is not what I'm doing either. It's top down like the title says. I tried to get it to work with my setup but can't do it. No matter what i do the clipping wouldn't work right.
Answer by HarshadK · Mar 01, 2017 at 08:46 AM
It is passing through because you are setting the position directly via transform.position
which will move the gameobject to that position ignoring the collisions. In Standard Assets there is a script called ProtectCameraFromWallClip
to prevent wall clipping of camera which you can use.
Although i found that CS file it is not that good on performance because it uses raycasting. However it is still an answer technically :)
Your answer
Follow this Question
Related Questions
How to rotate the camera with the player smoothly without the camera snapping back and forth? 2 Answers
Resetting Camera with a key input 1 Answer
Follow camera in 2d game 2 Answers
How to make a camera Follow an Object moving in zigzag path? 1 Answer
Gameobject flickers on camera follow. Solved but with silly method :/ 3 Answers