繁体   English   中英

为什么拖动时gameobject / raycast没有准确地跟随触摸position统一

[英]why gameobject / raycast when dragged is not accurately following the touch position in unity

所以我使用 raycast 制作了一个多点触控脚本。 当拖得更快时,游戏对象将被释放,但当缓慢移动游戏对象时,它会跟随触摸。 这里的代码

Vector2[] startPos = new Vector2[5];
Touch[] touch = new Touch[5];// Update is called once per frame
void FixedUpdate()
{

    Debug.Log(Input.touchCount);
    if (Input.touchCount > 0)
    {
        touch[Input.touchCount-1] = Input.GetTouch(Input.touchCount-1);
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(touch[Input.touchCount-1].position);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero, Mathf.Infinity);

        if (hit.transform != null)
        {
            if (touch[Input.touchCount - 1].phase == TouchPhase.Moved)
            {
                hit.transform.position = worldPoint;]
            }

            else if (touch[Input.touchCount-1].phase == TouchPhase.Began)
            {
                startPos[touch[Input.touchCount-1].fingerId] = worldPoint;
            }

            else if (touch[Input.touchCount-1].phase == TouchPhase.Ended)
            {
                hit.transform.position = startPos[touch[Input.touchCount-1].fingerId];
            }
        }
    }
}

如果没有释放游戏对象,我该怎么做才能更快地拖动? 对不起,我的英语不好

一种解决方案是使用布尔变量和标签,

您将要拖动的游戏对象保留在 memory 中,将 bool 变量设置为 true .. 这就是想法,您尝试使用 bool 变量而不是 touchphase.ended/began ...

这篇文章可以帮助你

我刚刚适应了game2D

 GameObject objet = null;
 Plane plane;
 float rayDistance;
 Vector3 Offset;
 bool mouseOver = false;
 bool mousePressed = false;

void FixedUpdate()
{

    if (Input.touchCount > 0)
    {
        mousePressed = true;
    }
    else
    {
        mousePressed = false;
        objet = null;
    }

    Vector2 worldPoint = Camera.main.ScreenToWorldPoint(touch[Input.touchCount - 1].position);
    RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero, Mathf.Infinity);

    if (hit.transform != null && hit.collider.tag == "Draggable")
    {
        mouseOver = true;
        if (Input.GetTouch(0).phase != TouchPhase.Moved)
            objet = hit.collider.gameObject;
    }
    else
    {
        if (mousePressed == false)
            mouseOver = false;
    }

    if (mouseOver)
    {
        if (mousePressed)
        {
            //to adapt following your game configuration
            plane = new Plane(Camera.main.transform.forward * -1, objet.transform.position);
            plane.Raycast(ray, out rayDistance);
            objet.transform.position = ray.GetPoint(rayDistance);// + Offset; to see if offset is needed
        }
    }

} // end update

暂无
暂无

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

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