I have a basic idea about how to do this, but I’m having trouble with the math behind it.
Essentially, I have a camera that orbits around the player in a 3rd person view, and I’m implementing a system that moves the camera in closer if something gets in the way. I’ve figured out how to make this work. However, I want to extend the linecast past my end vector about half a unit so that I can create a little buffer between the camera and the wall to avoid clipping into it.
I can’t simply subtract from the linecast distance, because it moves the camera away from the wall. The camera will Lerp back to the default distance, hit the wall, and move away again, creating a very annoying effect.
What I need is the unit vector of the linecast so I can use it to find a position vector 0.5 units from my camera. I want to use this as the endpoint instead, effectively “extending” the linecast behind my camera.
Here’s a bit of my code for context:
// Linecast to move the camera closer to the player if something gets in the way
RaycastHit linecastInfo;
if(Physics.Linecast(player.transform.position, Camera.main.transform.position,
out linecastInfo))
{
// Ignore really short linecasts
//(buggy linecasts are constantly detecting hits at extreme close range, why?)
if (linecastInfo.distance > 0.5f)
{
currentDistance = linecastInfo.distance;
}
}
else
{
currentDistance = Mathf.Lerp(currentDistance, defaultDistance, 0.75f);
}
BONUS: If anyone can tell me why my linecast is spazing out and constantly recording hits at extremely short distances (like 0.02 units, 0.004 units etc) even when nothing is obstructing the view, that would be great. Right now I have a pretty ugly hack in place to throw out any linecasts under 0.5 units in distance.