I got it working somewhat, thanks for the tips!
No idea what fixed it though – I revised and revised untill it worked. And now, a different bug showed its ugly head.
Below is the code:
using UnityEngine;
using System.Collections;
public class ThirdPersonCamera2 : MonoBehaviour {
public Transform playerCam;
public Transform camLooker;
public Vector3 camVector, camOrigin, camOriginRot;
float camMaxDist;
bool isChanged=false;
RaycastHit hit;
int layerMask;
// Use this for initialization
void Start ()
{
playerCam = GameObject.Find("Main Camera").transform;
camLooker = transform.Find("CameraLooker");
camMaxDist = Mathf.Abs( Vector3.Distance( playerCam.position, camLooker.position ) );
layerMask = 1 << 9;
layerMask =~layerMask;
camOrigin = playerCam.localPosition;
camOriginRot = playerCam.localEulerAngles;
}
// Update is called once per frame
void Update ()
{
camMaxDist = Mathf.Abs( Vector3.Distance( playerCam.position, camLooker.position ) );
camLooker.transform.LookAt(playerCam);
camVector = camLooker.transform.TransformDirection(Vector3.forward);
Physics.Raycast(camLooker.transform.position, camVector, out hit, camMaxDist, layerMask);
if (hit.collider)
{
if ( isChanged == false )
{
isChanged = true;
}
playerCam.transform.position = hit.point;
playerCam.transform.LookAt(camLooker);
Debug.DrawLine(camLooker.transform.position, hit.point);
}
Debug.Log (hit.collider);
if ( ( isChanged == true ) ( !hit.collider ) )
{
playerCam.localPosition = camOrigin;
playerCam.localEulerAngles = camOriginRot;
}
}
}
The code works so that when there is no collider between the camera and the player (looking from the player’s perspective) the camera defaults back to it’s original location. Problem is, it seems that the raycast isn’t done each frame/does not return true each frame. Under certain angles there seems to be a collision one frame, and no collision the other. The Debug.Log literally spits out Null and the colliding object as it sees fit. Is there some limitation to the Raycast function?
The most disturbing part is that when the angle is right, it returns a constant stream of collisions, while moving a mouse just a bit (thus rotating the whole thing) makes the camera go back and forth. Could it be that it is still colliding with the CharacterController all the time? I made sure that the object is in the ignored layer, and set the mask according to the reference guide.
EDIT: I just went with a hunch, and yes, the problem is how far the raycast is actually cast. The jitter happens when the ray barelly touches the surface, and it seems the engine calculates differently for each frame (quite a bummer). Seems I’ll just have to make sure there is a buffer in the ray lenght.
EDIT: Feel free to laugh at my obvious mistake here ^^‘’ The distance of the ray was needlesly calculated each frame, and it changed for no good reason. All works fine and dandy now.