0
\$\begingroup\$

I am trying to move camera only on the x-axis based on a Swipe. I want it to move smoothly to the left or right. Right now, it seems to be simply be jumping a few pixels forward, and not Lerping at all. What am I doing wrong?

This script is attached directly to a Cinemachine camera.

Here is the code:

private void Update()
    {
        if (Touch.activeFingers.Count == 1) {
            var touch = Touch.activeTouches[0];

            if (touch.phase == TouchPhase.Began)
            {
               
                startPos = touch.screenPosition;
                
            }

            

            if (touch.phase == TouchPhase.Ended && coroutineAllowed)
            {
                endPos = touch.screenPosition;
                
            }
                 

            TriggerSwipe(startPos, endPos);
        }
    }

   
    private void TriggerSwipe(Vector2 start, Vector2 end)
    {
        Vector3 direction = end - start;
        Vector2 direction2D = new Vector2(direction.x, direction.y).normalized;

        if (direction != prevDirection)
        {
            if (Vector2.Dot(Vector2.left, direction2D) > directionThreshhold)
            {
                var targetPosition = new Vector3(start.x, transform.position.y, transform.position.z);
                transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);
            }

            if (Vector2.Dot(Vector2.right, direction2D) > directionThreshhold)
            {
                var targetPosition = new Vector3(-start.x, transform.position.y, transform.position.z);
                transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);
            }

            prevDirection = direction;
        }

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Your function is called only once, consider a coroutine \$\endgroup\$
    – Zibelas
    Jul 26 at 19:04
  • 1
    \$\begingroup\$ Looks like you're making the common error of treating Lerp like a tweening routine that will continue to execute on subsequent frames after you invoke it once. But it's just a math function — if endPos and startPos are the same on subsequent frames, you skip the Lerp call and leave the object where it was after the first frame of the movement. I've answered versions of this question a few times, so you can find some strategies to correct this code in those existing answers. \$\endgroup\$
    – DMGregory
    Jul 26 at 19:21

0

You must log in to answer this question.

Browse other questions tagged .