- Home /
rigidbody2D only jump while grounded
Hello I am a new user to Unity and I am currently using JavaScript. Right now i have a question on how to make it that my rigid body can only jump while being grounded. Right now you can press W over and over and go flying up into the sky. I am using the code
pragma strict
var jumpSpeed: float = 10;
function Start () {
} function Update () { if (Input.GetKeyDown (KeyCode.W)){
rigidbody2D.velocity.y = jumpSpeed; }
}
Any help would be greatly appreciated! The ground i am using is completely flat!
In the future use the 101/010 button to format your code. The quotation button does not work well for code.
You'll get a better answer for your question if you describe your ground. There are several ways to detect if you are grounded...some specific 'y' value, raycasting down and checking the distance, detecting a collision with the ground to name three.
Answer by hirenkacha · Dec 24, 2013 at 04:28 AM
If you want the character to move and jump on inputs, you can use CharacterController.
Following commented code is right for you.
var groundCheck : Transform;
var b_grounded : bool = false;
function Start ()
{
groundCheck = transform.Find("groundCheck");
}
// Update is called once per frame
function Update () {
b_grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
print(b_grounded);
}
}
I'm not familiar with javaScript but i've c# code which be can used to detect character is grounded or not,
using UnityEngine;
using System.Collections;
public class GroundTest: $$anonymous$$onoBehaviour {
// Use this for initialization
private Transform groundCheck;
bool b_grounded = false;
void Start ()
{
groundCheck = transform.Find("groundCheck");
}
// Update is called once per frame
void Update () {
b_grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << Layer$$anonymous$$ask.NameToLayer("Ground"));
print(b_grounded);
}
}
Hey hirenkicha I cant use Character Controller because I am using the new Unity 2D features. Is the script still viable to use?
yes.. you can use. Just add a layer to the ground sprite as "Ground" and a gameobject named "groundCheck" at the feet of the character which will check for the ground layer
Thank you! Now I just need to fix my darn $$anonymous$$ono Develop, sorry for being slow, I literally just joined this morning:)
Your answer
Follow this Question
Related Questions
Spawn object in random areas 2 Answers
Parenting Objects 1 Answer
What is #pragma strict meaning? 2 Answers
Code compilation error 1 Answer
EMERGENCY!!! PLEASE HELP!!!!! 3 Answers