N0xus
N0xus

Reputation: 2724

Imposing a limit on translation movement

I have a zoom function on my camera that works by moving it on the Z axis when I pinch my fingers on the screen. However, when the camera moves into any value greater than zero, it has adverse effects on the rest of my camera code (movement, orbiting).

I put in a place a bool that would stop my camera moving once it got to a certain value, but it makes it very jumpy. And if your pinching, the camera will still move past the value until you let go.

So what I'm trying to do now, is use Mathf.Clamp to limit the range it can move, but I'm unsure if I'm using it correctly. This is my method right now:

void CameraZoom()
{
    // if fingers moved certain distance apart, zoom
    float dot = Vector2.Dot(Input.GetTouch(0).deltaPosition.normalized, Input.GetTouch(1).deltaPosition.normalized);

    if (dot < fingerDistance)
    {

        // Store both touches.
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);

        Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

        float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
        float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
       // apply zoom to camera
       transform.Translate(0, 0, -deltaMagnitudeDiff * perspectiveZoomSpeed);
       // clamp movement
        transform.position = new Vector3(transform.position.x, transform.position.y, Mathf.Clamp(0, 0, maxDistance));

        }
    }
}

I only want this to affect the Z axis, but when I zoom, my whole rig gets moved. What is it that I'm doing wrong?

Update

Ive changed my code to the following, but now when I zoom, it just jumps between two points and I can no longer zoom.

New code:

transform.Translate(0, 0, -deltaMagnitudeDiff * perspectiveZoomSpeed);
Vector3 pos = transform.position;
pos.z = Mathf.Clamp(transform.position.z, 0.0f, -200.0f);
transform.position = pos;

Upvotes: 0

Views: 108

Answers (1)

maZZZu
maZZZu

Reputation: 3615

Check the documentation for the Mathf.Clamp. You are using the parameters in the wrong order, which breaks the internal implementation of the function. The min value should be the second and the max value should be the third. So changing your line to this should stop the odd behavior:

pos.z = Mathf.Clamp(transform.position.z, -200.0f, 0.0f);

Upvotes: 1

Related Questions