I am trying to make a script for the SpringFollowCamera to make the camera move towards the player when the camera collides with the terrain. Only thing is, when it collides with the terrain, it now flickers from the original position to the calculated new position and back. I am using the following function:
void TerrainCollision()
{
var relativePos = transform.position - (target.position);
RaycastHit hit = new RaycastHit();
var RawCamPos = new Vector3(PlayerCamera.position.x,PlayerCamera.position.y, PlayerCamera.position.z - distanceOffset);
if(Physics.Raycast(RawCamPos, relativePos, out hit, distance+0.5f))
{
if (hit.transform.tag == "Terrain")
{
Debug.DrawLine(target.position,hit.point);
distanceOffset = distance - hit.distance + 0.8f;
distanceOffset = Mathf.Clamp(distanceOffset,0,25);
}
}
else
{
distanceOffset = 0;
}
}
Does anyone have any idea how I could stop the flickering so it adjusts the distance between the camera and the player more smooth?
Thanks in advance.
I am not familiar with a SpringFollowCamera (perhaps SmoothFollowCamera)
In general, working with collisions in cameras is fairly simply and straight forward. You can easily create a funciton to call from the MouseOrbit or SmoothFollowCamera’s to adjust for collision. You would need to simply know how far you want to come back from a collision.
Here is one that requires two basic variables to work; Offset, which is the amount of distance that the camera comes back when it finds a hit. Target, which is fairly self explanatory.
So use the original script, set your camera and position according to the distance that you are working with, then call this function to offset the camera according to a collision between the target and camera. The target should be in the original script, so it should work by just adding the offset.
Transform target;
float offset=1.0f;
void CheckCameraCollision(){
Ray ray=new Ray(target.position, transform.position - target.position);
RaycastHit hit = new RaycastHit();
if(Physics.Raycast(ray, out hit, (transform.position - target.position).magnitude)){
if(hit.distance > offset)
transform.position=ray.GetPoint(hit.distance - offset);
else
transform.position=target.position;
}
}
I tried your script and I cannot get it to work. I cannot simply use an original SmoothFollowCamera script as my camera script is customized so far that it would be too much work to create a new one. Is there a way to change:
if(hit.distance > offset)
transform.position=ray.GetPoint(hit.distance - offset);
else
transform.position=target.position;
so that not the transform.position will be returned but the correct offset? I mean, what would be the right calculation for that?
Thanks in advance.
i think we just add capsule collider/spherecollider and rigidbody with spesifics 1.0f points for both drag and angular drag