- Home /
The question is answered, right answer was accepted
Camera collision using raycasts (problems with SmoothDamp)
void WallDetection()
{
float wallBuffer = 2f;
if (Physics.Raycast(TargetLookAt.position, -transform.TransformDirection(Vector3.forward), out hitInfo, Distance, walls))
{
Distance = hitInfo.distance - wallBuffer;
}
}
I have a functional Raycast solution in my camera code that tracks wall collisions and adjusts the camera relative to the player, except the camera code I have is built off code that has built in smoothing into the distance calculation, and it's making my raycast "bounce" off colliders and messing up the raycast check.
void CalculateDesiredPosition()
{
// Evaluate distance
Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velDistance, DistanceSmooth);
// Calculate desired position
desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
}
Vector3 CalculatePosition(float rotationX, float rotationY, float distance)
{
Vector3 direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0f);
return TargetLookAt.position + rotation * direction;
}
void UpdatePosition()
{
var posX = Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth);
var posY = Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth);
var posZ = Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth);
position = new Vector3(posX, posY, posZ);
transform.position = position;
transform.LookAt(TargetLookAt);
}
The issue in question - I'm a novice coder so I'm probably missing something obvious. I'd like it to either make it perform the same task without the smoothing issue, or preferably modify the Raycast code so that it takes the smoothing in mind when calculating collisions.
Any help is appreciated
Answer by cyberspacecat_ · Feb 11, 2019 at 01:15 AM
After some trial and error I managed to make it functional for my own purposes. - I had overthought this problem severely and could, instead of using a SmoothDamp, smooth the distance with a simple Lerp.
void CalculateDesiredPosition()
{
// Evaluate distance
Distance = Mathf.Lerp(Distance, desiredDistance, DistanceSmooth * Time.deltaTime);
// Calculate desired position
desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
}
And modified my Raycast code slightly, as I found no wall clipping issue using a Lerp and the extra unit made the camera spin wildly as I got close to the wall.
void WallDetection()
{
if (Physics.Raycast(TargetLookAt.position, -transform.TransformDirection(Vector3.forward), out hitInfo, desiredDistance, walls))
{
Distance = hitInfo.distance;
}
else
{
Distance = desiredDistance;
}
}
Follow this Question
Related Questions
How do I get my camera to rotate around the y=0 coordinate it's looking at? 0 Answers
Security Camera Scripts? 1 Answer
Raycasting with Rotation of Camera 0 Answers
Multiple Camera.main.ScreenPointToRay 1 Answer
Raycast From Camera to Object 1 Answer