Hello,
So I Tried Programming The Player To Move and Jump (2D) For Now it only worked on moving
when I first started jumping worked but I had a bug where I can just press space and jump forever so I added a Grounded Variable and that’s where it all went downhill
Please Help[ me by telling me what’s wrong with my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platformer : MonoBehaviour
{
public float speed;
public float jumpForce;
bool isGrounded = false;
public Transform isGroundedChecker;
public float checkGroundRadius;
public LayerMask groundLayer;
Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move();
Jump();
CheckIfGrounded();
}
void Move() {
float x = Input.GetAxisRaw("Horizontal");
float moveBy = x * speed;
rb.velocity = new Vector2(moveBy, rb.velocity.y);
}
void Jump() {
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
void CheckIfGrounded() {
Collider2D collider = Physics2D.OverlapCircle(isGroundedChecker.position, checkGroundRadius, groundLayer);
if (collider != null) {
isGrounded = true;
} else {
isGrounded = false;
}
}
}
If you debug when hitting space it will tell you if your isGrounded variable is working properly. If the console prints true then your player is grounded so you can eliminate that as an issue.
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log(isGrounded); //print to console to see if you are grounded when pressing space
if(isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
}
Ok This Is The New Code But After i add it, it gives me this error
“Assets\Platformer.cs(44,39): error CS1026: ) expected”
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platformer : MonoBehaviour
{
public float speed;
public float jumpForce;
bool isGrounded = false;
public Transform isGroundedChecker;
public float checkGroundRadius;
public LayerMask groundLayer;
Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move();
CheckIfGrounded();
Jump();
}
void Move() {
float x = Input.GetAxisRaw("Horizontal");
float moveBy = x * speed;
rb.velocity = new Vector2(moveBy, rb.velocity.y);
}
void CheckIfGrounded() {
Collider2D collider = Physics2D.OverlapCircle(isGroundedChecker.position, checkGroundRadius, groundLayer);
if (collider != null) {
isGrounded = true;
} else {
isGrounded = false;
}
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space);
{
Debug.Log(isGrounded); //print to console to see if you are grounded when pressing space
if(isGrounded);
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
}
}