0
\$\begingroup\$

I have implemented a main camera that follows and orbits around an object (player). Now I would like to implement a Zoom In-Out mechanic. This functionality would allows the camera to approach the object that is being followed (lookAt()). Zooming in and out would be done by using the mouse scroll wheel. This is my code.

    public Transform PlayerTransform; 
    private UnityEngine.Vector3 _cameraOffset;
    [Range(0.01f, 1.0f)]
    public float smoothFactor = 0.5f;

    void Start()
        {
            _cameraOffset = transform.position - PlayerTransform.position;
        }
    void Update()
        {
            UnityEngine.Vector3 newPos = PlayerTransform.position + _cameraOffset;
                    transform.position = UnityEngine.Vector3.Slerp(transform.position, newPos, smoothFactor);

            if (Input.GetMouseButton(0))
                        {
                            UnityEngine.Quaternion camTurnAngle =
                                Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotSpeed, Vector3.up);
                            _cameraOffset = camTurnAngle * _cameraOffset;
                            transform.LookAt(PlayerTransform);
                        }


        }

The code should also limit how close and far away from the player can the camera move. Thank you for considering my question.

\$\endgroup\$
0
\$\begingroup\$

You can use Input.mouseScrollDelta to get which direction the mouse wheel is currently being scrolled and use that to offset the camerOffset Z value.

public Transform PlayerTransform;
private UnityEngine.Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
public float smoothFactor = 0.5f;
public float minZoomDistance = 0;
public float maxZoomDistance = 2f;
void Start()
{
    _cameraOffset = transform.position - PlayerTransform.position;
}
void Update()
{
    UnityEngine.Vector3 newPos = PlayerTransform.position + _cameraOffset;
    transform.position = UnityEngine.Vector3.Slerp(transform.position, newPos, smoothFactor);

    //offset the cameras forward Axis (Z) by whatever the current scroll wheel delta is, you can add a smoothing factor here to multiply by
    _cameraOffset.z += Input.mouseScrollDelta.y;

    //clamp the z value offset between min and max  
    _cameraOffset.z = Mathf.Clamp(_cameraOffset.z, minZoomDistance, maxZoomDistance);
    if (Input.GetMouseButton(0))
    {
        UnityEngine.Quaternion camTurnAngle =
            Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotSpeed, Vector3.up);
        _cameraOffset = camTurnAngle * _cameraOffset;
        transform.LookAt(PlayerTransform);
    }


}

This is untested code but it should work!

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.