Hi, I’m doing a 2D game and to try and stop the play from spamming jump. I did a grounded check, only problem now is that the player can only jump once. The collision between player and ground is not being deducted.
here’s my code:
public class movment : MonoBehaviour
{
public float speed = 3.0f;
public float jumpSpeed = 20.0f;
public bool grounded = true;
void Update ()
{
Vector3 x = Input.GetAxis ("Horizontal") * transform.right * Time.deltaTime * speed;
transform.Translate (x);
if(Input.GetButtonDown("Jump"))
{
Jump();
}
}
void Jump()
{
if (grounded == true)
{
rigidbody2D.AddForce (Vector3.up * jumpSpeed);
grounded = false;
}
}
void onCollisionEnter2D(Collision hit)
{
grounded = true;
Debug.Log ("I'm standing on the ground.");
}
}
thank you, I implemented the correction noted. but my problem still precisest I can only preform the 1st jump only,no more. any other advice or a page to look at to put me in the right direction would be greatly appreciated.
Did the function get called means debug log is printed ? Remember one thing more one of the bodies must have a rigid body to get called the "OnCollisionEnter2D"
nevermind … found my mistake… when I did the changed noted above I forgot to change hit to coll so it didn’t work, but now everything works just fine.
thanks you for assistance.
It’s not a good idea to make possible jump everytime you get a collision.
(remove “grounded = false” at line 23 i think that it’s the problem you could jump only one time)
So, if you add a second collider trigger on your surface and add at this gameObject with this trigger area the example code below:
This won't prevent the player from jumping in the air when it falls off the ground. Add a trigger collider and use OnCollisionStay2D is better. Also, [here][1]'s a couple ways to do ground check using Raycast2D and OverlapCircle2D. [1]: http://shinerightstudio.blogspot.tw/2016/10/in-air-check-for-2d-platformer-games-in.html
– casd82