Unity Cómo arrastrar Rigidbody usando el cursor del mouse

Para arrastrar Rigidbodies ​​con el cursor del mouse, necesitamos crear un script que se adjuntará a una cámara y detectará si se hizo clic en algún Rigidbody; de ser así, inicializará el movimiento de arrastre.

Sharp Coder Reproductor de video

SC_DragRigidbody.cs

using UnityEngine;

public class SC_DragRigidbody : MonoBehaviour
{
    public float forceAmount = 500;

    Rigidbody selectedRigidbody;
    Camera targetCamera;
    Vector3 originalScreenTargetPosition;
    Vector3 originalRigidbodyPos;
    float selectionDistance;

    // Start is called before the first frame update
    void Start()
    {
        targetCamera = GetComponent<Camera>();
    }

    void Update()
    {
        if (!targetCamera)
            return;

        if (Input.GetMouseButtonDown(0))
        {
            //Check if we are hovering over Rigidbody, if so, select it
            selectedRigidbody = GetRigidbodyFromMouseClick();
        }
        if (Input.GetMouseButtonUp(0) && selectedRigidbody)
        {
            //Release selected Rigidbody if there any
            selectedRigidbody = null;
        }
    }

    void FixedUpdate()
    {
        if (selectedRigidbody)
        {
            Vector3 mousePositionOffset = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance)) - originalScreenTargetPosition;
            selectedRigidbody.velocity = (originalRigidbodyPos + mousePositionOffset - selectedRigidbody.transform.position) * forceAmount * Time.deltaTime;
        }
    }

    Rigidbody GetRigidbodyFromMouseClick()
    {
        RaycastHit hitInfo = new RaycastHit();
        Ray ray = targetCamera.ScreenPointToRay(Input.mousePosition);
        bool hit = Physics.Raycast(ray, out hitInfo);
        if (hit)
        {
            if (hitInfo.collider.gameObject.GetComponent<Rigidbody>())
            {
                selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
                originalScreenTargetPosition = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance));
                originalRigidbodyPos = hitInfo.collider.transform.position;
                return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
            }
        }

        return null;
    }
}

Configuración

  • Adjunte el script SC_DragRigidbody a cualquier cámara
  • Coloque los objetos que desea arrastrar frente a la cámara (asegúrese de que los objetos que desea arrastrar tengan un componente Rigidbody adjunto).

¡Ahora puedes arrastrar Rigidbodies con el cursor del mouse!

Artículos sugeridos
Trabajar con el componente Rigidbody de Unity
Cómo comprobar si un reproductor de cuerpo rígido está basado en Unity
Cómo detectar colisiones usando código en Unity
Creando una simulación de bandera en Unity
La física detrás del Raycasting en Unity
Creando un juego de carreras basado en la física en Unity
Implementación de un gancho de agarre 2D en Unity