- Home /
Question by
AbubakrKhan · Apr 29, 2019 at 09:10 PM ·
unity 5cameraraycastcollider
Camera go through the wall. Please look at my script and help !!!
`
Using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public Vector3 offset;
public bool useOffsetValues;
public float rotateSpeed;
public Transform pivot;
// Start is called before the first frame update
void Start()
{
if(useOffsetValues)
offset = target.position - transform.position;
pivot.transform.position = target.transform.position;
//pivot.transform.parent = target.transform;
Cursor.lockState = CursorLockMode.Locked;
pivot.transform.parent = null;
}
// Update is called once per frame
void LateUpdate()
{
if (target != null)
{
pivot.transform.position = target.transform.position;
//get the x position of the mouse and rotate the player
float horizontal = Input.GetAxis("MouseX") * rotateSpeed;
pivot.Rotate(0, horizontal, 0, Space.World);
//get the x position of the mouse and rotate the player
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
pivot.Rotate(vertical, 0, 0, Space.World); //using x position to controll the y movement of the mouse
//limit up/down camera rotation
if (pivot.rotation.eulerAngles.x < 30f || pivot.rotation.eulerAngles.x > 180f)
{
pivot.rotation = Quaternion.Euler(45f, 0, 0);
}
//Move the camera based on the rotation of the target and original offset
float desiredYAngel = pivot.eulerAngles.y;
float desiredXAngel = pivot.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(desiredXAngel, desiredYAngel, 0);
transform.position = target.position - (rotation * offset);
//transform.position = target.position - offset;
if (transform.position.y < target.position.y)
{
transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
}
transform.LookAt(target);
}
}
}
Comment
If you're trying to prevent the player from rotating the camera into the wall, there are many ways to do it. One way would be to cast rays to the left and right of the camera, specify how close the camera has to get before it stops, then if it comes within that range, prevent the movement, or make it bounce back, ah dunno. Just make sure to ignore the player to be safe.