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 小时前
Niagara粒子系统-超炫酷的闪电特效(第二期 旋转的纸片)
游戏·游戏引擎·虚幻
WarPigs16 小时前
Unity渲染问题记录
unity·游戏引擎
不绝19116 小时前
导入3D模型时相关参数设置/Model标签页/Rig标签页/Avatar相关参数/Animation标签页/Materia标签页
unity·游戏程序
dlpay19 小时前
使用blender搭建模型并导入godot游戏引擎
游戏引擎·godot·blender
不是AI19 小时前
【Unity开发】一、在安卓设备上运行Unity项目
android·unity·游戏引擎
淡海水1 天前
【节点】[EyeSurfaceTypeDebug节点]原理解析与实际应用
unity·游戏引擎·debug·shadergraph·图形·surface·eye
淡海水2 天前
【节点】[IrisLimbalRing节点]原理解析与实际应用
unity·游戏引擎·iris·shadergraph·图形·ring·limbal
在路上看风景2 天前
33. RenderTarget
unity
在路上看风景2 天前
34. GPU偏爱2的幂次
unity
Zik----2 天前
Unity的基础使用
unity·游戏引擎