I have managed to get the script partially working but on occasions camera either stops calculating collisions properly and goes beyond walls, or starts bouncing between max and min distance near walls or the camera distance exceeds max value for the camera distance.
I tried to follow numerous Youtube video guides so the code may and will be garbage, but I want to learn Unity and C#(have only basic C knowledge) by making my own code and not copying solutions made by others.
Script attached to empty object which is parent for camera with camera control script.
Any help and rotten tomatoes thrown my way will be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DungeonCameraCollision : MonoBehaviour {
public float minDistance = 0.5f;
public float maxDistance = 2.5f;
public float smooth = 10.0f;
public float distance;
private Vector3 PlayerDirection;
void Awake () {
PlayerDirection = transform.localPosition.normalized;
distance = transform.localPosition.magnitude;
}
void LateUpdate () {
Vector3 desiredCameraPosition = transform.TransformPoint(PlayerDirection * maxDistance);
RaycastHit hit;
if(Physics.Linecast(transform.parent.position, desiredCameraPosition, out hit))
{
Vector3 hitPoint = new Vector3(hit.point.x + hit.normal.x * 0.2f, hit.point.y, hit.point.z + hit.normal.z + 0.2f);
distance = Mathf.Clamp(hitPoint.x, minDistance, hitPoint.z);
}
else
{
distance = maxDistance;
}
transform.localPosition = Vector3.Lerp(transform.localPosition, PlayerDirection * distance, smooth * Time.deltaTime);
}
}