如何在单击时将 2d 刚体平滑地移动到鼠标

How to move 2d Rigidbody Smoothly to Mouse on Click

Vector2 mousePos = Input.mousePosition;
    // motion core
    if (GameObject.Find("Camera").GetComponent<room>().playerNum == 1)
    {
        if (Input.GetMouseButtonDown(0))
        {
            // move script not working
        }

    }

因此,我几乎找到了所有可能的解决方案,但其中 none 有效。我无法使用 AddForce 让它顺利移动,因为我想不出一个有效的算法来使力向 MousePosition 移动。

我有一个脚本可以对破坏球的手柄进行同样的动作,但我现在没有代码。我不记得它是如何工作的,但我认为这个想法是当鼠标被点击时,阻力将被设置为一个非常大的数字,重力将被设置为 0。然后一个非常强大的力量将被添加到反击拖动,使对象不绕轨道飞行而飞向鼠标。释放鼠标后,阻力和重力将恢复正常。

我目前无法对此进行测试,因为我使用的是 chromebook,而我的装有 Unity 的 PC 在另一栋楼里,但如果我没有出错,这段代码应该可以解决问题。

使用 UnityEngine;

public class ExampleClass : MonoBehaviour
{
    float prevDrag, prevGrav;    

    bool mousedown;
    Plane plane;
    Rigidbody2D r;
    
    void Start()
    {
        r = GetComponent<Rigidbody2D>(); // assuming this script is attached to the object being moved.
        plane = new Plane(Vector3.up, Vector3.zero);
    }

    void Update()
    {
        if(mousedown)
        {
            float enter;
            if (plane.Raycast(ray, out enter))
            {
                var hitPoint = ray.GetPoint(enter);               
                var mouseDir = hitPoint - gameObject.transform.position;   
                rb.AddForce(mouseDir * 9999999);
            }
        }
    }
    
    void OnMouseDown()
    {
        mousedown = true;
        prevDrag = r.drag;
        prevGrav = r.gravity;
        r.drag = 99999;
        r.gravity = 0;
    }

    void OnMouseUp()
    {
        mousedown = false;
        r.drag = prevDrag;
        r.gravity = prevGrav;
    }
}

您离开 Input.mousePosition 的位置是屏幕上的坐标,而不是世界上的位置。要在两者之间进行转换,可以使用Camera.ScreenToWorldPoint().

if (Input.GetMouseButtonDown(0))
    {
        Vector3 mousePos = Input.mousePosition
        mousePos = new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane)
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3())

        // move script
    }

您可能需要将 mousePos 中的 z 坐标编辑为您尝试移动的对象的当前 transform.position.z,或此处最有意义的其他值。它充当一种墙,它会在鼠标位置上创建距离相机恰好那么远的点。这应该比光线投射便宜很多,并且如果没有任何东西可以击中您点击的地方,它仍然有效。