Unity 2D使用拖动上下移动

时间:2015-04-05 20:19:01

标签: c# android unity3d touch 2d

我想改变我的Android游戏,它就像乒乓球。我希望能够在手机上拖动拨片。提前谢谢你的帮助。这是我最古老的代码:

  using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour {
        public float speed = 30;
        public string axis = "Vertical";

        void FixedUpdate () {
        float v = Input.GetAxisRaw (axis);
          GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;



    }
}

继承我的旧代码,但它仍无效。

   using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour {
    public float speed = 30;
    public string axis = "Vertical";
    public object racket = "Racket";
    public bool touchInput = true;
    public Vector2 touchPos;





    void FixedUpdate () {

        //used to not have anything in parentheses
        float v = Input.GetAxisRaw (axis);
        //GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;
        if (Input.touchCount == 1)
        {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);
            if (racket == Physics2D.OverlapPoint(touchPos));
            {
                GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;

            }
        }
    }
}

这是我现在正在修复的代码。

using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour {
    public float speed = 30;
    public string axis = "Vertical";
    public object racket = "Racket";
    public bool touchInput = true;
    public Vector2 touchPos;





    void FixedUpdate () {

        //used to not have anything in parentheses
        //float v = Input.GetAxisRaw (axis);
        float v = Input.GetAxisRaw (axis);
        GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;
        if (Input.touchCount == 1)
        {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);
            if (Racket.Collider2D == Physics2D.OverlapPoint(touchPos));
            {
                this.transform.position.y = wp.y

            }
        }
    }
}

答案:上述代码是固定的,应该可以使用。

1 个答案:

答案 0 :(得分:2)

你说要拖动,因此你需要触摸 首先,您需要检查触摸,如果用户正在触摸屏幕,然后使用raycast2d检查他是否正在触摸划水板并使用相同的逻辑将其保持在您用于鼠标的手指位置。

首先尝试自己,用它来提示 http://answers.unity3d.com/questions/577314/how-to-detect-if-a-sprite-was-object-was-touched-i.html

谢谢