Unity 2D使用拖动上下移动

Unity 2D Using Drag To Move Up And Down

我想为 Android 改变我的游戏,就像乒乓球一样。我希望能够在 phone 上拖动桨。提前感谢您的帮助。这是我最早的代码:

  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

            }
        }
    }
}

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

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

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

谢谢