2d unity,如何仅使用触摸/手指在x轴上拖动对象

时间:2018-01-14 23:28:20

标签: android unity3d touch

这里有人可以帮助我。我是新的团结。我正在努力使物体仅在x轴/ y轴上移动,当物体触摸并向左拖动物体向左移动并在触摸时移动或在物体上移除。

using UnityEngine;
using System.Collections;

public class MoveScriptVertical : MonoBehaviour 
{
    //touch offset allows ball not to shake when it start moving

    float deltax,deltay;
    Rigidbody2D rb;

    bool moveAllowed = false;

    void Start ()
    {
        rb = GetComponent<Rigidbody2D> ();
    }

    void Update ()
    {
        //touch event
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch (0);

            //knowing the touch position
            Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);

            //touch phase

            switch (touch.phase)
            {
            case TouchPhase.Began:
                //if you touch the car
                if (GetComponent<Collider2D> () == Physics2D.OverlapPoint (touchPos)) 
                {
                    //get the offset between position you touch
                    deltax = touchPos.x - transform.position.x;
                    deltay = touchPos.y - transform.position.y;

                    //if touch began within  the car collider
                    //then it is allowed to move

                    moveAllowed = true;

                    //restriction some rigidbody properties
                    rb.freezeRotation = true;
                    rb.velocity = new Vector2 (0, 0);
                    GetComponent<BoxCollider2D> ().sharedMaterial = null;
                }
                break;

            //you move your finger
            case TouchPhase.Moved:                   
                //if you touches the car and move is allowed
                if (GetComponent<Collider2D> () == Physics2D.OverlapPoint (touchPos) && moveAllowed)
                    rb.MovePosition (new Vector2 (0, touchPos.y - deltay));

                break;

            //you released your finger
            case TouchPhase.Ended:
                //restore intial parameters
                //when touch is ended
                moveAllowed = false;
                rb.freezeRotation = true;
                rb.gravityScale = 0;
                PhysicsMaterial2D mat = new PhysicsMaterial2D ();
                GetComponent<BoxCollider2D> ().sharedMaterial = mat;
                break;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有些库允许您拥有复杂的手指事件,例如Touchscript。如果您选择此解决方案,您将在线找到教程。

最基本的方法是在这里使用统一的输入类和一个很好的文档:https://docs.unity3d.com/ScriptReference/Input.html

这可让您知道手指触摸屏幕或在屏幕上移动的时间。它将为您提供x和y坐标,因此如果您只想沿x移动,则只使用x值,例如使用

翻译您的对象
transform.Translate(new Vector3(x, 0f, 0f));

修改

由于您使用touchscript,看看TransformGesture,它应该允许您处理许多转换事件。如果你想拥有更多控制权,你可以使用PressGesture,PanGesture和ReleaseGesture来代替