Unity 通过键盘鼠标控制物体移动、旋转、缩放的方法

在Unity中,使用键盘ADWS键控制物体移动,通过鼠标左键控制物体旋转,鼠标中键控制物体缩放是再常见不过的方法。

方法如下:

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

public class MoveController : MonoBehaviour
{
    float moveSpeed = 10f;
    float rotateSpeed = 1000f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //获取横轴参数
        float Horizontal = Input.GetAxis("Horizontal");
        //获取垂直参数
        float Vertical = Input.GetAxis("Vertical");        

        //键盘ADWS键控制物体移动。
        //通过乘于Time.deltaTime,就可以让物体以每秒moveSpeed单位的速度向前移动
        transform.Translate(new Vector3(Horizontal * Time.deltaTime * moveSpeed, 0, Vertical * Time.deltaTime * moveSpeed)); 

        //左键鼠标点击状态下移动鼠标旋转
        if(Input.GetMouseButton(0))
        {
            //通过获取鼠标XY轴移动数值控制物体旋转
            transform.Rotate(new Vector3(Input.GetAxis("Mouse X") * Time.deltaTime * rotateSpeed, Input.GetAxis("Mouse Y") * Time.deltaTime * rotateSpeed));
        }

        //通过获取鼠标中键滑动值控制物体缩放
        transform.localScale += Vector3.one * Input.GetAxis("Mouse ScrollWheel");
    }
}

效果如下:Unity 通过键盘鼠标控制物体移动、旋转、缩放_哔哩哔哩_bilibili

相关推荐
晨星shine3 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526744 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang5 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf8 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools9 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的9 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21889 天前
.NET 本地Db数据库-技术方案选型
windows·c#