首页 文章

Unity游戏用手指移动拖动对象

提问于
浏览
0

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

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;
    }
}

2 回答

  • 0

    最简单的方法:

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

  • 0

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

    • Physics.Raycast();

    • RaycastHit.collider();

    • Camera.main.ScreenToWorldPoint(Input.GetTouch(<0或1或all>) . position);

    如果你想在 Map 上移动物体,你可以跟踪你的触摸,当它靠近角落时,可以直接移动相机(水平 - 垂直) .

相关问题