Unity's method of controlling the movement and rotation of rigid bodies

Create a Cube in the scene and add a rigid body, as shown in the figure:

Script:

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);
        //}
    }
}

Add the script to Cube and run:

Unity mouse controls rigid body movement and rotation (the actual effect is not good, purely for fun)

As shown in the video, the effect is really not good. You can only move the rotating rigid body up and down or left and right, and the effect of controlling it with the mouse is even worse. So using the above method is purely for fun.​ 

Guess you like

Origin blog.csdn.net/mr_five55/article/details/135006048
Recommended