- Home /
Need to find a point along a linecast slightly closer to the origin than hit.point
RaycastHit hit;
if (Physics.Linecast(head.transform.position, mainCam.transform.position, out hit)){
mainCam.transform.position = hit.point;
}
I'm trying to keep my camera from going through walls, and my solution for this was to have a linecast from the head of the character to the camera, and adjust the cameras location relative to the wall. I looked up GetPoint, but it doesn't apply to linecasts, and things get screwy when I use any other type of ray for this. I'm lost here.
Answer by Deign · May 28, 2014 at 04:16 AM
Vector3 distanceVec = hit.point - mainCam.transform.position;
mainCam.transform.position += distanceVec * percentOfDistanceToMove;
The last line can be replaced with
mainCam.transform.position += distanceVec.normalized * (distanceVec.magnitude - stopDistance);
The first one moves you to a percentage distance closer to the position you're looking at. percentOfDistanceToMove = 1 puts you right on top of hit.point. percentOfDistanceToMove = 0.75 puts you at 75% the distance that the camera was at to the hit.point position. The second one moves you to a set distance from the hit.point. A value of 5 in stopDistance will place the camera 5 units away from hit.point
The second line you supplied didn't work. The camera moved to a new position (off sides) and stayed there. I used the first one, which works, but I had to set percentOfDistanceTo$$anonymous$$ove to 1.5, because anything less than 1.0 set the camera farther back behind the object. I'm in class right now, so I'll get back to this later.
There's a typo, sorry about that. It should be += and not =. I have edited my answer to fix the typo :)