Reputation: 11
I'm sitting for hours at the same problem. I'm doing a WebGL game, which should be possible to play with mobile control (touch) or with keyboard when playing on PC. At the beginning of the game, Player is asked if he plays with keyboard or mobile, which then changes the UI to a Joystick and Buttons, when he plays mobile.
In Unity Animator, the Players Animations for Movement do have bools, which control the animations, so f.e. when anim.SetBool("Jump", true) the Jump Animation starts. When false and Player has no Movement, Idle Animation plays, or when false and Movement, Walking Animation plays.
This all works fine when I press 'Space'. When I press Space Jump() is invoked.
The Players movement is fine when playing with keyboard, but I struggle hard to get a jumping button working. The character is jumping, but for any reasons the animation does only work when the Input is from the Keyboard. Also both, the Button and the Keyboard just invoke the same function, please have a look:
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour
{
//...
public bool isMobile;
public Joystick joystick;
GameObject rend;
public Button buttonJump;
void Start()
{
// HERE Jump() IS INVOKED, WHEN THE JUMP BUTTON IS PRESSED!
buttonJump.onClick.AddListener(Jump);
}
void Update()
{
PlayerJump();
CheckIsGrounded();
}
private void FixedUpdate()
{
PlayerWalk();
}
void PlayerJump()
{
if (isGrounded)
{
if ( Input.GetKey(KeyCode.Space))
{
Jump();
}
}
}
//WHEN INVOKED VIA JUMP BUTTON, THE PLAYER MOVES UP FINE, BUT THE JUMP ANIMATION DOES NOT START!
public void Jump()
{
if (isGrounded)
{
anim.SetBool("Jump", true);
jumped = true;
myBody.velocity = new Vector2(myBody.velocity.x, jumpPower);
}
}
void CheckIsGrounded()
{
isGrounded = Physics2D.Raycast(groundCheckPosition.position, Vector2.down, 0.1f, groundLayer);
if (isGrounded)
{
if (jumped)
{
anim.SetBool("Jump", false);
jumped = false;
}
}
}
}
Upvotes: 0
Views: 698
Reputation: 11
I got a workarround, I think there is something like a bug in Unity itself (using 2019.3.8f1). I simply created a own Script, only for the one Jump Button, when it is pressed, sets the bool for the Animator and adds the velocity to the rigidbody, exactly the same, as I wrote in the old code, but in the new script it works.
Upvotes: 0