- Home /
Simple Rigidbody2D controller (Platformer Jump)
I'm trying to make a very simple character controller script for an object with a rigidbody2D (aiming for basic 2D platformer gamelay with WASD and Space to jump).
void HandleMovement() {
if (Input.GetKey (KeyCode.D)) {
rigidbody2D.velocity = new Vector2(walkForce, rigidbody2D.velocity.y);
print(rigidbody2D.velocity);
}
else if (Input.GetKey (KeyCode.A)) {
rigidbody2D.velocity = new Vector2(-walkForce, rigidbody2D.velocity.y);
}
if (Input.GetKeyDown(KeyCode.Space) & grounded) {
jumping = true;
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, jumpForce);
}
}
I can't understand why my HandleMovement method doesn't work. In my case no matter how big a value I put for walkForce or jumpForce, the object doesn't move a bit. The velocity is set correctly because it prints out the correct velocity when D is held, it's just that the object doesn't show any sign of moving. What could be causing this?
EDIT: I've solved this by runing the HandleMovement in FixedUpdate instead of Update. The controls now work but the jump is very "buggy-ish". How can get a nice fluid platformer jump with a rigidbody2d? What I've done above just doesn't play nicely.
Try using something like
void Handle$$anonymous$$ovement() {
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space) & grounded) {
jumping = true;
rigidbody2D.AddForce(0f, jumpForce);
}
}
Ins$$anonymous$$d of applying a velocity, you can just add an upward force to the object. The x value doesn't require a force because it will retain whatever velocity the object already has. Don't forget to still set your jumping value to true. And also be sure to set it back to false when object touches the ground again if you are working on a platformer of sorts.
Thanks, I tried that and it works but I still find the jump not very smooth. And also for some reason the character doesn't always jump to the same height
Do you have any other scripts? Anything outside that could be effecting it. $$anonymous$$aybe your character has more than one collider touching itself
the current script you already has works fine for me. I would check to make sure you don't have something else effecting it