Ground the object to only jump once in 2D platformer game.
Hi.. I am new to Unity and C# and i decided i want to make a simple platform game in 2D, where the player only moves in one direction, but i cannot seem to figure it out, how to ground the player so that when i press Space multiple times it won't jump midair. Please help me.. :)
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour { public float maxSpeed = 10f;
bool facingRight = true;
bool grounded = false;
public Transform floorCheck;
float floorRadious = 0.2f;
public LayerMask Floor;
public float jumpForce;
private Rigidbody2D rb2d;
void Awake()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle (floorCheck.position, floorRadious, Floor);
float move = 1;
rb2d.velocity = new Vector2 (move * maxSpeed, rb2d.velocity.y);
if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space) && grounded)
{
rb2d.AddForce (new Vector2 (0, jumpForce));
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Comment
Answer by conman79 · Oct 16, 2016 at 09:50 PM
Your code looks like it should work. I would think it's a problem with your floorCheck.position, floorRadious or Floor LayerMask. Make sure they are all set up correctly.