【问题标题】:Unity game Drag Object with finger movementUnity 游戏用手指移动拖动对象
【发布时间】:2016-08-13 03:05:38
【问题描述】:

我是 Unity 新手并开发移动 2d 游戏,现在我可以在屏幕中心之前或之后触摸屏幕时使对象左右移动。但是我想在手指仍然触摸屏幕并移动时触摸对象并将其拖动到 x 轴上,所以我希望对象位于我手指的相同 x 位置, 任何人都可以帮助我如何正确地做到这一点: 如果我在屏幕中心之前或之后触摸,这是我如何移动对象的代码:

public class paddle : MonoBehaviour {

    public Rigidbody2D rb;
    public float speed;
    public float maxX;
    bool currentisAndroid=false;
    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody2D> ();
        #if UNITY_ANDROID
        currentisAndroid=true;
        #else
        currentisAndroid=false;
        #endif
    }

    // Update is called once per frame
    void Update () {
        if (currentisAndroid == true) {
            if (Input.GetTouch (0).position.x < Screen.width/2 && Input.GetTouch (0).phase == TouchPhase.Stationary)
                moveLeft ();
            else if (Input.GetTouch (0).position.x > Screen.width/2 && Input.GetTouch (0).phase == TouchPhase.Stationary)
                moveRight ();
            else
                stop ();

        } else {
            float x = Input.GetAxis ("Horizontal");
            //if (Input.GetTouch (0).position.x == rb.position.x && Input.GetTouch (0).phase == TouchPhase.Moved)
            if (x == 0)
                stop ();
            if (x < 0)
                moveLeft ();
            if (x > 0)
                moveRight ();

            Vector2 pos = transform.position;
            pos.x=Mathf.Clamp (pos.x,-maxX,maxX);
            transform.position = pos;
        }


    }
    void moveLeft()
    {
        rb.velocity = new Vector2 (-speed, 0);
    }
    void moveRight()
    {
        rb.velocity = new Vector2 (speed, 0);
    }
    void stop()
    {
        rb.velocity = new Vector2 (0, 0);
    }
    public float getposition()
    {
        return rb.position.y;
    }
}

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    最简单的方法:

    添加组件 DragRigidbody 脚本,您将能够通过鼠标或触摸屏触摸拖动对象。

    【讨论】:

      【解决方案2】:

      如果我理解正确:
      1 - 使用相机从手指位置垂直投射到场景中。
      2 - 选择命中的对象。
      3 - 将您的相机映射到世界坐标,并根据您的射线的命中点使用地图或游戏对象\对象移动该对象。

      • Physics.Raycast();
      • RaycastHit.collider();
      • Camera.main.ScreenToWorldPoint(Input.GetTouch().position);

      如果你想在地图上移动对象,你可以跟踪你的触摸,当它靠近角落时,直接移动相机(水平 - 垂直)。

      【讨论】:

        猜你喜欢
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多