Skip to content

Lesson 3

Make it jump

Walk with the arrow keys and jump with Space, the physics way.

25 minDraft

Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.

Video coming soon

We are making a video for this lesson. For now, follow the steps below!

In this lesson you will

  • Move a Physics Body with code
  • Jump only when you stand on the ground
  • Change how high you jump

What you will make

A player that walks with the arrow keys and jumps when you press Space. Almost every platform game starts like this!

You need the player and the ground from the last lesson.

1. Write the code

Open your Player script in the Code tab. Replace everything with this:

export default class Player {
  private readonly mGameObject: GameObject;
  private body: PhysicsBody | null = null;

  constructor(gameObject: GameObject) {
    this.mGameObject = gameObject;
  }

  initialize(): void {
    this.body = this.mGameObject.GetComponentByType(ComponentType.PhysicsBody);
  }

  update(args: NUpdateArgs): void {
    if (!this.body) {
      return;
    }

    let move = 0;
    if (Input.IsKeyDown(KeyCode.Left)) {
      move = -3;
    }
    if (Input.IsKeyDown(KeyCode.Right)) {
      move = 3;
    }
    this.body.SetLinearVelocityX(move);

    if (Input.IsKeyPressed(KeyCode.Space) && this.body.isGrounded) {
      this.body.ApplyLinearImpulse(0, -4);
    }
  }

  destroy(): void { }
}

Press Ctrl + S, then Play. Walk and jump!

How does it work?

  • initialize() runs once. It finds the player's Physics Body and keeps it.
  • SetLinearVelocityX(move) sets how fast the player walks.
  • Input.IsKeyPressed(KeyCode.Space) is true only at the moment you press Space. Holding it does not make you fly away.
  • isGrounded is true while the player stands on something.
  • ApplyLinearImpulse(0, -4) gives the player a push. Up is minus, remember?

Try this

  • Change -4 to -6. Higher! What about -2?
  • Make the Up arrow jump too.
  • Take away && this.body.isGrounded. Why is the game too easy now?

Try it here

Coming soon

Your mission

Change the jump number and find the best jump.

Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!