- Home /
,How to make a platformer-like jumping script?
,I'm new to unity, (especially new to C#) and I want to make my character jump in a game I'm making. I don't know how to make it so you can't jump in midair, because I suck at variables and collision detection :P anyone know how to do this? (Sorry for asking a newbie question) Here is my code so far if you want it (for the player)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
[SerializeField]
KeyCode keyPositive;
[SerializeField]
KeyCode keyNegative;
[SerializeField]
Vector2 force;
void FixedUpdate()
{
if(Input.GetKey(keyPositive))
{
rb.velocity += force;
}
if (Input.GetKey(keyNegative))
{
rb.velocity -= force;
}
}
}
Answer by frederikedel · Aug 12, 2020 at 10:04 AM
There are of course many ways, but I suggest using an empty Gameobject attached to the bottom of the player, then checking if the object is overlapping with a specific layer (Layermask called whatIsGround)
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
}
And then just get the user Input and change the velocity.
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613005057im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Jumping player at platform connection 2 Answers
Glitchy collisions 0 Answers
My player goes straight through my colider 3 Answers
Diagonal collision script not working (Unity + Orthello, C#) 1 Answer
not allowing to walk on certain surfaces 2 Answers