Skip to content

Enable Player Movement #4

@CodeRhymesLife

Description

@CodeRhymesLife

Problem

Did you forget to fill up the gas tank before you went to save the universe 😱!? No, I just deleted the ship movement code 😄.

Where Is The Problem

File: src/entity/Ship.java
Function: checkMovement( ... )

When you fix this bug the ship should move left and right within the boundaries of the screen.

Instructions

If we detect whether the player is pressing the right and left keys we can move the ship in either direction. To detect whether the player is pressing the right and left keys use the input manager by calling the following functions:

Main.getInputManager().isRightKeyDown() will return true when the player is pressing the right key and false when they are not.
Main.getInputManager().isLeftKeyDown() will return true when the player is pressing the left key and false when they are not.

Now that you know when the player is pressing the movement keys you can react and move the ship. Luckily, there are functions for moving the ship left and right. They are:

this.moveRight(); moves the ship right.
this.moveLeft(); moves the ship left.

At this point you know when the player is pressing a movement key, and you have functions to move the ship. You will need to combined that knowledge to move the ship right if the right key is pressed and left if the left key is pressed. Give it a try at the bottom of the checkMovement( ... ) function.

After you added your new code run the program, select play and try moving left and right. Does it work? If not, check your code and try again. When you get it working continue reading.

You may have noticed that the ship can move off of the screen!

image

That's not good. It's probably because you're not checking the screen boundaries. The ship should only be able to move right if it's not touching the right side of the screen, and left if it's not touching the left side of the screen. Luckily, you were provided with isShipNotTouchingRightBorder and isShipNotTouchingLeftBorder which have checked this for you. Use them to make sure your ship stays on the screen.

Hint: you need to check if the player is pressing a movement key AND if the ship is not touching the border. To AND two boolean variables use the && operator. For example:

// This will return true
if( true && true ){
}

// This will return false
if( true && false ){
}

boolean first = true;
boolean second = true;

// This will return true
if( first && second ) {
}

After you have fixed this bug:

  1. Commit and push your changes to GitHub
  2. For groups, have each group member sync, run and test the latest code to make sure everything is working properly.
  3. Move on to Draw Enemy Ships #5!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions