- Home /
Camera movement causes 2D sprites to shake/glitch/jitter
Can anyone help me with this problem? My script code is down below:
public GameObject target;
public float followAhead;
private Vector3 targetPosition;
public float smoothing;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
targetPosition = new Vector3 (target.transform.position.x, transform.position.y, transform.position.z);
if (target.transform.localScale.x > 0f) {
targetPosition = new Vector3 (targetPosition.x + followAhead, targetPosition.y, targetPosition.z);
} else {
targetPosition = new Vector3 (targetPosition.x - followAhead, targetPosition.y, targetPosition.z);
}
//transform.position = targetPosition;
transform.position = Vector3.Lerp (transform.position, targetPosition, smoothing * Time.deltaTime);
}
}
Answer by merkaba48 · Jul 04, 2017 at 07:32 PM
Are you rendering at a low resolution? If so, you might need to 'fix' the camera position to pixel positions. I've done this in my stuff by parenting the camera to an empty transform, and then moving the transform rather the camera, and then having a script on the camera that snaps it to the nearest pixel.
That way, your transform will always have the 'correct' position, but the camera will only move on the grid.
The camera scrip looks like this,
public class DiscretePositionFixer : MonoBehaviour
{
public float pixPerUnit = 16;
void LateUpdate()
{
transform.position = new Vector3(
Mathf.Round(transform.parent.position.x * pixPerUnit) / pixPerUnit,
Mathf.Round(transform.parent.position.y * pixPerUnit) / pixPerUnit,
transform.parent.position.z);
}
}
NB. I use LateUpdate to ensure the parent transform has updated its position before the camera 'fixes' itself.
Not sure if this is actually the problem you're having, mind.
But aren't you loosing the smooth follow effect by snapping the camera to the grid ?