- Home /
Why is my Player moving only when I am pressing a key in the keyboard with the movement button?
So i am making a 2D game for android and Windows, At the moment I am developing movement for android using buttons but for some reason the movement of the player using buttons only works when I press both the button and the A key (Key for moving left) or D key (Key for moving right) or W key (Key for Jumping). I used the event trigger's onPointerUp and down and added the movement functions to it from the script placed in player. Here is the script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ButtonMovement : MonoBehaviour { public float moveSpeed = 2f; public float JumpForce = 4f; public float KASpeed = 4f; public bool isGrounded; public bool CanHoldJump; public float moveHorizontal; public float moveVertical; public float MaxTime; public float CurrentTime; Rigidbody2D rb;
public AudioSource JumpSFX;
public AudioSource HitSFX;
bool moveable;
public void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
MaxTime = 5f;
CurrentTime = MaxTime;
isGrounded = true;
CanHoldJump = true;
moveable = true;
}
public void Update()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
}
public void Jump()
{
if (CurrentTime >= 0)
{
rb.AddForce(new Vector2(0f, moveVertical * JumpForce), ForceMode2D.Impulse);
CurrentTime -= Time.deltaTime;
JumpSFX.Play();
}
}
public void StopMoving()
{
moveable = false;
rb.velocity = Vector2.zero;
}
void FixedUpdate()
{
if (moveable)
{
rb.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
}
}
}
Would mean a lot of someone answered :)
Your answer
Follow this Question
Related Questions
Magnet effect to draw coins,Magnetic effect to draw coins 5 Answers
scale based on position(help) 1 Answer
How to Make Character Shoot Where Aiming with Mouse 0 Answers
Can't convert from mouse screen position to world position 3 Answers
My balance in the game and my multiplier are not saving, i cant figure out why, any help? 0 Answers