Player won't move on UI button click

Hello, I’ve made a small game where I can move a player horizontally using a joystick and I would like to make him jump on a UI button click. The issue I have is that the player won’t move even tho the button works.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    public Joystick joystick;
    public float speed = 15f;
    public float jumpHeight = 50f;
    float moveX = 0;
   

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

    void Update()
    {
        if (joystick.Horizontal >= 0.2f)
        {
            moveX = speed;
            rb.velocity = new Vector2 (moveX, 0);
        }

        else if (joystick.Horizontal <= -0.2f)
        {
            moveX = -speed;
            rb.velocity = new Vector2 (moveX, 0);
        }

        else
        {
            moveX = 0;
            rb.velocity = new Vector2 (moveX, 0);
        }
    }

    public void Jump()
    {
        rb.velocity = new Vector2 (moveX, jumpHeight);
    }

        public void StopJump()
    {
        rb.velocity = new Vector2 (moveX, 0);
    }
   
}

This is my code. Everything works fine except for the last two functions. I have them both on an event trigger on the button.

Any help would be appreciated :).

8751753--1185807--b1.png

Haven’t tested any of your code, but the issue looks pretty obvious to me. You are setting the Rigidbody2D’s Y velocity to 0 every frame in your Update() method, so the 50f that you set it to for a single frame gets overwritten immediately.

There may be other issues, but I would start by fixing that. Instead of setting Y velocity to 0 in your movement code, set it to rb.velocity.y; I think that should work, don’t have Unity open to test.

Also, I’m pretty sure you’ll be calling the StopJump() method a few frames after the Jump() method, and that won’t work either. You don’t need the StopJump() method at all, if you set the Y velocity to 50f for a frame, it will naturally fall into the negative and cause the character to land back on the ground due to gravity.

1 Like

That does look pretty obvious now that you’ve said it lol. Thanks a lot. It works now :).

1 Like