Unity drags objects (rigid bodies) to move (restrictions on wall penetration) - actual maze combat

  • When dragging a rigid body, there will be a phenomenon of flying through the wall (the following is a 2D rigid body, the same is true for 3D rigid bodies). This is because the movement of the rigid body will also trigger the physical collision mechanism, and forcing the coordinates to change will cause problems. Unity It comes with a method MovePosition that allows rigid bodies to move in compliance with physical laws.
  • Add a 2D collision body and rigid body to the 2D object, and add a collision body to the object to be collided. Note that the Rigidbody2D-Collision Detection of the main object is set to Continuous (real-time monitoring of object collisions), which truly restores the collision scene. The new script is directly mounted to On the main object, put the code
using UnityEngine;

public class Move : MonoBehaviour
{
    
    
    Rigidbody2D rigidbody2d; // 存储2D物体的刚体组件的引用
    bool bar = false; // 控制拖拽状态的标志变量

    // 在游戏对象启动时调用的方法
    void Start()
    {
    
    
        // 获取自身的Rigidbody2D组件并存储在rigidbody2d变量中
        rigidbody2d = GetComponent<Rigidbody2D>();
    }

    // 当鼠标按下时调用
    public void OnMouseDown()
    {
    
    
        bar = true; // 设置拖拽状态为true,表示物体正在被拖拽
    }

    // 当鼠标释放时调用
    public void OnMouseUp()
    {
    
    
        bar = false; // 设置拖拽状态为false,表示物体停止拖拽
    }

    // 在鼠标拖拽时被调用
    public void OnMouseDrag()
    {
    
    
        if (bar) // 当拖拽状态为true时才执行拖拽操作
        {
    
    
            Vector3 mousePositionScreen = Input.mousePosition;

            // 提取屏幕坐标的X和Y分量,创建一个二维向量点
            Vector2 mousePosition2D = new Vector2(mousePositionScreen.x, mousePositionScreen.y);

            // 输出鼠标的二维向量点坐标
            Debug.Log("Mouse Position (Vector2): " + mousePosition2D);

            // 将刚体平滑移动到鼠标的二维向量点坐标
            rigidbody2d.MovePosition(Vector2.Lerp(rigidbody2d.position, mousePosition2D, Time.deltaTime * 100f));
        }
    }
}

  • The objects in the scene are implemented with the help of the Event Trigger component. The specific settings are as follows
    Insert image description here

Guess you like

Origin blog.csdn.net/Chj1319261607/article/details/132084132