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

    }
}
相关推荐
SmalBox14 小时前
【光照】Unity中的[经验模型]
unity·渲染
萘柰奈15 小时前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
Yasin Chen16 小时前
Unity UI坐标说明
ui·unity
应用市场17 小时前
无人机姿态控制系统详解与实现
游戏引擎·cocos2d
陈言必行21 小时前
Unity 性能优化 之 编辑器创建资源优化( 工作流 | 场景 | 预制体)
unity·编辑器·游戏引擎
1uther1 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
死也不注释1 天前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
程序猿多布1 天前
XLua教程之热补丁技术
unity·c#·lua·xlua
SmalBox2 天前
【光照】Unity中的[光照模型]概念辨析
unity·渲染
挂科是不可能出现的2 天前
unity导入blender动画
unity·游戏引擎·blender