Help a novice with wall jumping
I want to get back into using unity and I've been trying to add wall jumping into an old school project and I am at a loss with how to do it as I seem to have forgotten what little I have learned. I have found some solutions but don't know how to implement it into my own code without breaking everything. Here is the code for the the unit i want to be able to have wall jump. Any help is greatly appreciated.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour {
Rigidbody2D rb;
public float speed = 30;
public bool jump = false;
public bool grounded = true;
public Transform groundCheck;
public LayerMask mask;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//is our player grounded?
RaycastHit2D rh = Physics2D.Linecast(transform.position, groundCheck.position, mask);
//RaycastHit2D rh = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (rh.collider != null)
{
grounded = true;
}
else
{
grounded = false;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
jump = true;
}
}
private void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
rb.AddForce(h * Vector2.right * speed);
if (jump && grounded)
{
rb.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
jump = false;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
SceneManager.LoadScene("SampleScene");
}
}
Answer by BillehBawb · Dec 23, 2019 at 11:30 PM
There are a lot of different ways to do this, but the simplest would probably be to use collisions. Make sure your wall and your player have colliders (like a BoxCollider2D) and Rigidbody2Ds. Then you can make a "Wall" tag, give it to any walls you want to be wall-jumpable, and do something like this in your player script.
private void OnCollisionEnter2D(Collision2D collision)
{
// Check if the object the player is against is a wall, if they are off the ground and if up is being pressed
if (collision.collider.tag.Equals("Wall") && !grounded && jump)
{
// Add velocity to the player to push them off the wall. Put in your own values for xforce and yforce
rb.AddForce(new Vector2(xforce, yforce));
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612220550im_/https://answers.unity.com/themes/thub/images/avi.jpg)