- Home /
my player continuously jump when i press space-bar
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class player : MonoBehaviour {
public LayerMask ground_layer;
public float speed;
public float jumpspeed;
Rigidbody2D rb;
BoxCollider2D box;
// Start is called before the first frame update
void Start()
{
rb=GetComponent<Rigidbody2D>();
box=transform.GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void FixedUpdate()
{
float input=Input.GetAxisRaw("Horizontal");
rb.velocity=new Vector2(input*speed, rb.velocity.y);
if(IsGrounded() && Input.GetButtonDown("Jump"))
{
rb.velocity=new Vector2(rb.velocity.x,jumpspeed);
}
}
bool IsGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, Vector2.down * .1f, ground_layer);
Debug.Log(raycastHit2d.collider);
return raycastHit2d.collider != null;
}
}
Answer by Nafis1053 · Nov 25, 2019 at 01:23 PM
Hi!.....I might be wrong here....so check what i say before becoming sure about it......I cant tell if our IsGrounded() function is working properly,implemented well,or is right for the situation here....if all you are checking here is if the object is touching the ground or not....you can try this code here which is pretty simple and also with less complexity.....
' RaycastHit2D Hit = Physics2D.Raycast(checkHeightObject.transform.position, Vector3.down);
if(Hit.collider!=null && Hit.collider.CompareTag("Base"))
{
if (Hit.distance > 0.1f)
{
grounded=false;
}
else
{
grounded=true;
}
}`
know that u need to add a tag with the ground or base object in your game....i added the tag "base" in this example.....plus checkHeightObject is a object i attached with my character,from where i am raycasting for the ground....u need to place this object with your player object in a suitable way....right under him....
A Raycast would be more prefferable than a boxcast....if all u are looking for is if the player is grounded or not.....as u dont have any other thing going on in the isgrounded function.... as for ur player continuously jumping.......u are assigning the velocity to ur player in every frame.....once he jumps,"jumpspeed" is being continuously assigned in every frame.....so he shows no sign of coming down....:3.......optimal way is using rb.AddForce(new Vector2(0.0f,jumpspeed))......This should work just fine and is the best way for implementing basic jumps....Hope it helps....:D
Your answer
Follow this Question
Related Questions
jumping at a degrees angle 1 Answer
how to make a realistic jump? Very urgent please :( 0 Answers
having a subtle issue with my juump script 1 Answer
bumper script 1 Answer
How can I limit jump height in unity? 3 Answers