- Home /
Question by
kavithapeiris · Jan 25, 2021 at 07:42 PM ·
c#rigidbody2dgravityscripting beginnerjump
How to change the gravity scale of the rigidbody 2d back to it's default value after player lands to the ground from jump
As the title says when player jumps the gravity scale of the rigidbody2d changes. I want to set it back to its default value after player lands to the ground. How to do it? Here is my code without all the solutions I tried, so you can see everything that does work.
private Rigidbody2D rb;
private BoxCollider2D boxCollider2d;
public float JumpSpeed; // Player's jump speed
public float downScaler; // gravity to change
[SerializeField] private LayerMask platformLayerMask;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
boxCollider2d = gameObject.GetComponent<BoxCollider2D>();
}
private void FixedUpdate()
{
Jump();
}
private void Jump()
{
if (IsGround() && Input.GetKey(KeyCode.Space))
{
rb.gravityScale = downScaler;
rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
}
}
private bool IsGround()
{
RaycastHit2D rayCastHit2D = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .18f, platformLayerMask);
Debug.Log(rayCastHit2D.collider);
return rayCastHit2D.collider != null;
}
Comment
Answer by logicandchaos · Jan 25, 2021 at 08:27 PM
Once you touch the ground you set the gravity scale back to 1, that is the default value.
Your answer
Follow this Question
Related Questions
Modify Rigidbody2D Jump distance 1 Answer
Character not jumping high enough 1 Answer
unity2d cannot create if gravity level 1 Answer