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);

    }
}
相关推荐
EQ-雪梨蛋花汤25 分钟前
【Unity笔记】Unity 编辑器扩展:打造一个可切换 Config.assets 的顶部菜单插件
unity·编辑器·游戏引擎
SmalBox1 小时前
【URP】UnityHLSL顶点片元语义详解
unity·渲染
北岛三生3 小时前
ISP(图像信号处理器)
图像处理·数码相机·测试工具·计算机视觉·测试用例·模块测试
在路上看风景12 小时前
9. Mono项目与Unity的关系
unity
在路上看风景13 小时前
1.12 Memory Profiler Package - Summary
unity
兔子不吃草~15 小时前
鱼眼相机模型
数码相机
SmalBox18 小时前
【URP】Unity Shader Tags
unity·渲染
北岛三生21 小时前
Camera tuning flow相机调试流程
图像处理·数码相机·测试工具·模块测试
南山二毛21 小时前
机器人控制器开发(传感器层——奥比大白相机适配)
数码相机·机器人
格林威1 天前
棱镜的技术加持:线扫相机如何同时拍RGB和SWIR?
人工智能·深度学习·数码相机·yolo·计算机视觉