So I’m trying to make a basic platformer as a first project, as I have never coded before, and I’m having a little trouble. I’m currently trying to program the Jump function so that the player can not jump, the release and press Jump again (causing them to jump in mid-air); I want them to only jump once, then fall back to the ground. The problem lies in that I can’t seem to make it (basically) read “If the player is at y-level -4.5, the can jump. otherwise, wait.” I’ll include my PlayerMove script so far; I don’t know if this has already been answered before, but regardless, could someone help me figure this out?
using UnityEngine;
using System.Collections;
public class PlayerMove2 : MonoBehaviour {
public Rigidbody2D rb;
//These lines are here in case I decide I need/want them
// private float pressD;
// private float pressA;
// private float pressW;
// private float walkRight;
// private float walkLeft;
// private float jump;
// private float fall;
void Start ()
{
rb.GetComponent<Rigidbody2D> ();
}
void WalkRight()
{
if (Input.GetKey ("d")) {
rb.velocity = new Vector2 (2, 0);
}
}
void StopRight()
{
if (Input.GetKeyUp ("d")) {
rb.velocity = new Vector2 (0, 0);
}
}
void StopLeft()
{
if (Input.GetKeyUp ("a")) {
rb.velocity = new Vector2 (0,0);
}
}
void WalkLeft()
{
if (Input.GetKey ("a")) {
rb.velocity = new Vector2 (-2, 0);
}
}
void Jump()
{
if (//This is where the code is supposed to go){
if (Input.GetKeyDown ("w")) {
rb.velocity = new Vector2 (0, 5);
}
}
}
void Update ()
{
WalkRight ();
StopRight ();
WalkLeft ();
StopLeft ();
}
}
PLEASE NOTE: This question is slightly outdated. While the answer I received is correct, there are better ways to test for a y-position; for that matter, there are better ways to disable infinite jumps. Please refer to “Ray cast” for more info.