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

相关推荐
唐青枫9 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech17 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf2 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6252 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072553 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486664 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆4 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同4 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落4 天前
C# FileStream文件流读取文件
开发语言·c#