Trying to make the camera follow the player, but not clip through walls/objects. I know its the logic of my script being horribly wrong, so I need some help. The idea is to have the camera follow the target at a set height, and distance. Then, subtract that distance/height to be in between the player, and any objects which would normally have the camera clip through. I am trying to use raycast to detect it.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public LayerMask WallLayer;
public GameObject target;
public float cameraDistance = 2f;
public float cameraHeight = 3f;
public Vector3 desiredPosition;
private Vector3 cameraPosition;
void Start () {
// ... set referneces.
//I used this because FindWithTag wasn't working, I took everything out but the player(Which was tagged) and still.
target = GameObject.Find("Rabit Prefab");
}
void Update()
{
bool culling = false;
RaycastHit hit;
//Cast a ray from the camera to the player, checking only objects in the "wallLayer"
if (Physics.Raycast(cameraPosition, target.transform.position, out hit, WallLayer))
{
culling = true;
if (culling == false)
{
//Set the targetPosition to be the position of the target.transform.position, plus cameraHeight and cameraDistance.
cameraPosition = new Vector3(target.transform.position.x, target.transform.position.y + cameraHeight, target.transform.position.z - cameraDistance);
gameObject.transform.position = cameraPosition;
cameraPosition = new Vector3(target.transform.position.x, target.transform.position.y + cameraHeight, target.transform.position.z);
//Need a way to rotate with player here.
print("Nothing obstructing view, We should be in position.");
}
else if (culling)
{
cameraPosition = (hit.point - target.transform.position) / 0.8f;
print(hit + " is obstructing view, we should have moved into position now");
//Need a way to rotate with player here.
}
}
transform.LookAt(target.transform);
}
}