Unity学习记录-摄像机的移动

摄像机的移动跟物体的移动是一样的:

  • 使用Input.GetAxis获取坐标轴方向
  • 使用transform.Translate平移
  • 通过改变Translate参数控制平移速度和方向

代码示例:

public float fCameraSpe = 10;
public float fMouseSpe = 200;
void Update () {
        //获取坐标
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        float mouse = Input.GetAxis("Mouse ScrollWheel");
        transform.Translate(new Vector3(h* fCameraSpe, 0 ,v* fCameraSpe) * Time.deltaTime,Space.World);
        transform.Translate(new Vector3(0, 0, mouse * fMouseSpe) * Time.deltaTime);
    }

4-13更新.使用鼠标中间拖动移动摄像机

   if(Input.GetMouseButton(2))
        {
            float fX = Input.GetAxis("Mouse X");
            float fY = Input.GetAxis("Mouse Y");
            transform.Translate(new Vector3(fX, 0, fY) * Time.deltaTime * fMouseSpe, Space.World);
        }

摄像机平滑移动

    const float MAX_CAMERA_SPEED = 25;
    const float MIN_CAMERA_SPEED = 3;
    const float MAX_DecayFrame = 480;
    public float fMouse2Spe = 0;
    public float fMouse2Decay = 0;
    private float fMouse2DecayStart = 0;
    float fX = 0;
    float fY = 0;
  void Update () {     
        //按下中键移动摄像机
             if(Input.GetMouseButton(0))
        {
            fX = Input.GetAxis("Mouse X");
            fY = Input.GetAxis("Mouse Y");
            fMouse2Spe = (fX*fX/ + fY*fY)/2 + MIN_CAMERA_SPEED ;
            if (fMouse2Spe > MAX_CAMERA_SPEED) fMouse2Spe = MAX_CAMERA_SPEED;
            fMouse2Decay = MAX_DecayFrame * (fMouse2Spe / MAX_CAMERA_SPEED);
            fMouse2DecayStart = fMouse2Decay;
            transform.Translate(new Vector3(-fX, 0, -fY) * Time.deltaTime * MIN_CAMERA_SPEED, Space.World);
        }
        else
        {
            if (fMouse2Decay > 0)
            {
                fMouse2Spe *= (fMouse2Decay / fMouse2DecayStart);
                fMouse2Decay--;
            }
            else { fMouse2Spe = 0; fMouse2Decay = 0; }
            transform.Translate(new Vector3(-fX, 0, -fY) * Time.deltaTime * fMouse2Spe, Space.World);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值