ReuJDon
ReuJDon

Reputation: 45

Clamp RotateAround object Unity

I am making a script to rotate my camera around a sphere but I need to clamp the y axis so the camera does not co over the polls of the sphere I am using rotate around to move my camera.

Thanks!

My current code

public float sensitivity = 1;
public float moveSpeed = 10;
public float maxUp = 45f;
public float maxDown = -45f;

public Transform target;

void Update()
{
    transform.LookAt(target);

    float HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed;
    float VerticalAxis = Input.GetAxis("Vertical") * moveSpeed;

    if (HorizontalAxis >= 1 || VerticalAxis >= 1 || HorizontalAxis <= -1 || VerticalAxis <= -1)
    {
        Quaternion targetPos = transform.rotation;
        targetPos.x += HorizontalAxis * sensitivity;
        targetPos.y += VerticalAxis * sensitivity;

        transform.RotateAround(target.position, Vector3.left, targetPos.y);
        transform.RotateAround(target.position, Vector3.up, targetPos.x);
    }
}

Upvotes: 0

Views: 934

Answers (1)

derHugo
derHugo

Reputation: 90580

Your code makes no sense to begin with.

You do

Quaternion targetPos = transform.rotation;
    targetPos.x += HorizontalAxis * sensitivity;
    targetPos.y += VerticalAxis * sensitivity;

Just to then use these as parameters in

 transform.RotateAround(target.position, Vector3.left, targetPos.y);
 transform.RotateAround(target.position, Vector3.up, targetPos.x);

A Quaternion has not three but four components x, y, z and w and they move in ranges between -1 and 1. You never touch the individual component of a Quaternion except you really know exactly what you are doing!

You rather simply want to use the HorizontalAxis and VerticalAxis directly as the parameters to RotateAround.


You could rather simply remember and clamp how much you already rotated like e.g.

private float rotatedY;

private void Update()
{
    transform.LookAt(target);

    // why two different multipliers anyway though?
    var HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed * sensitivity;
    var VerticalAxis = Input.GetAxis("Vertical") * moveSpeed * sensitivity;

    // would a positive rotation exceed the maxUp?
    if(rotatedY + VerticalAxis > maxUp)
    {
        // then rotate only so much that you terminate exactly on maxUp
        VerticalAxis = maxUp - rotatedY;
    }
    // would a negative rotation exceed the maxDown?
    else if(rotatedY + VerticalAxis < maxDown)
    {
        // then you rotate only that much that you terminate exactly on maxDown
        VerticalAxis = maxDown - rotatedY;
    }
    
    transform.RotateAround(target.position, Vector3.left, VerticalAxis);
    transform.RotateAround(target.position, Vector3.up, HorizontalAxis);

    // sum up how much you already rotated vertically
    rotatedY += VerticalAxis;
}

Upvotes: 1

Related Questions