Unity smooth precise camera moving with inertia

2.2k Views Asked by At

I am trying to write a camera script but it is not working as intended.

void LateUpdate(){
        if (Input.GetMouseButtonDown(0)
        {
            _lastPosition = Input.mousePosition;
        }

        if (Input.GetMouseButton(0))
        {
            var delta = _lastPosition - Input.mousePosition;
            var deltaxz = new Vector3(delta.x, 0f, delta.y);
            transform.Translate(deltaxz * Time.deltaTime, Space.World);
            _lastPosition = Input.mousePosition;
        }
}

I wrote this code to move the camera but the mouse moves the camera strangely. If I move the mouse too fast, it moves fast. If slow, the camera moves slower than mouse.

I think that ScreenToWorldPoint can help, but the camera is RTS style, I want to move it like I am moving ground "drag and drop" \

2

There are 2 best solutions below

0
Jichael On

You should try using Vector3.Lerp(_lastPosition, deltaxz, someValue * Time.deltaTime)

This is what I use to make movements smoother and it's pretty good, just adjust someValue depending on what speed you want

3
caxapexac On

Thats because of deltaTime (it is always about 0.01f-0.02f = bad precision on lots of iterations ) You can use Lerp workaround to smooth moving like Jichael but with minor changing (it works with transform.positon directly), full code:

//new:
public float Sensitivity;

private Vector3 _lastPosition;

private void LateUpdate()
{
    if (Input.GetMouseButtonDown(0))
    {
        _lastPosition = Input.mousePosition;
    }

    if (Input.GetMouseButton(0))
    {
        var delta = (_lastPosition - Input.mousePosition);
        var deltaxz = new Vector3(delta.x, 0f, delta.y);
        //new:
        transform.position = Vector3.Lerp(transform.position, transform.position + deltaxz, Sensitivity * Time.deltaTime);
        _lastPosition = Input.mousePosition;
    }
}

P.S. why are you using LateUpdate?