Unity使用脚本控制相机移动、旋转

考虑到以后可能经常需要用到这个功能,所以写篇博客记录下代码。我的代码参考自博客:https://www.cnblogs.com/forever3329/p/17798070.html

功能:键盘wasd控制前后左右平移,qe控制左右视角旋转,rf控制视角升降。


csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Initialize_fruit : MonoBehaviour
{
    // Start is called before the first frame update
    //相机移动
    public int panSpeed;
    public float rotationAmount;
    public Vector3 zoomAmount;
    public int moveTime;
    private GameObject mainCamera;

    void Start()
    {
        //相机移动
        panSpeed = 1;
        rotationAmount = 0.1f;
        mainCamera = GameObject.Find("Main Camera");
    }

    // Update is called once per frame
    void Update()
    {
        CameraMove(mainCamera);
    }

    void CameraMove(GameObject camera)
    {//wasd控制前后左右平移,qe控制左右视角旋转,rf控制视角升降。
        var newPos = new Vector3(0, 0, 0);
        Vector3 newRotation = new Vector3(0, 0, 0);
        if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
        {
            Debug.Log("W or up");
            newPos = camera.transform.forward * panSpeed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
        {
            Debug.Log("S or down");
            newPos = -camera.transform.forward * panSpeed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
        {
            Debug.Log("D or right");
            newPos = camera.transform.right * panSpeed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
        {
            Debug.Log("A or left");
            newPos = -camera.transform.right * panSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.Q))
        {
            Debug.Log("Q");
            newRotation = Vector3.up * rotationAmount;
        }

        if (Input.GetKey(KeyCode.E))
        {
            Debug.Log("E");
            newRotation = Vector3.down * rotationAmount;
        }
        if (Input.GetKey(KeyCode.R))
        {
            Debug.Log("R");
            newPos = Vector3.up * panSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.F))
        {
            Debug.Log("F");
            newPos = Vector3.down * panSpeed * Time.deltaTime;
        }
        camera.transform.position += newPos;
        camera.transform.rotation = camera.transform.rotation * Quaternion.Euler(newRotation);

    }
}
相关推荐
zyh______12 小时前
unity值属性修改步骤
unity·游戏引擎
小贺儿开发14 小时前
Unity3D 四星探秘:手势互动演示
科技·unity·人机交互·科普·硬件·leap motion·互动
风酥糖14 小时前
Godot游戏练习01-第11节-显示优化,游戏背景,Shader
游戏·游戏引擎·godot
码界奇点17 小时前
基于模块化架构的Unity游戏开发框架设计与实现
java·c++·unity·架构·毕业设计·源代码管理
风酥糖19 小时前
Godot游戏练习01-第13节-粒子系统,武器攻击特效
游戏·游戏引擎·godot
小驰行动派20 小时前
Camera实战案例分析-三方相机,扫一扫预览卡顿
数码相机
张老师带你学21 小时前
unity船资源,快艇,帆船,游轮
科技·游戏·unity·游戏引擎·模型
C蔡博士1 天前
Unity游戏物体渲染顺序
unity·游戏引擎·游戏开发
废嘉在线抓狂.1 天前
Cinemachine 多大脑与多震源管理详解
数码相机
瑞瑞小安1 天前
Unity功能篇:PCVR开发(设备:HTC Vive Pro)更新中。。。
unity·游戏引擎