+ 2
How to make a camera following script in csharp for unity games ?
I want your help guys.
1 Answer
+ 3
There are many ways to do this, here is one (For main camera).
First, you probably want your camera to be in its own position relative to whatever object it is following.
So, we will keep its position by storing its distance to the object.
Vector3 offset;
void Start (){
offset = Vector3.Distance(camera.main.transform.position, ObjectPosition);
}
Then in our update, we will make our camera move along with the object. We will continue to stay offset far apart from the object.
I'll use the Lerp function:
https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
Something along the lines of:
Let CamFirstPost be the position of the camera when the object moves.
Camera.main.transform.position =
Vector3.Lerp
(CamFirstPos, ObjectPosition + offset, FOLLOW_SPEED * Time.deltaTime);
Or you could also directly change the cameras position based on how much the object moves.
(Add to the cameras position by how much the object moved).
You can do a similar thing with rotation if you want the camera to turn as well.