I’m trying to implement a box cast system for the jumping mechanic but jumping isn’t working, implying that the box cast isn’t giving information when in contact with the ground for some reason, how do I fix this?
Here is my code so far:
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody2D body;
private Animator anim;
private int Right;
private BoxCollider2D boxCollider;
[SerializeField] private LayerMask groundLayer;
//from GunMove
public GameObject Player;
private bool facingRight = true;
private void Awake()
{
boxCollider = GetComponent();
body = GetComponent();
anim = GetComponent();
Right = -1;
}
private void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//this code changes the velocity
float horizontalInput = Input.GetAxis(“Horizontal”);
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
//changes direction based on mouse
if (mousePos.x < transform.position.x && facingRight)
{
flip();
}
else if (mousePos.x > transform.position.x && !facingRight)
{
flip();
Debug.Log(“flip”);
}
//the raycast dosn’t seem to be working
if (Input.GetKey(KeyCode.Space) && IsGrounded())
{
Jump();
}
anim.SetBool(“Run”, horizontalInput != 0);
anim.SetBool(“Grounded”, IsGrounded());
}
void flip()
{
facingRight = !facingRight;
transform.localScale = new Vector3(1 * Right, 1, 1);
Right = Right * -1;
}
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, speed);
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;
//for some reason the raycast isn’t working
}
}