- Home /
How to make Player jump (like in a 2D fighting game)
I'm trying to make a 2D fighting game prototype, but im struggling with making the character jump while it has horizontal velocity. Everytime I keep pressing the jump button, it just makes him jump directly upwards or neutral jump. I believe it is because of the if statements, being grounded/recovered. Im not too sure what I can do to make the jump work as intended. Here is my code:
public class FighterControl : MonoBehaviour
{
Rigidbody2D rb;
float moveX;
float jumpY;
[SerializeField] float jumpX = 2.5f;
[SerializeField] float moveSpeed = 2f;
[SerializeField] float jumpForce;
[SerializeField] bool recovered = true;
[SerializeField] bool isGrounded;
[SerializeField] Transform enemy;
bool hasX;
// Start is called before the first frame update
void Awake()
{
rb = GetComponent<Rigidbody2D>();
recovered = true;
}
// Update is called once per frame
void Update()
{
moveX = Input.GetAxisRaw("Horizontal");
jumpY = Input.GetAxisRaw("Vertical");
//Positions and States
FaceTowardsOpponent();
isGrounded = IsGrounded();
}
private void FixedUpdate()
{
Walk();
Jump();
}
private void FaceTowardsOpponent()
{
if (!recovered) { return; }
else
{
transform.localScale = new Vector2(EnemyPosition(), 1f);
}
}
void Walk()
{
if (!recovered || !IsGrounded()) { return; }
else if (recovered && IsGrounded())
{
hasX = Mathf.Abs(moveX) > Mathf.Epsilon;
Animator myAnim = GetComponent<Animator>();
myAnim.SetBool("Walking", hasX);
if (Mathf.Abs(moveX) > Mathf.Epsilon)
{
rb.velocity = new Vector2(moveX * moveSpeed, rb.velocity.y);
}
}
}
void Jump()
{
Animator myAnim = GetComponent<Animator>();
myAnim.SetBool("Grounded", IsGrounded());
if(!IsGrounded()) { return;}
if (Mathf.Abs(jumpY) > Mathf.Epsilon)
{
rb.velocity = new Vector2(moveX * jumpX, jumpForce);
}
}
private int EnemyPosition()
{
int enemyPos = (enemy.transform.position.x > transform.position.x) ?
1 : -1;
return enemyPos;
}
public bool IsGrounded()
{
bool grounded = GetComponent<BoxCollider2D>().
IsTouchingLayers(LayerMask.GetMask("Ground"));
return grounded;
}
}
Answer by luknight · Feb 11, 2020 at 06:13 PM
To me the issue would reside in your code somehow rewriting over your x velocity.
In this part of your script
if (Mathf.Abs(jumpY) > Mathf.Epsilon)
{
rb.velocity = new Vector2(moveX * jumpX, jumpForce);
}
Try to not use rb.velocity. Instead try to use rb.AddForce()
I'll do something like rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse)
If you want more explanation on how it works you can ask me for more details ( if it indeed does work )
Answer by the_spyor_ · Feb 11, 2020 at 06:16 PM
@oraradaniel //How I would do it is the code below
if (Input.GetKeyDown(KeyCode.Space))
//That's all I really know, I hope that kind of cleared it up, I make 3D games mainly, so I don't know how 2D would work
Your answer