简体   繁体   English

当仅在x和z轴上拖放3d对象时,如何使其完全跟随鼠标?

[英]When drag and dropping a 3d object on only the x and z axis, how do you let it follow the mouse exactly?

I want to drag and drop an object on only the x and z axis. 我只想在x和z轴上拖放对象。 So far the code does do that, only the object moves slower than the mouse. 到目前为止,代码确实做到了这一点,只有对象的移动速度比鼠标慢。 How do I make it follow the mouse exactly? 如何使其完全跟随鼠标?

As I'm still new to coding, I've tried implementing different codes into my code and tried to edit it from what I've learned, but I can't figure it out. 由于我还不熟悉编码,因此我尝试将不同的代码实现到我的代码中,并尝试根据所学知识对其进行编辑,但我无法弄清楚。

    Vector3 dist;
    Vector3 startPos;
    float posX;
    float posZ;
    float posY;
    void OnMouseDown()
    {
        startPos = transform.position;
        dist = Camera.main.WorldToScreenPoint(transform.position);
        posX = Input.mousePosition.x - dist.x;
        posY = Input.mousePosition.y - dist.y;
        posZ = Input.mousePosition.z - dist.z;
    }

    void OnMouseDrag()
    {
        float disX = Input.mousePosition.x - posX;
        float disY = Input.mousePosition.y - posY;
        float disZ = Input.mousePosition.z - posZ;
        Vector3 lastPos = Camera.main.ScreenToWorldPoint(new Vector3(disX, disY, disZ));
        transform.position = new Vector3(lastPos.x, 4.8f, lastPos.z);
    }

I expect that the object follows the mouse, but it moves in the same direction as the mouse, only slower. 我希望该对象跟随鼠标,但是它的移动方向与鼠标相同,只是速度较慢。

I would get a starting position in world space by raycasting from the pointer to a plane at the surface level. 通过从指针到表面平面的光线投射,我将在世界空间中获得一个起始位置。 Then on drag, do the same raycast. 然后拖动,进行相同的光线投射。 Find the difference from the first raycast to the current raycast and add that to the starting position of the object to get the new position of the object: 找到从第一个光线投射到当前光线投射的差异,并将其添加到对象的起始位置以获取对象的新位置:

Vector3 dist;
Vector3 startPos;
Vector3 startIntersect;

bool clickedOnGround = false;

void OnMouseDown()
{
    clickedOnGround = false;
    startPos = transform.position;

    Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.down, new Vector3(0f, 4.8f, 0f)); 

    float planeHitDist;
    if (groundPlane.Raycast(cameraRay, out planeHitDist))  
    {
        clickedOnGround = true;

        startIntersect = cameraRay.GetPoint(planeHitDist);
    }
}

void OnMouseDrag()
{
    Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.down, new Vector3(0f, 4.8f, 0f)); 

    float planeHitDist;
    if (groundPlane.Raycast(cameraRay, out planeHitDist))  
    {
        Vector3 newIntersect = cameraRay.GetPoint(planeHitDist);
        transform.position = startPos + (newIntersect - startIntersect);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM