- Home /
My character jumps infinitely, even when in mid-air
I'm making a 2D platformer but I run into a bit of a problem, if you press the jump key repeatedly when the character is in mid-air, it will keep jumping. I only want the character to jump when it's making contact with the floor or a wall. Here's my code:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public float playerSpeed = 5.0f;
public float glideSpeed = 2.5f;
// Use this for initialization
void Start () {
//PlayerSpawnPoint
transform.position = new Vector3(0, 0, 0);
Physics.gravity = new Vector3(0, -1.0F, 0);
}
// Update is called once per frame
void Update () {
//Player Movement, left and right using arrow keys
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime);
transform.Translate (Vector3.up * Input.GetAxis("Jump") * playerSpeed * Time.deltaTime);
}
}
Comment
Answer by screenname_taken · May 21, 2014 at 07:32 AM
Just use physics.raycast and have your player raycast towards the ground. (remember to limit the range or it'll raycast to infinity). Jump if(ground is true and pressed button).
Your answer
![](https://koobas.hobune.stream/wayback/20220613145529im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help! How to change Real numbers to Natural numbers on Distance Counter script (Noob question) 0 Answers
Exponential XP (Beginner) 1 Answer
Distribute terrain in zones 3 Answers
2D Movement Problems 2 Answers
Character getting stuck on curbs.. 0 Answers