放大或缩小相机

时间:2016-07-04 05:30:00

标签: c# unity3d

我有一个球,用相机在随机高度和距离聚焦。在鼠标滚动时,我想将我的相机放大到球。我试过这个奇怪的代码,它的表现与我预期的一样奇怪。

void ZoomInOut() { 
    if(Input.GetAxis("Mouse ScrollWheel") > 0){
        Debug.Log("mouse scroll wheel greater");
        distance += 20.0f;
        Vector3 negDistance = new Vector3(targetFollow.transform.position.x, targetFollow.transform.position.y, -distance);
        Vector3 pos = transform.rotation * negDistance + targetFollow.transform.position;
        transform.position = pos;
    }
    if(Input.GetAxis("Mouse ScrollWheel") < 0){
        Debug.Log("mouse scroll wheel less");
        distance -= 20.0f;
        Vector3 negDistance = new Vector3(targetFollow.transform.position.x, targetFollow.transform.position.y, -distance);
        Vector3 pos = transform.rotation * negDistance + targetFollow.transform.position;
        transform.position = pos;
    }
}

2 个答案:

答案 0 :(得分:0)

如果想直接向前/向后缩放,可以使用:ZoomWithMouse.cs

它只是沿着transform.forward轴移动相机。

using UnityEngine;

// Zoom forward and backward with mousewheel, Attach this script to camera
public class ZoomWithMouse : MonoBehaviour
{
    public float zoomSpeed = 300;
    void Update()
    {
        var mouseScroll = Input.GetAxis("Mouse ScrollWheel");

        if (mouseScroll!=0)
        {
            transform.Translate(transform.forward * mouseScroll * zoomSpeed * Time.deltaTime, Space.Self);
        }
    }
}

源: https://github.com/UnityCommunity/UnityLibrary/blob/master/Scripts/Camera/ZoomWithMouse.cs

答案 1 :(得分:-1)

using UnityEngine;
using System.Collections;

public class Zoom : MonoBehaviour
{
    private float _speed = 10;

private void Update()
{
    float mouseScroll = Input.GetAxis("Mouse ScrollWheel");

    if (mouseScroll!=0)
    {
        transform.Translate(Mathf.Sign(mouseScroll) * transform.forward * _speed * Time.deltaTime, Space.World);
    }
}
}