Search code examples
unity-game-engine2d

How can i make camera move more when i finished drag in unity?


If it's simple question, sorry for the lack of knowledge.

I want to make camera still moving for a second after i finished drag.

(this is details : when i swipe screen, camera moves to opposite direction. and when i finished swiping, camera goes little bit more that direction.)

I tried Youtube and google, but couldn't find anything about it.

Please give me some hint?

This is current code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PanZoom : MonoBehaviour
{
    Vector3 touchStart;

    [SerializeField] float moveCameraSpeed = 3f;
    // Update is called once per frame
    void LateUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
        if (Input.GetMouseButton(0))
        {
            Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.position = Vector3.Lerp(Camera.main.transform.position,
            Camera.main.transform.position + direction, Time.deltaTime * moveCameraSpeed);
        }
    }
}

Solution

  • Save your move direction to a field. Then run some timer after the input is ended to set the move speed to zero after the needed time. Something like this (I wrote this code right here, so it can not be perfect for copy and paste, but I hope it is enough as an example)

    public class PanZoom : MonoBehaviour
    {
        Vector3 _touchStart;
        Vector3 _moveDirection;
        Coroutine _stopMoveRoutine;
        bool _isNeedMove;
    
        [SerializeField] 
        float _moveCameraSpeed = 3f;
        
        // Update is called once per frame
        void LateUpdate()
        {
            if (Input.GetMouseButtonDown(0))
            {
                StopCoroutine(_stopMoveRoutine);
                _isNeedMove = true;
                _touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }
            if (_isNeedMove == true)
            {
                _moveDirection = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
                _moveDirection.Normalize();
                transform.position += _moveDirection * Time.deltaTime * moveCameraSpeed; 
            }
            if(Input.GetMouseButtonUp(0))
            {
                _stopMoveRoutine = StartCoroutine(CoStopMove(1f));
            }
        }
    
        IEnumerator CoStopMove(float delay)
        {
            yield return new WaitForSeconds(delay);
            _moveDirection = Vector3.zero;
            _isNeedMove = false;
        }
    }
    

    By the way, imho, it will look better with slowing down speed instead of constant speed.