繁体   English   中英

Raycast无法在Update()Unity C#中工作

[英]Raycast not working in Update() Unity c#

我正在做一个物体跟随我的手指的游戏。 但是,如果我在屏幕上的任意位置点击,我都不希望该对象跳到手指上。 我正在使用raycast进行此操作。 除非我的手指移动得太快,否则物体会冻结,因此效果很好。

我的理论是,由于存在于Update() ,一旦我将手指从对象上移开,它就会检测到无法再拖动它。 我不知道该如何解决。

public GameObject Bigball;
public GameObject Smallball;

// Update is called once per frame
private void Update ()
{ 
    // lets ball follow finger
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(0).phase == TouchPhase.Stationary)
    {
        var touch = Input.GetTouch(0);
        Vector3 fingerPos = touch.position;
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(fingerPos);

        if (Physics.Raycast(ray, out hit) && (hit.collider.tag == "ball"))
        {
            Smallball.SetActive(false);
            Bigball.SetActive(true);
            Vector3 pos = new Vector3((Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position)).x,
               (Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position)).y, 0);
            Bigball.transform.position = pos;
        }
    }
    else
    {
        Bigball.SetActive(false);
        Smallball.SetActive(true);
        Smallball.transform.position = new Vector3(Bigball.transform.position.x, Bigball.transform.position.y, 0);
    }
}

当手指触摸屏幕时,仅Raycast一次可能更有意义。 如果该Raycast找到要拖动的对象,则只需存储该对象并在每次Update()时将其移动到跟随手指的位置即可,只要手指继续触摸屏幕即可。

松开手指后,只需忘记对象,直到下一次触摸找到要拖动的新对象。

一种替代方法是完全不使用Raycast,而要像Bijan已经提到的那样在IBeginDragHandler,IDragHandler和IEndDragHandler上构建。

暂无
暂无

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

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