Forum begins after the advertisement:
[Part 1] My player isn’t jumping no matter what I do.
Home › Forums › Video Game Tutorial Series › Creating a Metroidvania in Unity › [Part 1] My player isn’t jumping no matter what I do.
- This topic has 1 reply, 2 voices, and was last updated 2 years, 11 months ago by
Terence.
-
AuthorPosts
-
November 28, 2023 at 8:03 pm #12327::
I have no idea why the player doesn’t jump. Here is the code.
<pre>using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour { [Header(“Horizontal Movement Settings:”)] [SerializeField] private float walkSpeed = 1;
<code>[SerializeField] private float jumpForce = 45; [Header("Ground Check Settings:")] [SerializeField] private Transform groundCheckPoint; [SerializeField] private float groundCheckY = 0.2f; [SerializeField] private float groundCheckX = 0.5f; [SerializeField] private LayerMask whatIsGround; //References Rigidbody2D rb; private float xAxis; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { GetInputs(); Move(); Jump(); } void GetInputs() { xAxis = Input.GetAxisRaw("Horizontal"); } void Move() { rb.velocity = new Vector2(walkSpeed * xAxis, rb.velocity.y); } public bool Grounded() { if (Physics2D.Raycast(groundCheckPoint.position, Vector2.down, groundCheckY, whatIsGround) || Physics2D.Raycast(groundCheckPoint.position + new Vector3(groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround) || Physics2D.Raycast(groundCheckPoint.position + new Vector3(-groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround)) { return true; } else { return false; } } void Jump() { if (Input.GetButtonUp("Jump") && rb.velocity.y > 0) { rb.velocity = new Vector2(rb.velocity.x, 0); } if (Input.GetButtonDown("Jump") && Grounded()) { rb.velocity = new Vector3(rb.velocity.x, jumpForce); } }</code>}</pre>
Can you guys please help me with this?
November 28, 2023 at 9:19 pm #12329::Hi demilade, you will only be able to jump when the <code>Grounded()</code> function returns true. That means that this section here needs to be true:
<pre>public bool Grounded() { if (<mark class=”green”>Physics2D.Raycast(groundCheckPoint.position, Vector2.down, groundCheckY, whatIsGround) || Physics2D.Raycast(groundCheckPoint.position + new Vector3(groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround) || Physics2D.Raycast(groundCheckPoint.position + new Vector3(-groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround)</mark>) { return true; } else { return false; } }</pre>
You need to make sure that your <strong>Ground Check X</strong> and <strong>Ground Check Y</strong> have non-zero values, your <strong>Ground Check Point</strong> is set, and the <strong>What Is Ground</strong> property is set to the correct layers.
-
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: