Home > database >  Swipe using mobile touchscreen
Swipe using mobile touchscreen

Time:10-04

I am new to game development, i am trying to to change my code to mobile touch. I tried to change the flowing code to make workable for mobile touchscreen unfortunately failed. can you help me how can I make flowing code for mobile? Here is the code.

    Vector2 newPos;
    bool canMove = true;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        newPos = transform.position;
    }

private void Update()
    {
        if (canMove)
        {
            if (Input.GetKeyDown(KeyCode.RightArrow))
            {
                newPos.x  = 1.4f;
                transform.position = newPos;                
            }
            if (Input.GetKeyDown(KeyCode.LeftArrow))
            {
                newPos.x -= 1.4f;
                transform.position = newPos;
                    
            }
        }
        if (Input.GetKeyDown(KeyCode.Space) && canMove)
        {
            rb.AddForce(Vector3.down * speed);
            canMove = false;
        }
        Vector2 clampPos = transform.position;
        clampPos.x = Mathf.Clamp(transform.position.x, -2.1f, 2.1f);
        transform.position = clampPos;
    }

CodePudding user response:

Create a Canvas with a screen wide transparent Image component inside.

Use OnPointerDown and OnDrag event functions to catch finger movement on this image. Just make your class implement IPointerDownHandler and IDragHandler interfaces and use PointerEventData args properties to get delta or current position.

You can use the code below. Add it to the screen wide image and assign your Ridigbody2d and transform in inspector.

public class Movement: MonoBehaviour, IPointerDownHandler, IDragHandler
{
    public Rigidbody2d rb;

    public float maxSpeed = 10f;
    public float sensitivity = 0.1f;
    public float xBound = 2.1f;


    Vector3 initialFingerPosition;
    bool canMove = true;

    public void OnPointerDown(PointerEventData pointerEventData)
    {
        initialFingerPosition = pointerEventData.position;
    }

    public void OnDrag(PointerEventData data)
    {
        if(!canMove)
            return;

        var position = rb.position;
        position  = data.delta * sensitivity * speed * Time.deltaTime;
        position.x = Mathf.Clamp(position.x, -xBound, xBound);

        rb.MovePosition(position);
    }
}
  • Related