Skip to content

Lesson 1

Move with the keyboard

Use the arrow keys to move your character left and right.

20 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

  • Read the keyboard in a script
  • Move a sprite with the arrow keys
  • Change the speed from the Inspector

What you will make

A character that walks left and right when you press the arrow keys.

1. Make the player

Make a sprite and name it Player. Give it a picture.

2. Add a script

Click Player, then Add Component. Type Player and choose Create script "Player".

3. Write the code

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

export default class Player {
  speed = 200;

  private readonly mGameObject: GameObject;
  private readonly mTransform: NCTransform;

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

  initialize(): void { }

  update(args: NUpdateArgs): void {
    if (Input.IsKeyDown(KeyCode.Right)) {
      this.mTransform.position.x += this.speed * args.dt;
    }
    if (Input.IsKeyDown(KeyCode.Left)) {
      this.mTransform.position.x -= this.speed * args.dt;
    }
  }

  destroy(): void { }
}

Press Ctrl + S, then Play. Press the arrow keys!

How does it work?

  • Input.IsKeyDown(KeyCode.Right) is true while you hold the right arrow.
  • if (...) { ... } means: do this only if it is true.
  • speed = 200; is a variable: a box with a name that keeps a value.

Change the speed without code

Stop the game and click Player. Look at the Script in the Inspector: speed is there! Change it to 400 and play again.

Picture coming soonThe speed setting of the script in the Inspector

Try this

  • Make the Up and Down arrows move it on y.
  • Make it run faster while you hold Shift. Hint: KeyCode.Shift.

Try it here

Coming soon

Your mission

Change speed in the Inspector, then walk with the arrow keys.

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!