Zoom camera with touch on Unity

Asked

Viewed 377 times

0

I am working with this code below controlling the distance from the camera to the character, this distance is the result of linear interpolation between a minimum and maximum offset, where the variable float distance controls this result.

Vector3.Lerp(minOffset, maxOffset, distance)

But in the zoom function the result of Vector2.Distance is being quite large, between 110,000 and 890,000, which is certainly beyond the minimum and maximum necessary to control Lerp.

void Zoom()
{
    if (Input.touchCount != 2)
        return;

    Touch touch0 = Input.GetTouch(0);
    Touch touch1 = Input.GetTouch(1);

    if(touch0.phase == TouchPhase.Moved || touch1.phase == TouchPhase.Moved)
    {
        distance = Vector2.Distance(touch0.position, touch1.position);
    }
}

I’ve tried using Mathf.Clamp, but logically the value of Vector2.Distance is quite large for the result to be less than 1F.

distance = Mathf.Clamp(Vector2.Distance(touch0.position, touch1.position), 0F, 1F)

How can I reduce the minimum and maximum of the Vector2.Distance at min 0F and max 1F?

Remembering that I must consider that in some devices the result between the touch0 and touch1 in the Vector2.Distance may be greater.

  • You have a script that does something similar to this in the Asset Store: https://www.assetstore.unity3d.com/en/#! /content/14489 .

1 answer

0

I am without Unity3d installed at the moment to test, but I have the impression that the Touch.position returns a Vector2 with the coordinate onscreen. Thus, the distance calculation will return a measure in pixels, so that the higher the resolution of the image presented, the higher the number returned to the same finger positions.

So what you can try to do is calculate the distance between the vectors of the normalized positions, using the attribute normalized:

distance = Vector2.Distance(touch0.position.normalized, touch1.position.normalized);

A normalized vector has the coordinates adjusted so that its magnitude becomes 1. Thus, its calculation of the distance between the normalized coordinates is independent of the resolution of the screen used. Note that this distance will be small and with decimal variations. Use it to weigh the camera’s distance similarly to what you’re already doing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.