- Home /
Detecting Collision for Jumping
Hi, I was looking to see how I would detect collision between two objects, my player and the floor.
Im trying to give my player the ability to jump when they press the space bar, I tried this out at first
if (Input.GetKey(KeyCode.Space))
{
rigidbody.AddForce(0, 10, 0);
}
But this makes it to where the player flies up continuously if pressed.
What I thought about doing was detecting whether the player was colliding with the floor, and then if true, letting him jump.
Hopefully it would let him go up,then detect that the player was not colliding with the floor, then send him back down.
Please let me know if you need any further info, or if there is a simpler way to do this
Thanks again!
Answer by gharbill · May 14, 2013 at 08:55 PM
Use function OnCollisionEnter()
. your code should be something like this:
var letJump : boolean;
OnCollisionEnter(col:Collision){
if (col.transform.tag == "Ground") letJump = true;
}
function Update (){
if (Input.GetKey(KeyCode.Space))
{
if (letJump){
rigidbody.AddForce(Vector3(0, 10, 0),ForceMode.Impulse);
letJump = false;
}
}
so I would just label all my floor objects with the tag Ground, then when my player touches anything with that tag, it changes letJump = true, am I on the right track?
yes that works but I was just showing a way for your solution. depending on your game this may or may not be good Idea. for example you want your player to be able to jump when standing on top of an object, then you should change the tag of every jumpable object to "ground" which is kind of nonsense. If i were you i would have created a leg collider for my player which was staying just under the player body. and when ever this collider hits something it means our player has landed somewhere, it doesn't matter on a ground or somewhere else. this way you could omit the tag checking "if". hope this helps :)
oh by the way,the leg collider is better to be set to trigger (checking trigger box in the inspector), and then you should use OnTriggerEnter(col : Collider)
function ins$$anonymous$$d of OnCollisionEnter(col : Collsion)
thanks for your help! I just removed the tag check and changed a little bit of my script into functions, works like a charm now, THU$$anonymous$$BS UP!!
youre welcome. just don't forget to choose the answer as correct if it is :)