- Home /
Question by
kwfer377 · Dec 16, 2019 at 08:41 AM ·
raycastunity 2dplatformplatformercontroller
How to disable wall jumping in 2D platformer with raycast and tilemap?
Im working on a 2d platformer project.
I made a player controller script that uses a raycast to detect whether or not the player is on the ground.
However, when i am up against a wall but not on the ground, the game thinks that i am grounded and it allows me to jump
How do i fix this?
Also im using a tilemap for platforming
here's the code
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public float jumpHeight;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
private Sprite[] sprites;
// Use this for initialization
void Start()
{
sprites = Resources.LoadAll<Sprite>("fbla man sprites");
}
void fixedUpdate()
{
//grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
void OnCollisionStay2D(Collision2D collider)
{
CheckIfGrounded();
}
void OnCollisionExit2D(Collision2D collider)
{
grounded = false;
}
private void CheckIfGrounded()
{
RaycastHit2D[] hits;
//We raycast down 1 pixel from this position to check for a collider
Vector2 positionToCheck = transform.position;
hits = Physics2D.RaycastAll(positionToCheck, new Vector2(0, -1), 0.01f);
//if a collider was hit, we are grounded
if (hits.Length > 0)
{
grounded = true;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.D))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
GetComponent<SpriteRenderer>().sprite = sprites[2];
}
else { GetComponent<SpriteRenderer>().sprite = sprites[0]; }
if (Input.GetKey(KeyCode.A))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
GetComponent<SpriteRenderer>().sprite = sprites[2];
}
else { GetComponent<SpriteRenderer>().sprite = sprites[0]; }
if (Input.GetKeyDown(KeyCode.W) && grounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
GetComponent<SpriteRenderer>().sprite = sprites[1];
}
}
}
Comment