Hello everyone!
I was testing rigidbodies with balls where one ball can be controlled. Now I have an issue with my movement script (which is very basic right now): I can jump on straight surfaces but as soon as it gets a bit oblique the ball won’t jump anymore. I tried to search for solutions but couldn’t find anything.
Here is the script:
public float movementSpeed = 1;
public float jumpForce = 10;
private Rigidbody2D _rigidbody;
// Start is called before the first frame update
void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
var movementH = Input.GetAxis("Horizontal");
transform.position += new Vector3(movementH, 0, 0) * Time.deltaTime * movementSpeed;
if(Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
{
_rigidbody.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
}
Unity is 2020.3.29f1
Anyone any ideas? Thanks in advance
You should not be reading input during the fixed-update, you have to read it during the “update” (per-frame). Also, don’t modify the transform, that’s the whole point of a Rigidbody2D to write to the Transform. You’re completely bypassing what it’s trying to do.
You need to debug it. Saying “it won’t jump” means you need to determine if it’s the input or if it’s your velocity Y check or something else.
Likely if you’re on a slope and sliding down then the Y velocity will always be bigger than your magic constant of “0.001”. Normally jumping is based upon being “grounded”.
There’s lots of tutorials showing how to check for being grounded and most of them are overly complex. You can follow my basic example here:
Of course this example stops you jumping when the slope is too steep but unlike yours, it’s choose to do that by configuring it to do so. You can change the ContactFilter2D so that any contact with the ground allows you to jump.
BTW: You’re better off asking this on the 2D or Physics forums.
Thank you for your reply.
I reworked the transform part (where I move to left or right) of that very basic script. That solved it. I don’t know why exactly since the jump was done by AddForce and only the left-right movement by transform (which is messy that I did this in the first place) but yeah… both done with addforce - everything works fine and gives expected results.
I’ll work in the IsGrounded next, thanks.
1 Like