Zoom to mouse position like 3ds Max in Unity3d

2019-03-02 05:10发布

问题:

What I want to achieve is to be able to zoom the camera using the mouse wheel to where my mouse is. Think of it more like how 3ds max does this. The camera zooms into the point where the mouse is and there are no jerks or snaps.

This is my current implementation but this assumes the target is in the center. If I move the target position the camera snaps to that position and basically brings it to the center.

targetDist -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed * 0.5f * (isOrtho ? 15f : 1f);
targetDist = Mathf.Max(0.1f,targetDist);
distance = moveSmoothing * targetDist + (1-moveSmoothing )*distance;

transform.localRotation = Quaternion.Slerp( transform.localRotation, targetRot, rotateSmoothing * deltaTimeFactor );

target.position = Vector3.Lerp(target.position, targetLookAt, moveSmoothing * deltaTimeFactor);
distanceVec.z = distance;

transform.position = target.position - transform.rotation * distanceVec;

Any thoughts?

回答1:

So I got around to figuring it out. For anyone looking for this. This script is applied on the Camera and this is in the Update function.

if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
    RaycastHit hit;
    Ray ray = this.transform.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
    Vector3 desiredPosition;

    if (Physics.Raycast(ray , out hit))
    {
        desiredPosition = hit.point;
    }
    else
    {
        desiredPosition = transform.position;
    }
    float distance = Vector3.Distance(desiredPosition , transform.position);
    Vector3 direction = Vector3.Normalize( desiredPosition - transform.position) * (distance * Input.GetAxis("Mouse ScrollWheel"));

    transform.position += direction;
}


标签: c# unity3d zoom