为什么游戏对象在拖动时,raycast不能准确地跟随unity中的触摸位置?

问题描述 投票:0回答:1

所以我做了一个多点触控的脚本,使用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];
            }
        }
    }
}

我可以做什么拖动更快,没有gameobject将发布? 对不起,我的英语不好

c# unity3d
1个回答
0
投票

一种解决方案是使用一个bool变量和标签。

你把你拖动的游戏对象保存在内存中,你把一个bool变量设置为true......就是这样,你试着用bool变量代替touchphase.endbegan。

这是你的想法,你试着用布尔变量代替触摸阶段.endbegan... 岗位 可以帮你

我刚刚适应了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
© www.soinside.com 2019 - 2024. All rights reserved.