- Home /
How can I make my player unable to jump up walls?
Sorry I know this might be an easy fix but I've been at it for hours now. I'm making a 2D platformer and when adding some ground detection my player now detects everything in my tile set.
public class jump : MonoBehaviour { [Range(1, 10)] public float jumpVel; public bool Grounded; public BoxCollider2D box;
void Update()
{
if(Input.GetButtonDown("Jump") && Grounded){
GetComponent<Rigidbody2D>().velocity = Vector2.up * jumpVel;
}
}
void OnCollisionStay2D(Collision2D collider)
{
CheckIfGrounded();
}
void OnCollisionExit2D(Collision2D collider)
{
Grounded = false;
}
private void CheckIfGrounded()
{
float extra = 0.1f;
if(Physics2D.Raycast(box.bounds.center, Vector2.down, box.bounds.extents.y + extra)){
Grounded = true;
}
Color rayColor = Color.green;
Debug.DrawRay(box.bounds.center, Vector2.down * (box.bounds.extents.y + extra), rayColor);
}
} I'm under the impression that raycasting only detects in one direction but i'm extremely new to this. The Grounded bool works normally on the ground and in the air(true on the ground false in the air), however it's set to true when colliding with walls in the air. Any help would be greatly appreciated.
Answer by highpockets · Apr 01, 2021 at 06:22 AM
You are just raycasting against every collider with no filter. You should set a layer on your ground objects in the inspector. So now let’s say you have all your objects with the layer named “Ground” and say that layer is number 8:
int layerMask = 1 << 8;
if(Physics2D.Raycast(box.bounds.center, Vector2.down, box.bounds.extents.y + extra, layerMask))
{
//now you know that only the ground has been hit
isGrounded = true;
}
Obviously make sure that walls are not assigned the Ground layer
Answer by Wolfos · Apr 01, 2021 at 06:46 AM
In addition to what @highpockets mentioned, you can check the collider normal to find the angle it's at.
RaycastHit hit;
if(Physics2D.Raycast(box.bounds.center, Vector2.down, out hit, box.bounds.extents.y + extra))
{
var maxSlopeDegrees = 45f;
if(hit.normal.y > 1 - maxSlopeDegrees / 90)
{
isGrounded = true;
}
}