- Home /
How to add a functioning walljump?
Hello, I'm a young game developer making a game for a school project. I'm having some trouble adding a walljump, does anyone know how I can add a walljump that moves the player away from the wall, upwards, and prevents them from moving for a short moment? This is the script I have:
[SerializeField] private float speed;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private LayerMask wallLayer;
private Rigidbody2D body;
private Animator anim;
private BoxCollider2D boxCollider;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
boxCollider = GetComponent<BoxCollider2D>();
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
if (horizontalInput > 0.01f)
transform.localScale = Vector3.one;
else if (horizontalInput < -0.01f)
transform.localScale = new Vector3(-1, 1, 1);
if (Input.GetKey(KeyCode.Space) && isGrounded())
Jump();
if (Input.GetKey(KeyCode.Space) && onWall())
wallJump();
anim.SetBool("Running", horizontalInput != 0);
anim.SetBool("grounded", isGrounded());
}
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, speed + 5);
anim.SetTrigger("Jump");
}
private void wallJump()
{
body.velocity = new Vector2(body.velocity.x, speed + 5);
anim.SetTrigger("Jump");
}
private void OnCollisionEnter2D(Collision2D collision)
{
}
private bool isGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
return raycastHit.collider != null;
}
private bool onWall()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, new Vector2(transform.localScale.x, 0), 0.1f, wallLayer);
return raycastHit.collider != null;
}
Comment