Android jerky update() camera pan

Im trying to make a camera pan script which moves with touch. The script works fine but the movement jerks and is not fluid. The fps is around 50-60. The fps seems constant. The movement is fine except for the jerkiness. Ive tried time.deltatime as well as smoothdeltatime but doesnt seem to fix.

Camera cam;
float locate;
Vector3 pos;
public int smoothing = 1;

void Update(){

        if (Input.GetTouch (0).phase == TouchPhase.Moved) {
            if (cam.ScreenToWorldPoint (Input.GetTouch (0).position).x > 0) {
                locate = Input.GetTouch (0).deltaPosition.x * (Time.smoothDeltaTime * smoothing);
                pos = new Vector3 (locate, 0, 0) + cam.transform.position;
                cam.transform.position = pos;
            }
        }
    }

I’m assuming that you want the camera to move to the right when the right side of the screen is touched. Right now this is checking if the touch’s world x position is greater than 0, and once the camera moves right, all touches will be greater than 0 in world space.

Instead, you can use the Viewport position of the touch, which goes between 0,0 and 1,1. So if the touch x is greater than 0.5f then the right half of the screen was touched no matter where the camera is in the world.

Try this and let me know if it works and/or makes a difference:

public float moveSpeed = 1f;
private Vector3 targetPosition;
private Touch currentTouch;

private void Update() {
    currentTouch = Input.GetTouch(0);
    if(currentTouch.phase == TouchPhase.Moved) {
        if(Camera.main.ScreenToViewportPoint(currentTouch.position).x > 0.5f) {
            targetPosition = (Vector3.right * currentTouch.deltaPosition.x) + Camera.main.transform.position;
        }

        Camera.main.transform.position = Vector3.MoveTowards(Camera.main.transform.position, targetPosition, moveSpeed * Time.deltaTime);
    }
}

If that doesn’t do it for you, try this as well:

public float moveTime = 1f;
private Vector3 targetPosition;
private Touch currentTouch;
private Vector3 velocity;
private void Update() {
    currentTouch = Input.GetTouch(0);
    if(currentTouch.phase == TouchPhase.Moved) {
        if(Camera.main.ScreenToViewportPoint(currentTouch.position).x > 0.5f) {
            targetPosition = (Vector3.right * currentTouch.deltaPosition.x) + Camera.main.transform.position;
        }

        Camera.main.transform.position = Vector3.SmoothDamp(Camera.main.transform.position, targetPosition, ref velocity, moveTime);
    }
}
1 Like

Yes this works much much smoother! Thank you for your help. But do you know why this is smooth and my code isnt?

I would think it’s because I’m moving the camera towards a ‘target position’ each frame rather than setting a hard position. Because of this, the camera is always moving in a consistent way, and even if the target position changes wildly, the camera will interpolate smoothly towards it.

1 Like