【问题标题】:Unity2D move transform on touchUnity2D 触摸移动变换
【发布时间】:2015-08-17 09:56:31
【问题描述】:

我想在用户移动鼠标(在 PC 上)或手指(在移动设备上)时移动我的主播放器

我做了一个简单的插图。如果我将手指向左移动 10 个单位,我希望玩家也向左移动 10 个单位。对于移动设备和 PC,我如何才能做到这一点?

【问题讨论】:

    标签: unity3d touch transform


    【解决方案1】:
    Vector3 screenPoint;
    Vector3 offset;
    
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }
    
    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
    

    将此代码添加到播放器的脚本中。

    编辑:此代码非常简单,可以将其转换为“通过点击从各个位置移动”。唯一的问题是 OnMouse* 函数仅在您单击脚本化和碰撞对象时才起作用。只需使用 Input.GetMouseButton 更改它即可解决。

    bool flag = false;
    
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (!flag)
            {
                flag = true;
                screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
                offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
            }
    
            Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
            transform.position = curPosition;
        }
        else
        {
            flag = false;
        }
    }
    

    【讨论】:

    • 这个答案的问题是它只有在我点击我设置脚本的对象时才会起作用。如果我单击屏幕上的其他任何位置,它将不起作用。
    • 您可以使用 Input.GetMouseButton(0) 代替 OnMouse* 函数。我编辑了我的答案,你可以看看它
    【解决方案2】:

    您需要两个函数:DragStart(),在每次鼠标按下时调用,Drag(),在鼠标按下时每帧调用。

    DragStart() 方法中,您希望首先将鼠标位置捕获到名为“Vector2 mouseDown”的变量中,并将另一个对象位置捕获到名为Vector2 objectStart 的变量中。

    Drag() 函数中,您创建了一个名为Vector2 offset 的变量,基本上您只需执行offset = mouseDown - Input.mousePosition; 即可获得您的偏移量,现在您所要做的就是将另一个对象移动与您的偏移量相同的量:@ 987654328@.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多