Controlling sprite coordinates

Let's prevent the sprite from going off screen. Here, we are going to render the ship in another part of the screen. Follow these steps to do so:

  1. First, let's set the screen size to dedicated constants so that we can use it in our code:
      const screenWidth = 800;
const screenHeight = 600;

var config = {
type: Phaser.AUTO,
width: screenWidth,
height: screenHeight,
backgroundColor: '#03187D',
scene: {
preload: preload,
create: create,
update: update
}
};
  1. Now, on each update, you can check whether the new coordinates of the ship are off screen and change the value to point to another place, or maybe even prevent the ship from moving if you want the ship to stay where it is:
      function update() {
// RIGHT button
if (cursors.right.isDown) {
ship.x += 2;
ship.flipX = false;
}
// LEFT button
else if (cursors.left.isDown) {
ship.x -= 2;
if (ship.x <= 0) {
ship.x = screenWidth;
}

ship.flipX = true;
}
// UP button
else if (cursors.up.isDown) {
ship.y -= 2;
}
// DOWN button
else if (cursors.down.isDown) {
ship.y += 2;
}
}
  1. As you can see, each time the horizontal or x coordinate becomes less than zero, that is, the image is going off the left-hand side of the screen, we reassign it to the value of the screen's width, that is, the right-hand side of the game screen.
  2. Restart the game and press the Left arrow key until the ship reaches the left-hand side of the game screen:

  1. Now, try moving the ship further off of the screen. Notice how it appears from the right-hand side and keeps moving to the center:

  1. Now, let's do the same for the vertical axis:
      function update() {
// RIGHT button
if (cursors.right.isDown) {
ship.x += 2;
if (ship.x >= screenWidth) {
ship.x = 0;
}
ship.flipX = false;
}
// LEFT button
else if (cursors.left.isDown) {
ship.x -= 2;
if (ship.x <= 0) {
ship.x = screenWidth;
}
ship.flipX = true;
}
// UP button
else if (cursors.up.isDown) {
ship.y -= 2;
if (ship.y <= 0) {
ship.y = screenHeight;
}
}
// DOWN button
else if (cursors.down.isDown) {
ship.y += 2;
if (ship.y >= screenHeight) {
ship.y = 0;
}
}
}

When the ship reaches the bottom edge of the screen, we move it to the top, and vice versa. Now, it's impossible for the ship to leave the screen; the ship always appears on the opposite edge of the screen.

In this section, we have learned how to control the sprite's coordinates on the screen. Now, let's learn how to make the ship move faster by controlling its speed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.223.123