我是新來的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;
}
}