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

相关推荐
刘欣的博客31 分钟前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
Yorlen_Zhang2 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝1912 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话2 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc11400756634 小时前
通信 28
c#
我的offer在哪里5 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
bugcome_com7 小时前
C# 程序结构详解:从 Hello World 开始
c#
淡海水8 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
唐梓航-求职中8 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
在路上看风景8 小时前
4.6 显存和缓存
unity