Unity 控制刚体的移动与旋转的方法

在场景创建一个Cube,并添加刚体,如图:

编写脚本:

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

[RequireComponent(typeof(Rigidbody))]
public class RibRotate : MonoBehaviour
{
    //private Vector3 mouseStartPosition;
    private Rigidbody rigidbody;
    //private bool isMouseDown;

    private float moveSpeed = 5f;
    private float rotationSpeed = 10f;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();        
    }

    // Update is called once per frame
    void Update()
    {
        float vertical = Input.GetAxis("Vertical");
        float horizontal = Input.GetAxis("Horizontal");

        

        if (Input.GetMouseButton(0))
        {    
            //鼠标左键控制左右旋转
            rigidbody.angularVelocity = -transform.up * horizontal * rotationSpeed;
        }
        else if(Input.GetMouseButton(1))
        {
            //鼠标右键控制上下移动
            rigidbody.velocity = -transform.forward * vertical * moveSpeed;
        }

        //if (Input.GetMouseButtonDown(0))
        //{
        //    mouseStartPosition = Input.mousePosition;
        //    isMouseDown = true;
        //}
        //if (Input.GetMouseButtonUp(0))
        //{
        //    isMouseDown = false;
        //}

        //if (isMouseDown)
        //{
        //    // 获取鼠标移动距离和方向,并计算旋转角度
        //    float mouseX = Input.GetAxis("Mouse X");
        //    float mouseY = Input.GetAxis("Mouse Y");
        //    Vector3 rotation = new Vector3(-mouseY, mouseX, 0) * rotationSpeed;

        //    // 应用旋转
        //    transform.Rotate(rotation);
        //}
    }
}

把脚本添加到Cube中,运行:

Unity鼠标控制刚体移动旋转(实际效果不好,纯粹用来玩玩)

如视频所示,效果真的不行,只能单纯上下或左右移动旋转刚体,同时用鼠标控制效果更差。所以使用上面方法纯粹就是玩玩。

相关推荐
切韵10 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
RPGMZ10 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
程序猿多布10 天前
Unity Addressable使用之检测更新流程
unity·addressable
Bunny Chen11 天前
Unity中的物理单位是真实的吗?
unity·游戏引擎
benben04411 天前
Unity3D仿星露谷物语开发69之动作声音
游戏·ui·unity·c#·游戏引擎
徐子竣11 天前
Unity Shader开发-着色器变体(1)-着色器变体概述
unity·游戏引擎·着色器
playmak3r12 天前
某手游cocos2dlua反编译
游戏引擎·lua·cocos2d
Magnum Lehar12 天前
wpf3d游戏引擎ProjectLayoutView实现
游戏引擎·wpf