B
B
Brian May2020-10-21 07:52:43
C++ / C#
Brian May, 2020-10-21 07:52:43

How to fix continuous motion when using controls via UI elements?

I'm making an Android game, I implemented the control through swipes, but when I swipe right / left, the player continuously moves right / left

public class Player : MonoBehaviour, IBeginDragHandler, IDragHandler
{
    public float speed; 
    public float jumpForce; 
    public float moveInput; 

    private Rigidbody2D rb;

    public bool facingRight = true; 

    public bool isGrounded;
    public Transform feetPos;
    public float checkRadius;
    public LayerMask whatIsGround;

    public GameObject ground;

    public void OnBeginDrag(PointerEventData eventData)
    {

        if ((Mathf.Abs(eventData.delta.x)) > (Mathf.Abs(eventData.delta.y)))
        {
            if (eventData.delta.x > 0)
            {
                moveInput = 2;
                rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
            }
            else
            {
                moveInput = -2;
                rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
            }
        }
        else
        {
            if (eventData.delta.y > 0 && isGrounded == true)
            {
                rb.velocity = Vector2.up * jumpForce;
            }
            else
            {
                
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question