- Home /
Problems with 2D Camera Shaking
Hey guys! I've looked through a lot of the answers and managed to get some smooth camera code to follow my target. However I wanted to add bounds to the current level that the camera cannot see past, so I found the clamp function.
After adding the clamp function my camera worked correctly at around 60fps. Today I went to go test my game again and it was running at around 400fps (Not sure if this is relevant) but the camera was violently shaking and no changes to code have been performed.
Attached is my code and I am not sure what I need to change to fix this problem:
void followPlayer(){
float cameraClampX = Mathf.Clamp(transform.position.x, -15, 13);
float cameraClampY = Mathf.Clamp(transform.position.y, 2, 14);
Vector3 point = camera.WorldToViewportPoint(target.position);
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.4f, 0.4f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
Vector3 currentplace = new Vector3(cameraClampX, cameraClampY, transform.position.z);
//Vector3 cameraMove = Vector3.MoveTowards(currentplace, destination, 0.5f);
Vector3 cameraMove = Vector3.SmoothDamp(currentplace, destination, ref velocity, dampTime);
transform.position = cameraMove;
}
If anyone would like to explain to me a more efficient way of making this work or something that will even fix this problem I would be extremely grateful!
Thank you
Answer by CTatz · Feb 22, 2013 at 02:27 AM
Ah, for anyone looking the answer is pretty simple:
When having the camera follow a player make sure you have the clamp boundaries checking from the players position and not the camera! I guess it having to run through and check the cameras position from the past while the player is already somewhere else makes it seem all jerky.
Code that sort of explains it:
float targetClampX = Mathf.Clamp(target.position.x, -15, 15);
float targetClampY = Mathf.Clamp(target.position.y, 2, 14);
Vector3 targetPosition = new Vector3(targetClampX, targetClampY, mainCameraZValue);
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth);
Answer by Nelis · Feb 20, 2013 at 02:18 PM
Are you sure that your camera is shaking or is it your player who is clipping
If I take off the clamp then the camera runs smooth. Would that still happen if the player clipped?
Answer by Perengano · Apr 22 at 02:30 AM
put the camera script in the last place of the script execution order
Your answer
Follow this Question
Related Questions
Why does the camera smoothly follow in one direction but not the other? 0 Answers
How to smoothly move a 2D camera without ghosting 3 Answers
Map level selection slide smoothly 3 Answers
Smooth Camera 2D 0 Answers
The sprite that is being followed by thr camera is very jittery and doesn't look very nice at all. 2 Answers