Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 2-4: Enter the Robot

10/13/2012

402 Comments

 
Picture
Lesson #2-9: Creating the Main Character
Welcome to the fourth day! Now that we got the basic frameworks set up, we will be adding our main character.

To do so, we will be creating a new class. Within this class, we will do the following:

1. Manage x, y coordinates and speed.
2. Make updates to speed and position.
3. Allow other classes to retrieve its x, y related variables.

Therefore, the methods of this class will be divided into these categories:

1. Constantly updated methods that are called on each iteration of the game loop.
2. Methods that are only called upon player input.
3. Helper methods that retrieve and change the value of variables in the class.

Let's get started.

We begin by creating a new class called Robot.java in the kiloboltgame package (or whatever you named your package). 

Copy and paste the following:

Figure 2-13: Robot.java

package kiloboltgame;

import java.awt.Graphics;

public class Robot {
        //In Java, Class Variables should be private so that only its methods can change them.
private int centerX = 100;
private int centerY = 382;
private boolean jumped = false;

private int speedX = 0;
private int speedY = 1;

public void update() {

// Moves Character or Scrolls Background accordingly.
if (speedX < 0) {
centerX += speedX;
} else if (speedX == 0) {
System.out.println("Do not scroll the background.");

} else {
if (centerX <= 150) {
centerX += speedX;
} else {
System.out.println("Scroll Background Here");
}
}

// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{                       
                     centerY += speedY;
                }

// Handles Jumping
if (jumped == true) {
speedY += 1;

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

}

// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
}

public void moveRight() {
speedX = 6;
}

public void moveLeft() {
speedX = -6;
}

public void stop() {
speedX = 0;
}

public void jump() {
if (jumped == false) {
speedY = -15;
jumped = true;
}

}
}

What do those variables mean?

A brief description of the variables (there will be more a in depth discussion further down):
1. centerX, centerY are the x, y coordinates of our robot character's center.
2. speedX, speed Y are the rate at which these x and y positions change.
3. jumped changes to true if the character is in the air, and reverts to false when grounded.

Now let's talk about each of the methods above.

1. Always called methods:

update() : this method will be called on each iteration of the for loop. This is a very important method, so let's spend time taking about it. But before we do that, PLEASE look through it one more time and try to make sense of the if statements.

*When examining the update() method again, Keep the following in mind. 

1. Speed can be negative, which means that a character with negative speedX would move to the left.

2. The Origin (0,0) pixel is at the TOP LEFT. I will talk about this below. This means that if a character has a positive speedY, he is FALLING, not RISING.

Picture
The origin is at the top left of the screen.
3. Recall the meaning of += :
x += 1; 
is equivalent to: 
x = x + 1;

4. We are arbitrarily defining the ground at about 440 pixels. That means if the character's centerY is at about 382, his feet would reach the ground at ~440 pixels.

5. If the character's centerX is lesser than 60, his left hand will be outside the left edge of the screen.

Now have a look at a diagram:
Picture
Basic Diagram

Examine this update() method once more before moving on!

  public void update() {

// Moves Character or Scrolls Background accordingly.
if (speedX < 0) {
centerX += speedX; //This changes centerX by adding speedX.
} else if (speedX == 0) { 
System.out.println("Do not scroll the background.");

} else {
if (centerX <= 150) { //If the character's centerX is in the left 150 pixels
centerX += speedX; //Change centerX by adding speedX.
} else {
System.out.println("Scroll Background Here"); /
}
}

// Updates Y Position
if (centerY + speedY >= 382) {
              //382 is where the character's centerY would be if he were standing on the ground.
centerY = 382;
}else{                      
                     centerY += speedY; //Add speedY to centerY to determine its new position
                }

// Handles Jumping
if (jumped == true) {
speedY += 1; //While the character is in the air, add 1 to his speedY.     
                       //NOTE: This will bring the character downwards!

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

}

// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) { //If speedX plus centerX would bring the character     //outside the screen,
centerX = 61;
                       //Fix the character's centerX at 60 pixels.
}
}

Dissecting the update() method:

First, let's discuss the section labeled:
// Moves Character or Scrolls Background accordingly.

1. Our first if statement:
For our game to draw the character in the proper location, centerX must constantly be updated; however, if the character is not moving (speedX == 0), then there is no need to update centerX by adding speed to it.

2. Watch a few seconds of this video:
In Metal Slug, the character freely moves in the left half of the screen, but once he starts moving to the right, the character stays at the same location while the background scrolls. This is what we are doing here. If speed is zero, then we will not scroll the background. If the character's centerX coordinate is less than 150, he can move freely. Else, we will scroll the background and stop moving the character.

Now, let's discuss the sections labeled: 
//Updates Y Position and //Handles Jumping.
Since gravity is always present, the character is constantly being pushed to the ground. We assume that the ground is located at about 440 pixels down from the top, and if the character's Y position plus his Y speed will bring him below the ground, we use the statement: centerY = 382; to manually set the character at a height that will stop him from moving.

The Handles jumping section will check the current speed and position to test whether the character is in mid-jump or on the ground.

Finally, let's discuss the section labeled:// Prevents going beyond X coordinate of 0

This section just checks if the character is moving beyond the left edge of the screen and fixes his centerX coordinate at 61 if he tries to move off the screen.

Now that we have discussed the update() method, we will move on to the other methods:

2. Methods called upon input:


moveRight(), which sets the character's horizontal speed (speedX) as 6.
moveLeft(), which sets the character's speedX as -6.
stop(), which sets the speedX as zero.
jump(), which sets the vertical speed as -15. 


3. Helper Methods
We will be adding these later in today's lesson.
Lesson #2-10: Graphics 101
To make sense of those speed values, we need to talk about some basic graphical stuff.

Pixels are the tiny squares on your display. They are the smallest unit of change in your display, and are either on or off and have a single color. 

Screen resolution is a representation of your horizontal and vertical pixel counts. For example, a resolution of 1920 by 1080 tells you that a display has 1920 horizontal pixels and 1080 vertical pixels.

Individual pixel coordinates are given in (x,y); however, by convention and technological limitations, we choose the top left corner as (0,0). On a screen with resolution 1920 x 1080, then, the bottom right pixel has coordinates (1919, 1079) NOT (1920, 1080). This is because we begin counting from zero, not one.

I will now apply this to describe how we create an illusion of motion in games.
Within the StartingClass's paint method, we will write a statement that will look something like this:
drawRobot(centerX, centerY). This will draw the Robot at the coordinate (centerX, centerY). 

With each iteration of the paint method, which is called roughly 60 times per second, the Robot will appear to move as its centerX and centerY values change. To change the centerX and centerY, we use the speedX and speedY variables, which represent the rate at which centerX and centerY will change with each update of the game (60 times per second).

So when I say that moveRight() sets the character's horizontal speed as 6, I am saying that each time that moveRight() is called, the character's speed will be given a value of 6 pixels. In the case of the robot, the update() method, will add this speed of 6 to the centerX value. Changing the centerX value will mean that the drawRobot(centerX, centerY) statement above will now "move" the robot to a new location with its new centerX. If this happens on a speed that is fast enough, we get the illusion of smooth motion.
Creating a Robot named robot.
With the Robot class created, we can now create a Robot object inside StartingClass.
Locate:

public class StartingClass extends Applet implements Runnable, KeyListener {
and below it, declare:
private Robot robot;
to create a private Robot object called robot.

Now, let us initialize this value by writing:

robot = new Robot(); in the start() method.

Now that we have created an instance of the Robot class, we can take Robot's methods and call them by writing:

robot.methodName(); (methodName() is just a generic name for any method in the Robot class).
Lesson #2-11: Drawing the Main Character from StartingClass.java
There's lots of code to cover here, and I will try to keep the explanations as simple as possible; however, some of the concepts here are a bit elusive and you might wonder how you would come up with such a solution when programming by yourself in the future. This is one of those cases where you are not required to memorize or fully understand how something works, because it is so easy to implement and difficult to fully understand.

We will be working in the StartingClass.java
1. First make sure that you have imported : java.awt.Graphics;
2. Then we will begin by going below the run method (it does not matter where, but I like grouping related methods together) and create the following methods: update(Graphics g) and paint(Graphics g). It is easy to do create these methods by typing update and then pressing Ctrl+Space, and choosing the first option. Do the same thing with paint. 


The update() method is implicitly called automatically, and will loop over and over again. The paint() will similarly be always called, with the repaint() statement within the run() method.

I. Defining the update() Method:

Let's first deal with the update() method. We will use this method for double buffering - a technique that is used to prevent tearing and flickering. Feel free to read up more on this subject, as I am not an expert in this topic. The basic concept is that it works by retaining the previous position of the screen's current image for a short amount of time, so that the movement of the image looks smooth and natural.

1. Begin by declaring (below private Robot robot): 

private Image image;
private Graphics second;

As class variables (accessible by all methods within the StartingClass). 

2. If you receive an error on either Graphics or Images, press Ctrl+Shift+O to auto-import them.
3. Now go down the the update() method and add the following:

Figure 2-14: update() method within StartingClass.java

  @Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}


second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);


g.drawImage(image, 0, 0, this);


}
The individual statements of this segment of code is easy to understand. What is difficult is discerning how each of these pieces fit together as a whole to create a double buffering system. Feel free to look at this in detail, but my advice to you: ignore it, accept it, and move on. :)

II. Defining the paint() Method:
The paint() method will be used to draw our graphics to the screen. For now, we only need to draw the robot, so it will have one statement inside:

Figure 2-15: paint() method within StartingClass.java

        @Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}
The g.drawImage() method takes in the following parameters:
g.drawImage(img, x, y, observer)

An Image variable, the x and y coordinates where you want to draw the Image, and an ImageObserver (which is slightly beyond the scope of this lesson). 

In our example, we will use the character variable to represent our robot image, and then draw the top left corner of the robot 61 pixels to the left, and 63 pixels above the (centerX, centerY), and then use the "this" keyword as our ImageObserver.

At this point, you will have a lot of errors. We will address them each one at a time.
Picture
The paint() method should have errors.

I. Addressing the character variable error

1. The character variable is undefined, so we must first define it. 
Find the statement:  private Image image;
and add , character like so:

private Image image, character;

2. Now we must assign a value to it. We will assign an image to the variable character. To do so, we must create a URL object that will allow us to use addresses (such as C:\Images\image.jpg) to refer to images. 

So, below private Image image, character; add:

private URL base;

(As mentioned before, private variables are only accessible from within the class - it is common practice to create class-wide variables as private).

Remember to import URL.

3. Within the init() method, we will define the URL base and the assign value to character. 
Make these changes:

Figure 2-16: init() method within StartingClass.java

  @Override
public void init() {

setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}


// Image Setups
character = getImage(base, "data/character.png");

}
4. Finally, we must create a data folder by right clicking on src and creating a folder named data.
Inside it, download, drag, and drop this image:
character.png
File Size: 3 kb
File Type: png
Download File

That should solve the character errors. The StartingClass.java will look like this now:
(If you have errors, try Rebuilding by doing the following: On the toolbar above, click on Project > Clean > OK).

Figure 2-17: StartingClass.java, After Fixing character Errors

 package kiloboltgame;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener {


        private Image image, character;
private Graphics second;
private URL base;

@Override
public void init() {

setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}

// Image Setups
character = getImage(base, "data/character.png");

}

@Override
public void start() {
robot = new Robot();

Thread thread = new Thread(this);
thread.start();
}

@Override
public void stop() {
// TODO Auto-generated method stub
}

@Override
public void destroy() {
// TODO Auto-generated method stub
}

@Override
public void run() {
while (true) {

repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}

second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);

g.drawImage(image, 0, 0, this);

}

@Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

@Override
public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;

case KeyEvent.VK_LEFT:
System.out.println("Move left");
break;

case KeyEvent.VK_RIGHT:
System.out.println("Move right");
break;

case KeyEvent.VK_SPACE:
System.out.println("Jump");
break;

}

}

@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;

case KeyEvent.VK_LEFT:
System.out.println("Stop moving left");
break;

case KeyEvent.VK_RIGHT:
System.out.println("Stop moving right");
break;

case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;

}

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

}

II. Addressing the get... errors

We still have these errors in our StartingClass:
Picture
In my previous description of the Robot class, I mentioned that we would be creating:

1. Constantly updated methods that are called on each iteration of the game loop.
2. Methods that are only called upon player input.
3. Helper methods that retrieve and change the value of variables in the class.


We never did create the helper methods. So here we do that. 

1. Open Robot.java again.
2. Right click anywhere on the white space, click Source >> and select Generate Getters and Setters.
Picture
Generate Getters and Setters
Picture
3. Select all, sort by getters then setters, and then press OK.

What are getters and setters?
Again, in Java, it is common practice to set class-wide variables as private. For other classes to access these private variables, they must use helper functions known as getters and setters.

Let's have a look at a pair:

  public int getSpeedX() {
return speedX;
}

and
public void setSpeedX(int speedX) {
this.height = speedX;
}

Whenever a getter method is called, it returns the value that you "get." When I say:
myNewVariable = getSpeedX(), my new variable will get the value of speedX.

If I say: setSpeed(10); then my speedX will now have a value of 10.

With these three things finished, the result is:

Figure 2-18: StartingClass.java After Fixing the get... Errors

 package kiloboltgame;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener {

private Robot robot;
private Image image, character;
private Graphics second;
private URL base;

@Override
public void init() {

setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}

// Image Setups
character = getImage(base, "data/character.png");

}

@Override
public void start() {
robot = new Robot();

Thread thread = new Thread(this);
thread.start();
}

@Override
public void stop() {
// TODO Auto-generated method stub
}

@Override
public void destroy() {
// TODO Auto-generated method stub
}

@Override
public void run() {
while (true) {

repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}

second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);

g.drawImage(image, 0, 0, this);

}

@Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

@Override
public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;

case KeyEvent.VK_LEFT:
System.out.println("Move left");
break;

case KeyEvent.VK_RIGHT:
System.out.println("Move right");
break;

case KeyEvent.VK_SPACE:
System.out.println("Jump");
break;

}

}

@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;

case KeyEvent.VK_LEFT:
System.out.println("Stop moving left");
break;

case KeyEvent.VK_RIGHT:
System.out.println("Stop moving right");
break;

case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;

}

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

}
Lesson #2-12: Character Movement
At this point, you should be able to draw your character to the screen without any flickering:

Picture
Our progress so far.
Now we will make our final set of changes to make this character move.

First: In StartingClass go down to the keyPressed() method, and replace:

1. System.out.println("Move left"); with robot.moveLeft();
2. System.out.println("Move right"); with robot.moveRight();
3. System.out.println("Jump"); with robot.jump();

And in the keyReleased() method, replace:

1. System.out.println("Stop moving left");
and
2. System.out.println("Stop moving right");
with 
robot.stop();

Second: Within the run() method, we need to call robot.update();

Figure 2-19: run() method within StartingClass.java

  @Override
public void run() {
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Now you should finally have the end result:

Figure 2-20: StartingClass.java, End of Day 4

package kiloboltgame;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener {

private Robot robot;
private Image image, character;
private Graphics second;
private URL base;

@Override
public void init() {

setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}

// Image Setups
character = getImage(base, "data/character.png");

}

@Override
public void start() {
robot = new Robot();

Thread thread = new Thread(this);
thread.start();
}

@Override
public void stop() {
// TODO Auto-generated method stub
}

@Override
public void destroy() {
// TODO Auto-generated method stub
}

@Override
public void run() {
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}

second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);

g.drawImage(image, 0, 0, this);

}

@Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

@Override
public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;

case KeyEvent.VK_LEFT:
robot.moveLeft();
break;

case KeyEvent.VK_RIGHT:
robot.moveRight();
break;

case KeyEvent.VK_SPACE:
robot.jump();
break;

}

}

@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;

case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;

case KeyEvent.VK_LEFT:
robot.stop();
break;

case KeyEvent.VK_RIGHT:
robot.stop();
break;

case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;

}

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

}

Figure 2-21: Robot.java, End of Day 4

 package kiloboltgame;

import java.awt.Graphics;

public class Robot {

private int centerX = 100;
private int centerY = 382;
private boolean jumped = false;

private int speedX = 0;
private int speedY = 1;


public void update() {

// Moves Character or Scrolls Background accordingly.
if (speedX < 0) {
centerX += speedX;
} else if (speedX == 0) {
System.out.println("Do not scroll the background.");

} else {
if (centerX <= 150) {
centerX += speedX;
} else {
System.out.println("Scroll Background Here");
}
}

// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{                        
                        centerY += speedY;
                }

// Handles Jumping
if (jumped == true) {
speedY += 1;

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

}

// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
}

public void moveRight() {
speedX = 6;
}

public void moveLeft() {
speedX = -6;
}

public void stop() {
speedX = 0;
}

public void jump() {
if (jumped == false) {
speedY = -15;
jumped = true;
}

}

public int getCenterX() {
return centerX;
}

public int getCenterY() {
return centerY;
}

public boolean isJumped() {
return jumped;
}

public int getSpeedX() {
return speedX;
}

public int getSpeedY() {
return speedY;
}

public void setCenterX(int centerX) {
this.centerX = centerX;
}

public void setCenterY(int centerY) {
this.centerY = centerY;
}

public void setJumped(boolean jumped) {
this.jumped = jumped;
}

public void setSpeedX(int speedX) {
this.speedX = speedX;
}

public void setSpeedY(int speedY) {
this.speedY = speedY;
}


}

That's it for Day 4. This was a tough lesson. Please let me know in the comments section if you need me to clarify anything at all.

If your code is not working for any reason, try Rebuilding by doing the following:
On the toolbar above, click on Project > Clean > OK.

As a general rule, if your code does not work and you cannot find any errors, your first step should be to rebuild the project!

Thanks for reading and please support us if you are learning! Every dollar helps us out tremendously!
Picture
kiloboltgame4.zip
File Size: 13 kb
File Type: zip
Download File

Instructions on importing projects can be found here.
Picture
Go to Day 3: Taking User Input
Go to Day 5: Background and Sprites
402 Comments
David link
10/14/2012 01:41:18 am

I was following the text and noticed:

robot = new Robot();

wasn't mentioned.

Reply
Ben
10/14/2012 04:39:35 am

I too noticed this. I also am having other issues but I'm checking to see if its a mistake I have made first.

Reply
Ben Brace
10/14/2012 07:10:08 am

Working fine now, wasn't loading the png file for some reason. Great tutorials!

James C.
10/15/2012 12:34:44 am

This will be fixed soon.

Reply
simon
1/8/2014 11:33:17 am

I wanted to create 3d games.....am I in the right place

Aoi Okami
3/14/2014 04:31:52 am

With my personal experience and say yes. I also want to create 3D games but before jumping to the sea, you need to know how to swim. This GREAT tutorial will help you understand the basic knowledge in game developing like looping, collision and other logic that you need to use in 3D games, especially if your using a game engine.

Ev
12/7/2012 06:53:54 am

Yeah I realized this too.... I ran into a null pointer exception till I realized that the robot object had not be initialized O:

Reply
James C.
12/8/2012 01:37:06 am

Sorry about that! I thought I fixed that already.

richard
11/7/2013 10:27:16 pm

The robot declaration in still missing in one of the "full" code snippets. Great tutorial.

Wv
3/7/2014 05:43:07 pm

This was the reason why robot doesn't show up in my program. I have no idea why though.

Can someone explain why this causes the image to not to show up?

Reply
James link
10/14/2012 06:46:19 am

I have been following these tutorials and I must say they are great. Keep them coming!

Reply
nightmare6m
10/14/2012 12:17:16 pm

Had the same issue with the png but also got it working in the end. Can't wait for day 5.

Reply
rolson
1/19/2013 02:48:29 am

How did you get the PNG to load. Mine isn't loading either

Reply
rolson
1/20/2013 11:50:06 am

Actually to get the image to load I had to change the path to from "data/character.png" to " ../data/character.png" It worked after that.

Bill Siegel
4/2/2013 08:00:36 pm

Thanks rolson.. good find, I also had to add the "../" to "data/character.png" to end up with " ../data/character.png" then it would paint

Son
8/11/2013 09:39:08 pm

Mine just works after I changed:
- inside init(): base = getDocumentBase() -> base = getCodeBase()
- Turn Java Compiler from 1.7 -> 1.6

Hope I help somebody ! :)

Jeison
2/12/2014 09:59:15 am

YO man can any one PLLLLLLZZZZZZZZZ help me like face chat or some thing to help me download the picture icons cause that is my biggest problem.

Harshit
7/9/2016 05:31:51 am

Replace "data/character.png" with "..bin/data/character.png".
Worked with me. ;)

morloxx
6/1/2018 10:03:35 am

(2018) after many tries this it what works for me:
base = getCodeBase();
character = getImage(base, "../bin/kiloboltgame/data/character.png");

Ben
10/14/2012 06:43:35 pm

Just curious about the "height and width" variables mentioned when you set up the getters and setters, I can see them in your code screenshot but not in any of the code itself, what are these used for?

Reply
James C.
10/15/2012 12:30:41 am

I included them by accident. I will fix that asap. :)

Reply
Victor
10/28/2015 02:37:00 am

The variable height is still mentioned in day 4 tutorial... you've said "ASAP in 2012 Hehehe. This tutorial is great and easy to understand. Great job man.

Ben
10/14/2012 10:53:28 pm

One other thing I've noticed (having copied and adapted the code to create my own game alongside this one) is that movement is jarred, if I suddenly change direction from left to right my character will move a fraction pause for a short while and then move in the direction as normal. Any idea what might be causing this?

Reply
James C.
10/15/2012 12:32:51 am

Ben, this is normal behavior when you press two buttons and release one. We will be implementing a more complex movement system soon. This game is nowhere near finished so don't worry about little bugs for now.

Reply
Ben
10/15/2012 02:07:22 am

I actually figured this out shortly after I posted my comment and realised that the stop method was still being invoked on the release of one key even if another one had already been pressed.

Again James, thanks for these tutorials they are awesome. I am using them as a base to build my first android app and game and I will 100% be putting your name and website in my credits. I look forward to the rest of the series.

Matt link
10/15/2012 11:31:19 pm

Thanks for your time on the tutorials James, very much appreciated.

Reply
Manish
10/16/2012 09:41:26 pm

very nice tutorial.

Reply
Brendan
10/17/2012 02:06:28 pm

Hey I've just started reading these today. Thankfully I know basic Java so I was able to start unit 2 right away. I like the way these tutorials actually start the game making process right off the bat instead of trying to sit the reader through 150+ pages of theory from a textbook.

For this section I had one problem trying to create a data folder within the package. I got it eventually but maybe this part should be clarified a bit more. Other than that the only problem I have with the tutorials is sometimes there is a lack of depth. If something isn't fully explained or I am told to copy and paste something it doesn't feel like learning. This hasn't happened too much though and it's understandable when you have to try and write out one or two tutorials a week.

Other than that I will try to keep up with these great tutorials until the end. I'd also like to know what games you guys are planning for the future? You have a 3D tutorial planned but no 3D games on the Market yet!

Reply
Albert L.
4/17/2013 03:33:29 am

"For this section I had one problem trying to create a data folder within the package. I got it eventually but maybe this part should be clarified a bit more."
Agreed.

"Other than that the only problem I have with the tutorials is sometimes there is a lack of depth. If something isn't fully explained or I am told to copy and paste something it doesn't feel like learning."

I have to disagree with you on this one. I think that some of these concepts are mote easily understood when the product is observed as a whole. So instead of trying to explain all of the defenitions and later trying to peice them all together, he first puts them into context and then explains the meaning of each part and what it does.

Reply
ale
10/17/2012 05:09:13 pm

I can't solve the image problem, the program runs, the console says: "Do not scroll the background.", but the red "robot" wont show up, if I move the message in te console changes, but it still wont show me the image :( how did you guys solved it?

The image is in KiloboltGame\src\data\character.png

Reply
nightmare6m
10/17/2012 08:31:35 pm

I had this problem as well. I eventually solved it by deleting the image from the data folder. Then opening eclipse, opening my desktop (where the png was orginally stored) and dragging the png to the data folder icon in eclipse. I am not sure why that worked while actually placing the image in the folder did not but maybe worth a try.

Reply
James C
10/17/2012 11:27:49 pm

Try rebuilding the project by going to Project > Clean. That should solve the issue.

mlorenz
11/23/2012 06:04:11 am

+1 for this. I tried everything else listed here and nothing, but nothing, worked. Dragging the image from another folder and dropping it into the data folder in Eclipse finally did the trick.

I don't know why this should matter, either.

driff
12/6/2012 11:23:59 am

u can also just right click the project and select refresh this happens because u are adding outside eclipse and it doesnt check what has changed from outside eclipse unless u close it and open it back again or u hit refresh

Hanashimaru
6/12/2013 09:08:09 am

Thank you! I tried everything else, but this was the one way to actually get it work! Thanks again!

XOLAROViCH link
4/11/2014 05:03:53 pm

Thnx nightmare6m. It worked for me.

truongnv
8/17/2015 03:44:14 pm

Thank you. It's runned. I only need Refresh project.

UAB-Student
1/23/2014 04:15:56 am

Actualy the right way to do this is change last line in the "init()" methode to:

// Image Setups
character = getImage(path, "../Data/robot.png");

adding the two points "../" indecates the previous folder, some versions of the operating system won't work without the "../"

Reply
ale
10/18/2012 04:15:51 am

still not loading the image :(

. drag and drop won't work, same problem
. project > clean, same problem

any other idea?

Reply
James C.
10/18/2012 04:54:51 am

Have you tried importing the finished source code I posted at the end?

Reply
Mike
1/17/2013 01:03:42 pm

This is a bit late but I was having the same issue with the image not showing. I fixed it by changing the line that reads:

base = getDocumentBase();
- to -
base = getCodeBase();

See: http://docs.oracle.com/javase/1.4.2/docs/api/java/applet/Applet.html

Hopefully this doesn't cause an issue later. :D

R4m80
1/24/2013 12:33:28 am

I even would recommend "getCodeBase()" because it returns the URL to the folder,
while "getDocumentBase()" returns the URL of a generated html-file in this folder.
however, it works both ways for me
(wanted to reply to Mike but didn't find a "Reply"-button :( )

ale
10/18/2012 06:07:31 am

well that solved it, apparently I was creating the wrong type of "data" folder.

is it ok that it doesn't move up?

ps. cool work with the style of the site :D
can't wait until tomorrow for next lesson :)

Reply
Sean
10/18/2012 09:02:29 am

I have the same problem as Ale although I can't fix it. What type of folder is it that you use to store the robot graphic?

Reply
James C
10/18/2012 09:08:42 am

It is just a regular folder you create by right clicking the Src folder and creating a New folder. Adding new files often causes problems so make sure you rebuild. If you cant figure it out, copy and paste your Two classes and email them to me :)

Jamescho7@Kilobolt.com

Reply
Sean
10/18/2012 10:05:32 pm

It's okay I've fixed it now! :D

Reply
ale
10/19/2012 02:59:31 pm

hello, the link to day 5 is not working :p

thanks for another aesome lesson! :D

Reply
Richie
10/25/2012 04:07:44 am

Hi there
got a question:
while handling y coordinates,
centerY += speedY;
if (centerY + speedY >= 382)
centerY = 382;
and
f (jumped == true) {
speedY += 1;

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

Why are we using if (centerY + speedY >= 382) {centerY = 382; } twice ? (the one before the boolean condition and the one after it)

Reply
James C.
10/25/2012 04:56:34 am

The first centerY = 382 is called when jumped is false.
The second is called when jumped is true.

Reply
Confused
4/2/2014 09:10:32 pm

How does the java know that SpeedX is dedicated for horizontal movement and SpeedY is dedicated for vertical movement?
Since both SpeedX and SpeedY are just int variables, how does java differentiate which variable is used for horizontal movement or vertical movement?
thanks in advance

Mario
8/3/2014 09:07:41 am

Hi Confused,
I am not quite sure, but if you check the paint method within the update method in StartingClass, the statement "g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);" is implicitly saying what are X coordinates and Y coordinates. The g.drawImage method has the parameters (image, x, y, observer).

Richie
10/25/2012 03:06:55 pm

Thank You!!

Reply
Hymosi
10/26/2012 01:13:14 am

Why the

public void update(Graphics g) method update automatically?

Reply
Bob
10/26/2012 01:45:21 pm

It's just a function of an applet

Reply
Alpha120_xda link
10/26/2012 06:45:12 am

Hello, I dont know if my app is working fine.
I nearly cant move the robot to the right, in console i see "Scroll the background", but I can move the robot to the left, out of the screen. Someting wrong with coords maybe? Also, jumping does not work.
Is there anything wrong or is it ok as of now?

Great tutorials, thank you for your hard work, James.

Reply
James C.
10/26/2012 12:57:04 pm

It sounds like some of your code is wrong. Try downloading the source code to see if there are any differences in those movement related methods.

And the "Scroll the background" is normal behavior. I included a video of Metal Slug, which incorporates such forward movement.

Reply
Alpha120_xda link
10/27/2012 11:54:17 am

Hi James, I solved the problem.
There was a pair of misplaced braces.
FIrstly, I replaced all my code by yours, in Robot.java.
I run it and jumping and moving worked.
I compared the two files, side by side in Notepad++ and noticed the misplaced braces.
Now Its working fine, jumping works and I cant go off the screen.
Thank you for your hard work.

abhyudaya srinet
10/30/2012 09:18:54 pm

i am not getting the character on my applet. i downloaded your file and cross checked everything but i cannot find anything.
your robot class had imported graphics which i had not so i did that but it shows a warning that it is an unused import plus i have a few warnings in my startingclass too. i have mailed you the two classes i made. please tell me the error.

love you work.. thank you for teaching everyone all of this so clearly and briefly.

Reply
abhyudaya srinet
10/31/2012 03:55:28 am

there two draw images.. one in update and the other in paint..
i get that paint will make the character at the coordinates by the arguments.. but how do the link together??

Reply
James C
10/31/2012 03:59:16 am

The statements in the update method simply create the double buffering effect that I briefly discussed, and the statements inside the paint method are what you are drawing literally to the screen (i.e. the robot).

They aren't technically "linked." They are called sequentially and automatically by the fact that these are runnable java applets.

Reply
DeathRage
11/4/2012 04:18:59 am

thanks alot for these great tutorials
please just add a summery at the end for long lessons like this one
and thanks again!

Reply
André
11/18/2012 01:32:44 am

I have a problem ... When I press the right arrow key the robot moves to the right, but when I press the left he doesn't move. If I change the value of speedX to a positive value he already moves with the left key. What is the problem?

Reply
Reece
11/18/2012 05:12:41 pm

I'm really impressed and happy with the progress made today. thank you so much. I agree with previous comments its so nice to get straight to it not after hundreds of textbook pages.
Thanks heaps!

Reply
zahire
5/11/2013 12:01:22 am

Woke up till 1 am? no wonder u are impressed and happy.

Reply
Ben
11/21/2012 09:40:41 am

Hi, setfocusable(true) doesnt seem to set the focus onto the applet. This is on a Mac. Any ideas?

Reply
Bogdan
11/21/2012 05:14:43 pm

Hi,
Your tutorial is really awesome!

I'd just like to point out something that I believe to be an inconsistence in the code:
// Updates Y Position
centerY += speedY;
if (centerY + speedY >= 382) {
centerY = 382;
}
Your intent is to limit centerY to 382, but you're doing it the wrong way. Let's say that centerY=370 and speedY=6. Is this case you add 6 and obtaint centerY=376, but then you check if 376+6>=382 which is true, and thus you instantly teleport the robot to 382.
The right way to do what you want it to simply add speedY and then check only if (centerY>=382), no need to add speedY again.
So correct code is:
// Updates Y Position
centerY += speedY;
if (centerY >= 382) {
centerY = 382;
}

or even:
// Updates Y Position
centerY += speedY;
centerY -= centerY-382; //deduct any extra

Hope this helps somehow. Thanks!

Reply
Bogdan
11/21/2012 05:17:53 pm

I've just noticed that my very last piece of code only works if you got over 382, so ignore it. Only my first solution is correct.

Thanks

Reply
James C.
11/21/2012 05:27:24 pm

Thanks for your comment!
Actually my intent is to prevent the centerY from going over 382 in the first place. Your solution corrects the position after it passes 382, which is fine until we incorporate deltaTime. Then the character will be jumping more significantly than it does with my current approach.

I do agree that my current approach is oversimplification that would cause the update to happen a tiny fraction of a second early, but for our purposes (we aren't developing a AAA title), it will work :)

James C.
11/21/2012 05:35:34 pm

if (centerY + speedY >= 382) {
centerY = 382;
}else{
centerY += speedY;
}


This probably works best. Changed the guide :) Thanks!

Bogdan
11/21/2012 07:09:31 pm

That makes sense. Thanks!

Eric
12/4/2012 12:43:11 pm

TO ALL THOSE WHO ARENT GETTING THE IMAGE STILL!

the getDocumentBase method, was only getting me to the bin folder. So when i got the image i had to include the path from the bin folder.
character = getImage(base, "kiloboltgame/data/character.png");
I am on a OSX 10.8

Reply
Boris
12/19/2012 11:17:10 pm

Thanks Eric! That did it.

Reply
R4m80
1/24/2013 12:41:54 am

You also can put the data folder to the bin folder. (hope this wont get any side effects later on, when we put such an applet on a phone)
getDocumentBase() and getCodeBase() got me to the bin folder as well on:
ubuntu 12.04 - java 1.6
ubuntu 12.04 - java 1.7
windows 7 - java 1.7
(didn't try any other OS-Java combination)

Reply
Johnyeo
12/17/2014 10:52:43 am

Thanks a lot! Really helpful.

Reply
G
12/22/2012 03:13:10 pm

Copy/pasting in: Private Robot robot;
I get an error.

Tooltip suggests I create a Class.

But if I change to: private Robot robot; (lower p private)
It works fine.

Nice site!

Reply
James C
12/22/2012 04:04:13 pm

Fixed. Thank you!

Reply
Eugene
12/29/2012 11:45:15 pm

Hi James!
At first, I would like to thank you for this great tutorial! :)
I've noticed a little issue, when I tested the game.
If I press left and then without a pause press right, I've noticed some lag in character's movement. It's a quite annoying. How we can fix it?
Thanks!

Reply
John
1/10/2013 06:29:13 am

I had the same problem and the way I fixed it was by first locating the keyReleased method and under case VK_RIGHT and VK_LEFT I removed the call to robot.stop();. Hope that helps.

Reply
John
1/10/2013 11:03:24 pm

Nevermind incorrect. Sorry

Humoud
12/31/2012 06:02:21 pm

Thnx man! i Really Really appreciate it. You have no idea how much this is helping me.

Reply
Anish
1/3/2013 12:51:26 pm

I have the same code as you in the Starting and Robot class but the image doesn't appear on the window when I run the program. What can be the problem

Reply
Anish
1/3/2013 01:20:25 pm

never mind, I had the picture saved in the wrong folder.

Reply
Chris B
1/8/2013 06:13:38 am

Hi James - firstly, great tutorial, thanks!
Secondly, I notice that the update() and paint() methods that are overridden in the StartingClass do not call .super(). The javadoc suggests that you have to do this to make sure the container gets painted/updated properly. Why do we not call them? I did try calling them, but it just made the robot image flicker (so I am sure you have a good reason for not calling them!!)

Cheers,
Chris

Reply
James C.
1/8/2013 06:15:50 am

Oh there is no reason. It just didn't seem necessary!

No need to worry about fixing what ain't broke ;)

Reply
Bruno
1/12/2013 10:14:57 am

For those of the people that aren't getting the robot image, make sure you are creating the data folder in src and not putting data inside the kiloboltgame package this is what happened to me haha

Reply
User
10/1/2013 11:26:48 am

After reading through a lot of comments, finally a solution

Reply
Another User link
6/29/2014 11:39:08 pm

I made the same mistake.... thank you

Reply
Sandeep Dhaga
1/16/2013 08:22:30 pm

Really amazing tutorials and the explanations are also crisp.
Thanks! My robot is moving left & right and jumping too!

Reply
Josh
1/18/2013 12:01:24 pm

If your robot image still isn't showing up after the suggestions above, try right clicking the data folder in eclipse and hit "Refresh", this worked for me

Reply
A.A.ron
1/23/2015 05:19:40 am

Perfect solution. I did everything before this and nothing worked. Thank you sooooo much!

Reply
Povilas
1/18/2013 09:52:38 pm

I was following this tutorial nad when i run the application i get the following error: Exception in thread "Thread-3" java.lang.NullPointerException
at kiloboltgame.StartingClass.run(StartingClass.java:58)
at java.lang.Thread.run(Unknown Source)

Any ideas about that?

Reply
Povilas
1/18/2013 09:58:22 pm

Also the robot sprite is not appearing until i change the size of the window

Reply
James C.
1/20/2013 08:37:28 am

Check your StartingClass with the example above.

Reply
Povilas
1/20/2013 10:50:24 pm

The fun thing is that my code is identical to the code in your project, yet when i run my code nothing shows up until i change the size of the window (good thing the error is now gone), but when i run your code it works perfectly

Povilas
1/20/2013 10:57:39 pm

Okay i found the problem - i missplaced one brace. Anyway thanks for the awesome tutorial

Daniel
2/9/2013 07:59:11 pm

I had the same problem, in my case it was related to the start method in starting class.
what i had :
@Override
public void start() {

Thread thread = new Thread(this);
thread.start();
robot = new Robot();

}

what it needs to be :
@Override
public void start() {
robot = new Robot();
Thread thread = new Thread(this);
thread.start();

}

Reply
Pipkin link
2/11/2013 11:13:28 pm

That was exactly my error. Thanks for helping!

Troy
3/28/2013 07:46:46 am

Thank you so much! His tutorial says put it below that >_o. That should be updated.

Paula
10/9/2013 10:53:37 pm

Thanks a lot! I couldn't figure it out!

Jesus
3/9/2014 04:08:28 pm

Thank you, I had the same error. I didnt know what was wrong with my code

Miss Wise
7/3/2014 04:14:53 am

Thank you for solving that!

Tim
3/30/2016 07:57:20 pm

Thanks. It would have taken me forever to realize that mistake.

Gman
1/25/2013 08:05:11 am

Ok, was the most frustrating thing in the entire world!!!!! My robot image would not show up either, and i was raging super hard when none of the fixes worked. I finally said screw it, and downloaded the source from the tutorial. Upon inspection I noticed his data folder was INSIDE his "src" folder. The whole time i had been creating new source folders, that would not go into the src folder! You do not! i repeat DO NOT want a SOURCE FOLDER! You want just a plain old normal folder. The reason this is so deceiving is because when you right click, it does not give you the option to create a normal folder. Simply just click other, then search for folder. Select the normal folder not source, and create it. Then drag and drop the image in! Note:the folder the character.png goes into, is a white box, not a brown or yellow one. Other than that extreme frustration i'm loving these tuts!

Reply
Gnome
7/5/2013 12:32:32 am

This totally worked to fix it for me. Thanks a ton

Reply
John
1/29/2013 12:34:40 am

The image problem is basically making sure your source file is were it belongs.
It needs to be placed within the bin, into the the file (Whatever name you picked). there you will find the code headers you created to date.
So if you used (Kilobolt), that would be the file that resides in the bin.
Go into the Kilobolt file and place the data file, that simple.
Great tutorials, defiantly will contribute to the site.

Reply
Martin link
2/10/2013 03:59:19 am

Hey thank you so much for the lessons... a great help to a n00b such as myself :-)

I only have one issue from here... working fine as of the end of this lesson, however when moving left or jumping (or moving in general) although the Q-Bot is moving fine... there is an extra pair of legs in the original position that remain... (the moving Q-Bot is not missing his legs...)

Have run the clean thingy and double checked all code... can't quite see what i've done wrong... any ideas?

Reply
Scott
2/18/2014 08:03:58 am

I am having a similar issue. First, when the window opens, it does not fully open to show the whole robot. As I make the window big enough to see the whole robot, when he jumps one pair of legs stay at the original position, but when he jumps he is whole. Finally, when I move him left or right, the top part of him moves. It is as if the lower section of him is behind the background. I have gone through my code line by line with the sample code and cannot find a difference. I hesitate to import the correct code as then I don't find my own error. Any help would be great. Thank you.

Reply
Michael
6/26/2014 02:28:40 pm

Did you end up finding a solution to this?

IvanL
2/11/2013 08:36:53 am

This day 4 is a lot harder compared with the previous, at least for me since I'm totally new to programming :(. I can't understand a lot of things, hope they are somewhat explained later. How the program can work without a main method? What are the "g" of Graphics and the "e" of Keyevents? What's the mean of "this"? How to know when is better to use "public" or "private"? And what's the point of use "private" if you are going to need getters later?

Reply
James C.
2/14/2013 03:32:51 am

Ivan,

"g" is just a Graphics object and "e" is just the variable that we can use to refer to as the current key press.

Graphics g appears when the update/paint methods are called. These are called by the applet (automatically), which passes in a Graphics object by default. We just call this object g and use it to draw to the screen.

"this" usually refers to the current class or the object that calls a method.

If you were to say:
g.drawImage();

"this" would refer to "g" inside the drawImage() method.

The reason we use private is to ensure that we do not have any methods mistakenly changing the values of the private variables. It's just a safety line that prevents us from doing damage to our game.

I hope that clears things up!

Reply
Jafar
8/8/2013 01:21:34 am

Could you please elaborate about the image and second variables.
I just can't really understand how the images are drawn on the screen and when.

Thank you for the great tutorial!

newbie
2/12/2013 02:12:20 pm

Hi I just want to know why you call setColor() twice when you do the double buffering. I tried commenting out the first setColor() and the output is the same.

Reply
James C.
2/14/2013 03:24:05 am

Depending on the situation, commenting that first one out may or may not cause issues. This is a universal solution.

Reply
Tumble
2/14/2013 06:54:08 am

Thanks for a great tutorial, im halfway through day 4.
Ive added getters and setters in the robot class but im still getting errors on the gets in the startingClass. Ive got to the bit where you output it to the applet, all works ok. will the errors go as i progress or have i missed something?

Thanks again

Tom

Reply
Tumble
2/14/2013 06:57:39 am

all sorted after a second clean. what a tool! cant wait to crack on with this tomorrow!

Reply
Weathers
2/21/2013 07:04:33 pm

Hey James thanks so much for the tutorial! Hey i'm having a little of a problem when i run the program the applet thats displayed is resizable and when it loads i only see half of the robot i have to resize the window to see the whole robot. Any ideas why this is?

Reply
James C.
2/21/2013 10:15:14 pm

Not sure what is happening. Email me your code at jamescho7@kilobolt.com.

Reply
ken
2/25/2013 02:32:17 am

hello
thank u for your effort
i have question
in this code
if (jumped == true) {
speedY += 1; //While the character is in the air, add 1 to his speedY.
//NOTE: This will bring the character downwards!

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

}

this code if (jumped == true)
speedY += 1;

i think we have to use while loop instead of if
so we can make this statement (centerY + speedY >= 382) true

so could u plz explain why we use if not while loop
thanks

Reply
rtt
2/25/2013 02:37:06 am

hi
speedY = 1;
why it is not speedY = 0;
thank you

Reply
Sean
2/27/2013 02:16:05 am

A positive value for speedY is the speed at which your robot is falling. If you set it at a negative, it will float up at that speed. With that said, change the value from 1 to 0 and jump a bunch. Now change it back. You will notice the speed difference.

Reply
Confused
4/2/2014 09:04:42 pm

How does the java know that SpeedX is dedicated for horizontal movement and SpeedY is dedicated for vertical movement?
Since both SpeedX and SpeedY are just int variables, how does java differentiate which variable is used for horizontal movement or vertical movement?
thanks in advance

Matt
2/25/2013 09:53:35 pm

Hi, Java newbie here,
I have tried a bunch of different fixes and looked through all of the comments, but i cannot for the life of me get my .png image to show up in the applet. The applet itself loads, and also post message in the console(like "move up" when you press up etc.), but the image does not show up. If anyone could help it would be greatly appreciated!
-Matt

Reply
James C.
2/27/2013 12:12:41 am

Matt,

Export and send me your project (jamescho7@kilobolt.com). I will look into it for you.

Reply
sean
2/26/2013 08:26:12 am

So I was having a nightmare of a time figuring out why my robot would not move; the key presses was being reported in console but the robot would simply not move. I commented the entire file out and pasted yours in and it worked so I knew it was doing on my part.

I found the culprit:

public void start() {


Thread thread = new Thread(this);
thread.start();

robot = new Robot();

}

Can you explain to me why robot = new Robot(); has to be above the thread creation and not below it? I followed your directions and it somehow had me placing it where it was below and if below it seems the robot will not move; no matter how many times I sigh at it and ask it to kindly move :)

On a side note, you show, during the getters and setters portion a total of 14 but when I ran it, only 10 displayed. Did I miss something or has the code changed since you took the screenshot? Also, can you elaborate more on why and how getters and setters work? Why not simply set something as public if you are going to be passing information from class to class? And does using Eclipse to auto-generate these detract from us understanding how and why they work?

Lots of beginner questions, I know...but it's better to understand how things work rather than simply assuming they will always function as intended. :)

Reply
Djiango
3/10/2013 09:35:21 pm

Thank you so much. My robot wouldn't move like yours, but your advice seemed to work!

Reply
Bruce Lindman
2/11/2014 12:13:14 am

Ah! Thank you for finding that error, I had the same one, and I can explain it simply. Once the thread starts, the program focuses only on what is happening inside the thread, not leaving it until the thread ends. If the robot is defined after the thread starts, the program never reaches it's definition (until after the game thread has completely ended), leaving it as a null variable.

Reply
jose
2/26/2013 02:36:01 pm

help me!! I am not getting
@Override
public void update(Graphics g)

or public void paint(Graphics g)

Reply
Martin Clement
7/12/2014 06:14:44 am

Ok jose! I had the exact problem following the tutorial. Sorry for being here a year late =). My solution to this was to download the package and compare. I realized in the end that I had to a "}" at the top of the
(Graphics g) method, * before the actual method. It appears that Eclipse identified the problem as a missing variable, or whatever. Let me know if that worked. Btw, you may have to delete a "}" after adding the one on top. Mess around until the error indicator is gone. Also save so you do forget that the problem was fixed, *if fixed.

Reply
tom link
3/6/2013 08:15:12 am

I had all kinds of trouble with getting the robot image to appear, but fixed it after a lot of frustration. Since this is such a common topic I would do something to clarify the tutorial in case people don't read through the comments - it is such a great tutorial you don't want people giving it up because of this.

In my case I had created the folder and moved the image into it entirely outside of eclipse -- ultimately I changed the code to:

try {
// base = getDocumentBase();
base = getCodeBase();
} catch (Exception e) {
// TODO: handle exception
}

// Image Setups
System.out.println("Base: " + base );

character = getImage(base, "../src/data/character.png");

Reply
Will
3/7/2013 01:48:56 am

I did this but the Robot only appears (flickers) as I resize the window.

I can't see the robot when not actively resizing the window.

I have tried both JavaSE-1.6 and 1.7, I've double and triple checked my code, every thing looks as it should.

Reply
Will
3/7/2013 03:25:34 am

Turns out I had missed "paint(second);" in the update(graphics g) method.

Kieran
3/12/2013 11:23:49 am

I did everything you said but still get errors on getCenterX and Y. I started over and did it again, but still the same errors.

Reply
Erv
3/27/2013 04:24:09 pm

Same thing happened to me, I just wanna solve it already so I can move on lol

Reply
Bob Dole
6/5/2013 03:10:34 pm

I had the same problem. I just renamed centerX and centerY to CenterX/CenterY and it resolved it. I'm guessing that was the problem. Is it required that we capitalize the second word in names like that? As in getCenterX as opposed to getcenterX

JC
6/6/2013 09:22:28 am

The convention is to use camelCase but it is not a requirement.

Bob Dole
6/6/2013 12:13:06 pm

Thanks, was never sure. I think my changing centerX to CenterX wasn't legal. I don't know why it was giving me those errors but whatever autocorrect eclipse suggested when you mouse over it fixed it, though it didn't look like it changed any text.

Sorin
3/16/2013 09:41:12 pm

Hey, I made all you said in the tutorial, but sometimes it works, and sometimes not. It gives me this error :
Exception in thread "Thread-3" java.lang.NullPointerException
at busdriver.StartingClass.run(StartingClass.java:59)
at java.lang.Thread.run(Unknown Source)

Can someone please help me?

Reply
aliaksei
4/3/2013 04:26:41 am

Hi amazing tutorials, thanks for spending your time on these;

I get an error on the line:
robot = new Robot();
It says "Unhandled exception type AWTException"
It suggests surrounding it with a try/catch, I have declared "private Robot robot", and tried cleaning the project multiple times

Reply
Gary
4/6/2013 03:38:43 am

Thank you so much for this, it is excellent work. I intend to go through this with my 10 year old son so he can learn programming (i dont hink 10 is too young) and then use his imagination in the future to create a game which will make us rich! :-)

Reply
Michael
4/13/2013 03:04:15 am

So i read and write down the code as you go and everything. i actually am learning and thank you for that. But whenever i click the run it will just spam my console with "Do not scroll the background." after that i just decided to copy in your code and the same thing happened. I dont know why it does this. I am on a mac, if your wondering what computer I use.

Reply
James
4/21/2013 12:14:50 pm

Mike, if I remember correctly, that is the right behavior.

Reply
Shane
4/19/2013 03:27:55 am

I could not for the life of me figure out how to get the png's to appear using your method. I put the images in every possible folder. I ended up loading the images using a different approach.

ex: background = new ImageIcon("src/data/background.png").getImage();

Is that method any worse to use that the one you had?

Reply
James C.
4/21/2013 12:14:11 pm

It should be fine. I am sorry it did not work for you (and many others). I will revisit this section in a few weeks and make sure I have multiple ways outlined.

Reply
Mike
4/22/2013 10:36:04 am

No ya i figured it out eventually, dont know what was wrong but i just reinput the source code and it just happened to work, will reread this section though.

nelzkie
4/27/2013 06:24:10 pm

I am using Intellij and i cant make the image to show? i tried to make it ../data/character.png still not working.. black screen

Reply
Lamar
8/15/2013 03:01:44 pm

I'm using Intellij also. you haven't found a solution I found that, for me, Intellij reads from the /tmp directory. So I just moved my data folder there and it all worked. I don't know how to tell it to read and write to the projects directory.

Reply
Richard Burns
4/28/2013 01:08:12 am

Would the code learned in this tutorial series help me if I was to make a game with AndEngine?

Reply
Jerzku
4/28/2013 03:06:04 am

Hey. Just wondering will you be telling us how to use small standby animation or does it work just by importing .gif file? Probaply would found tutorials for that but though of asking you first :) Great tutorials btw.

Reply
Priya
5/8/2013 03:17:00 am

Hi James the site is really wonderful & very helpful.
I am facing problem in loading images I have read previous discussions but still am facing same issue. can u help me in sorting out this problem plz?

Reply
Supriya
5/10/2013 04:19:24 pm

In my case image worked when i placed image in folder "bin/data" as "bin/data/character.png"

Reply
Esteban
5/9/2013 06:30:06 am

Hi,
im having trouble with my Getter and setter.. I do as the tutorial says but i get a message saying "the opreation is not applicable to the current selection. Select a fiels which is not
declared as type variable or a type that declaes such fields." Any ideas??

Reply
sameer
5/15/2013 04:44:03 pm

HI,
// Moves Character or Scrolls Background accordingly.
if (speedX < 0) {
centerX += speedX;
} else if (speedX == 0) {
System.out.println("Do not scroll the background.");

} else {
if (centerX <= 150) {
centerX += speedX;
} else {
System.out.println("Scroll Background Here");
}
}

// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{
centerY += speedY;
}

// Handles Jumping
if (jumped == true) {
speedY += 1;

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}

}
Could u explain these codes in a simple way pls, why we are checking SpeedX<0 and centerX<=150

Reply
sameer
5/16/2013 07:35:44 pm

No probs i understood

Reply
javad
5/18/2013 06:07:39 pm

Thanks a lot!! Very useful!
I will read all of your tutorials...

Reply
shree
5/21/2013 04:01:34 pm

there is a mistake in the code
// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{
centerY += speedY; // it does'nt work here..robot does'nt move
}

however it is correct in the code you have given to download
// Updates Y Position
centerY += speedY;
if (centerY + speedY >= 382) {
centerY = 382;
}
However the tutorial is amazing. Very good job.. learnt a lot from it.Thanks.

Reply
shree
5/21/2013 04:31:16 pm

there is a mistake in the code
// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{
centerY += speedY; // it does'nt work here..robot does'nt move
}

however it is correct in the code you have given to download
// Updates Y Position
centerY += speedY;
if (centerY + speedY >= 382) {
centerY = 382;
}
However the tutorial is amazing. Very good job.. learnt a lot from it.Thanks.

Reply
Kevin
5/23/2013 05:21:28 am

I'm not getting any errors, however the image is not being display. The character.png file is in the workspace\KiloboltGame\src\data folder. Neither of these statements work.

character = getImage(base, "data/character.png");
character = getImage(base, "../data/character.png");

Thank you.

Reply
Kevin
5/23/2013 05:50:02 am

Fixed.

Reply
Bartlee Anderson
6/2/2013 09:47:16 am

For NetBeans, you need to prefix the path with classes, i.e.

in init
character = getImage(base, "classes/data/character.png");

Reply
Justin T.
6/16/2013 04:00:02 pm

Oh man thanks so much for this

Reply
Louis N
6/7/2013 06:55:42 pm

As per your suggestion in Lesson 8, I started reading the code through in the order it would execute. Something from this lesson has me confused though, so I figured I'd make my comment here.

In the Robot class, we declare and initialize speedY to 1. Later, in the // Handles Jumping section, after checking if the robot is done jumping, we set speedY to 0. Concerned about the inconsistency between the speedY setting, I tried changing the initialization of speedY to a much higher number, as well as trying to set the setting of speedY in the // Handles Jumping section to a much higher number. I found that no matter what I set them to, the robot's jumps aren't affected in any way (as long as I don't set them to a negative value, in which case the robot starts flying).

So that begs the question, why do we set speedY to 0 at one point, and to 1 at another. I can see that it doesn't matter what we set it to as long as it's not a negative value, but shouldn't we keep the number consistent?

Reply
Akshay
6/19/2013 03:45:41 am

Only a black window appears with Q bot alpha written on the title bar.. png is not loading.. pls help..

Reply
Ilias
6/23/2013 09:38:40 pm

I still cant load the image? I tried everything what people said in the comments but it still won't work? Help please!

Reply
Ian
6/24/2013 10:09:07 am

James, just wanted to say this is a great tutorial and I am really enjoying getting to grips with game programming. Had a little bit of trouble with the png as some have also had but I solved that. Can't wait to carry on with Unit 2!

Reply
Ian
7/3/2013 04:29:24 am

There are 2 data folders in my file system. The images seem to need to be in bin\data. Whenever I clean up the project it seems to remove the PNGs from this data folder not the other. I'm not sure why this is but I am now avoiding the clean up. If you are having display problems check your bin\data folder and make sure all the images are there.

Reply
Tyler
6/27/2013 08:11:15 pm

My character.png does not appear when running the program. I have tried every suggestion in this thread, but to no avail. At this point, I'm assuming it's an IDE issue. I am using IntelliJ. You wouldn't happen to have an idea as to what would cause this would you?

Reply
Lamar
8/15/2013 02:38:27 pm

I'm having the same problems in Intellij. Has anyone been able to solve this yet? my getCodeBase and getDocumentBase always points my /tmp directory.

Reply
Lamar
8/15/2013 03:02:45 pm

I solved it after writing the last reply. I found that, for me, Intellij reads from the /tmp directory. So I just moved my data folder there and it all worked. I don't know how to tell it to read and write to the projects directory.

Reply
Eugene
8/26/2013 01:58:38 pm

I tried everything I could but I couldn't get anything to work, even after downloading the source code. I noticed that the path in the source code was /data/character.png". Make sure that the path does NOT have the leading slash. Instead, it should be: "data/character.png". d

Reply
Andy
2/11/2014 02:37:52 pm

I got the image to appear by changing the path to "../src/data/character.png"

Reply
Dav
11/29/2014 11:01:58 pm

works for me Andy....

Juan
7/2/2013 07:00:37 pm

I've been following this tutorial with NetBeans. I'm currently stuck here since I haven't been able to make the Robot appear. I've tried using the downloadable code but it still doesn't appear. I've tried adding classes in the string url but it still doesn't appear. Please help!

Reply
Colby
7/3/2013 03:34:05 am

I had a similar issue. All I did was go to the Package Explorer and refreshed the KiloBoltGame package. The Robot started to appear. Hope this helps!

Reply
Juan
7/3/2013 02:59:11 pm

I think its called something else. Package Explorer is for Eclipse. But no, it also doesn't work...

Eugene
8/26/2013 01:57:59 pm

I tried everything I could but I couldn't get anything to work, even after downloading the source code. I noticed that the path in the source code was /data/character.png". Make sure that the path does NOT have the leading slash. Instead, it should be: "data/character.png".

Reply
Malcolm
7/7/2013 10:16:54 am

Absolutely love the tutorials! At first I couldnt get the little man to be displayed but then I saw that the png needs to be in the bin directory not the src. Keep up the awesome work!

Reply
Ryan
7/9/2013 01:18:19 am

I've had loads of problems with the character loading and i've figured out why. It seems like the update method in the robot class that was originally posted in the beginning is different then what's in the source so go back and check that out and fix it then your robot should load up.

Reply
Ryan
7/9/2013 01:20:10 am

never mind guess it was me that just miss typed sorry about the inconvenience. Great tutorials :)

Reply
Mitz
7/9/2013 11:15:54 am

Hi!
I'm currently working with an Android game. Luckily I saw this tutorials and they're great! I've been following this for some weeks now.

I have one error, the java.awt.graphics . It says that "the java.awt.graphics cannot be resolved". Do you have any idea on how to fix this?

Thank you. Keep up your work!

Reply
jba
7/8/2014 09:50:51 am

I had the same problem. You must have put the update and paint methods inside run(). put them after run and it should be fine

Reply
ozgur
7/24/2013 09:40:41 pm

if you get error th show character.png change this code lines like this.
try {
base=this.getClass() .getResource("/data/character.png");
}
catch (Exception e)
{
//TODO
}

character =getImage(base);

Reply
wire64
1/15/2015 09:56:42 am

thks much, ozgur--I'm using netbeans 7.4--putting your code change in, finally made the robot show--good job

Reply
Irmis
2/28/2016 05:35:10 am

Thank you, been trying to make my robot appear on the screen for few hours now and this worked!!! Thank you

Reply
Nanashi
7/25/2013 05:53:50 pm

When pressed jump, the character's centerX becomes 382 + (-15) which is 367.
Shouldn't the character appear in the peak of its jump when jumped?
How are we getting this smooth motion when jumping up?

Reply
Richard
4/2/2014 05:13:32 am

I've been scratching my head all day wondering the same thing!

Reply
Ricahrd
4/2/2014 05:25:47 am

I figured it out as soon as I wrote this. It's because -15 is the vertical speed of his jump NOT his max jump height (what I initially though). So every update he speed is getting adjusted by +1 (i.e. -15, -14, -13, ... -2, -1, 0, 1, 2, ... 13, 14, 15) until he hits ground then jump is turned set to false.

Reply
Vaibhav
1/13/2015 05:20:05 pm

Thanks for the explaination dude!
Even i was scratching head for it for the whole day.
So i put it in debug mode, printed the changing value of speedY and understood the logic with the help of your explaination.
and Thanks alot James for all the effort you have put in creating this and making it easier to make us understand. Will share it with friends, keep clicking on ad sense and donate some amount. I think thats how the open source community will get motivated and share things.

Jonathan
7/27/2013 06:32:37 am

For people that cant get the robot to appear, check under your data folder and see what the character image is actually named. according to the source code it should be character.png but mine was named character[1].png so I had to change the code to "data/character[1].png
Also I need help, my robot will not move very far to the right, its like he only has access to a 1/4 of the screen. copied the source code and same problem?

Reply
Jonathan
7/27/2013 10:24:15 am

Disregard the robot not moving to right problem, everything is working as it should. Thanks a ton for the Tutorial!

Reply
Mike link
7/31/2013 03:06:52 pm

Why dont we put "don't scroll the background" when centerX <= 150 (that is, when the robot goes left) and we only don't scroll the background only when speed = 0 ?

Considering the metal slug video above, whenever he stops the background doesnt scroll, but when the character goes left the background doesnt scroll too right?

I find it's a bit inconsistent

Reply
Eshrath
8/1/2013 04:37:22 pm

Hi...!!
i tired your tutorial it showing following error in console..
Exception in thread "Thread-4" java.lang.NullPointerException
at sifu.eshrath.StartingClass.run(StartingClass.java:59)
at java.lang.Thread.run(Thread.java:619)

so please help me..
As per my knowledge i think update method is not working...

Reply
Tom link
8/10/2013 05:11:51 pm

Let's clean up that update() method. It's entirely too confusing.

//moves the character.
public void update() {
// Moves Character.
centerX += speedX;
centerY += speedY;

//prevents going beyond x coordinate of 150.
if (centerX > 150) {
centerX = 150;
/*
* Code to scroll background here. The Robot should NOT be scrolling the background!
* The Robot and the Background should not need to know anything about one another to
* perform their functions. I suggest a GameManager Object to handle the movement of
* the Robot and the Background in relation to one another.
*/
System.out.println("Scrolling the backgound.");
} else {
//do not scroll the background.
System.out.println("Not scrolling the background.");
}

// Prevents going beyond X coordinate of 0
if (centerX <= 10) {
centerX = 10;
}

// Updates Y Position
if (centerY > 352) {
centerY = 352;
speedY = 0;
jumped = false;
}

// Handles Jumping
if (jumped == true) {
speedY += 1;
}
}

Reply
pranaykarani
4/2/2014 08:55:06 pm

How does the java know that SpeedX is dedicated for horizontal movement and SpeedY is dedicated for vertical movement?
Since both SpeedX and SpeedY are just int variables, how does java differentiate which variable is used for horizontal movement or vertical movement?
thanks in advance

Reply
pro grammar
5/16/2014 08:25:36 pm

It doesn't. You do. SpeedX is for horizontal movement only as long as you use it that way.

daniel
8/11/2013 06:44:52 am

How do I get the robot move slower? even slower than if I put movespeed=1

Reply
pranaykarani
4/2/2014 08:52:56 pm

thats easy, declare SpeedX as float and put...
float SpeedX = 0.00001;

Reply
Peter
8/16/2013 07:26:52 am

I have a question, sorry if i sound noob on asking it lol. Thought the code works perfectly (thank you a lot, just came in this site for the first time and i must say that i love it congratulations excelent tutorials), i have a doubt. When you click the space bar, you "call" the jump method inside the Robot.java, wich adds 15 to the speedY, and sets jumped to true. Then we have the part that handles virtual gravity, which when jumped is true, subtracts 15 to the speedY. My question is, as the jumped variable is setted to true as soon as the speedY is changed, and that one should be reseted once the jumped variable sets to true, why is it that the speedY variable is not reseted as soon as setted, making it almost instantanly go back to the defaul and preventing te robot from updating and going up in the next loop? sorry if needed ill explain myself better. ty

Reply
Oblivious
8/21/2013 05:50:05 am

I don't understand how the robot appears to be jumping slow either.

Reply
Vaibhav
1/13/2015 05:26:08 pm

Please check for "Ricahrd" explaination above, also i have posted some information on it.
You will understand how it appears to be jumping slowly and then coming back slowly.
For hint the value of speedY changes from -15,-14,-13,-12 and so on to +14 i think. so the coordinates keeps changing and hence it appears jumping slowly with this logic

centerY += speedY;

if (centerY + speedY >= GROUND) {
centerY = GROUND;
}

// Handles Jumping
if (jumped == true) {
speedY += 1;

if (centerY + speedY >= GROUND) {
centerY = GROUND;
speedY = 0;
jumped = false;
}

}

DarylZero
8/21/2013 07:35:09 pm

I had a problem with the image, too.
Tried all the fixes - did not work.
Then I did the following:
base = getCodeBase();
System.out.println(base);
base = getDocumentBase();
System.out.println(base);
After that I realized I copied the file in the /projectname/src/data folder instead of /projectname/bin/data folder :)
changed the file location, everything was peachy.

As for jumping - you might want to try simple physics equation for movement ( starting from s = s0 + v0*t + 0.5*a*t^2; v = v0*t + a*t ).
I did so in a project I am working in as a game designer - a negative acceleration (a) added to jump/fall movement makes it smoother and actually better. If you find that difficult, try any sin/cos function, it does practically the same.

Reply
Griffiin Jarmin
1/9/2014 10:47:17 am

thank you

Reply
WV
3/7/2014 05:12:20 pm

How did you change the file location? Bin folder is invisible to me.

Erick
8/31/2013 10:10:30 pm

Under Linux (Ubuntu 12.04 LTS) I couldn't get this to work as posted. The window would become unresponsive. After some debugging, I traced the problem to the run() method. Commenting out the while loop resulted in the Robot being drawn once, but obviously no animation was happening.

Based on the code here: http://www.javapractices.com/topic/TopicAction.do?Id=153

I changed the moved the loop to a new private class and got it to work.

This is how my code looks like:

public class StartingClass extends Applet implements KeyListener {

.
.
.

public void start() {
robot = new Robot();
Thread thread = new Thread( new Worker());
thread.start();
}

private final class Worker implements Runnable {

@Override
public void run() {
while (true) {
repaint();
robot.update();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

Reply
Oli
9/8/2013 04:58:04 am

No matter what I do I can't get the robot to move. When I press up and down, it appears in the console but when I press left and right, the robot doesn't move and nothing about the background is displayed in the console as it should. I have checked both classes against the source files and there is no difference :s

Reply
Mike
10/25/2016 02:07:16 pm

My robot would not move until I noticed I forgot to out 'this' in the brackets:
Thread thread = new Thread(this);

Reply
Thomas
9/14/2013 11:50:55 pm

Just question - Isn't better to have public variables without getters and setters? If there are two methods for each variable, it mess the code pretty much and it does the same as a public variable.

Reply
John
9/18/2013 08:29:50 pm

why is it centerx+= speeds

Reply
John
9/18/2013 10:20:45 pm

hey its me again could u explain me why we have to put the above code and explanation and my name is really not John i just dont want to reveal my name.

Reply
allan
3/5/2014 07:55:50 pm

that would be because of
centerX += speedX is just a shorter version of
centerX = centerX + speedX.

centerX is the center of our character. speedX is the speed in which our character moves (6 / -6). in order to actually make our character move, we have to assign new coordinates to centerX. We do that by adding speedX value to centerX.

Reply
Saurabh
10/9/2013 03:33:13 pm

I have a question here.
Why are we defining the
================================
Thread thread = new Thread(this);
robot = new Robot();
thread.start();
================================
in start method ?
If we put this same code in init() it still does the purpose ?
I may be wrong here but just want to know why.
Again re-iterating... the tutorials ROCK!!! :-)

Reply
Christopher Wolff
10/24/2013 04:31:57 pm

Hello sir,

I think its because we only want to create a new instance of the robot when our game thread starts. That's why it is in the start() method. If we put new Robot() in our init() method the robot will be created before the game starts.

Reply
Dushyant
10/10/2013 03:48:29 am

First of all, great tutorials.
I am facing a problem with the movement of the robot character.When I press left or right,only a part of the image moves,the rest of the image part remains still and then when i resize the applet window the remaining part joins the moving part.Please help!
Thanks in advance.

Reply
GMan
10/10/2013 03:44:15 pm

Awesome tutorials, man, they're really well done!

A concern I have after this less, however:

I'm a total newbie to programming, just started to try and learn Java maybe a week and a half ago.

In Unit 1 I was able to follow along really well, fully understand what was going, and even take the stuff learned in each lesson and make my own little programs to test my understanding etc.

But after this lesson I just feel lost.. like I can't even comprehend ever being able to take the stuff done today and apply it independently to a program of own. I feel like I was splashing in the kiddy pool and now i've tried to jump in the deep end of the pool haha.

I mean, if I really look at each piece and put my mind to it I understand what's going on basically, but in terms of following it through the big-picture and all the nuances you seem to have to know to get everything to work, it seems so complicated.

I guess what I'm wondering is, after going through Unit 1 and the first few lessons of this Unit should I be able to understand this with ease, or do I need to come back when I have more experience with the fundamentals?

Thanks again for all your hard work!

Reply
ginsengjin
2/28/2014 02:40:50 am

I have this exact problem. I understand the code in parts but I don't understand how everything connects to one another as a whole.

Reply
sumit
10/23/2013 06:00:56 pm

how to create our own robot...???

Reply
pranaykarani
4/2/2014 08:45:38 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
pranaykarani
4/2/2014 08:45:47 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
pranaykarani
4/2/2014 08:46:00 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
pranaykarani
4/2/2014 08:46:14 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
pranaykarani
4/2/2014 08:46:30 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
pranaykarani
4/2/2014 08:46:38 pm

what do you mean by "our own robot"?
do you mean your own robot image or YourOwnRobot class with YourOwnRobot_speedX , YourOwnRobot_speedY..etc.
plese be clear..

Reply
sumit
10/23/2013 06:02:48 pm

plz help guys.....

Reply
Christopher Wolff
10/24/2013 04:28:59 pm

Hey everyone,

Not sure if this has been answered already, but isn't our window already automatically double buffered with the latest version of Java? If so then we wouldn't need an update() method for our Applet correct? Or has automatic double buffering only been added for JFrame?

Reply
Christopher Wolff
10/24/2013 04:34:15 pm

Also, is there a reason that we use Applet rather than JApplet?

Reply
John Ellis
10/27/2013 06:37:49 pm

Don't know if my question will ever be answered but I've got a strange problem. Input seems to read in but my robot will not move at all UNTIL I use the applets drop down menu and hit restart. After the applet restarts he controls just fine. Any idea why that might be?

Reply
Bruce Lindman
2/11/2014 12:08:50 am

Great tutorial, but I am also getting this issue. I did replace the robot class with my own class called biker, and the robot image with an image of a bike, but the only changes are to the names, and I made sure they were consistent.

I'm also getting a null pointer exception at the biker.update(); method when the game runs. It does not seem to throw the error on restart though.

Reply
Mark0h
10/3/2014 01:54:01 am

Hi John,
I know this is late, but I had this same issue. I then ran into an issue where my background would not scroll in the next lesson.

I noticed I was getting a Thread-3 nullPointerException error on my first start. I found the following solution for that, and it fixed the "restart" issue, my scroll issue, AND my thread-3 issue!

I move the following from the start() method in StartingClass.java, to the end of the init() method instead:


bg1 = new Background(0,0);
bg2 = new Background(2160,0);

robot = new Robot();

Reply
Michael J
11/9/2013 05:19:28 pm

Great series thus far! I have alot of experience with GML and use a very similar syntax to Java/c# as I code with it. Moving to Java seems to be a breeze since I have experience in c# as well.

However, I have hit a snag. My code looks exactly like yours but I am getting an error before I can even launch the game:

public void moveRight()
public vod moveLeft()
public void stop()

All of those are giving me syntax errors on void, expected @ token.

public void () is throwing EnumBody errors.

Any ideas?

copy/pasted from my IDE
public void moveRight()
{
speedX = 6;
}

public void moveLeft()
{
speedX = -6;
}

public void stop()
{
speedX = 0;
}

public void jump()
{
if(jumped == false)
{
speedY = -15;
jumped = true;
}
}

Forgive my C#/C++ way of formatting. I cannot get used to the javascript/Java way of formatting.

Reply
pradeep
11/12/2013 11:12:31 pm

When i press space
Please explain why "y-axis" decreases 10 , decreases 9, decreases 8 and so on.....

Reply
Claudiu
12/1/2013 07:41:17 am

I want to know this too. if it goes up he will not suposed to be pozitiv value?

Reply
minh
11/29/2013 07:14:51 pm

hi guys,

I tried to run the program by creating a new class with main().
public class Main {

public static void main(String[] args) {
System.out.println("******************");
System.out.println("Q-bot starting....");
StartingClass ss = new StartingClass();
ss.init();
}
}

I got a null pointer exception inside StartingClass right at:
Frame frame = (Frame) this.getParent().getParent();

Any idea how it happened? Thanks in advance

Reply
Albert
12/5/2013 12:13:53 pm

When I tried to run my project in the applet it says <project root>[in Game] does not exist
Game is my java project if anyone could help me it would be great i am new to programing

Reply
gaebolgone
12/5/2013 04:35:44 pm

Thanks so much fo this GREAT TUTORIAL !!!
So far, i can understand and implement it (i thinks because i have a little exp. on java :p )
i want to ask,
how to insert image in every moving method???
i mean, i want to insert image a character face right when he move right, face left when he move left, jump pose image when he jump.
can anyone tell me how to do it ??
(sorry if the aswer of my question actually have in this website somewhere, but I am very curious! )

Reply
pranaykarani
4/2/2014 08:37:50 pm

How I did this:
first you should have 3 images in your assets(excluding jumping)...
1. default.png(when your character is not moving or jumping)
2. movinright.png
3. movingleft.png

----------FOR MOVING RIGHT IMAGE----
1. go under "case keyEvent.VK_RIGHT:" in method "public void keyPressed".
add-" robot = getImage(base,"data/movingright.png"); " above "robot.moveright()".
2. add "robot = getImage(base,"data/default.png");" above robot.stopright() in method "public void keyReleased"

same way you do this with moving left and jumping..
Hope it helps

Reply
tanmay
12/15/2013 12:48:07 am

my character is flickering from the start of the applet. Should it do so?

Reply
tanmay
12/15/2013 12:12:49 pm

Got it in the startingclass remive the super methods from paint and update classes

Reply
nm
12/28/2013 06:26:31 am

had the same problem of image.
When i prints base value by

System.out.println(base.toString());

it threw

file:/C:/Users/<username>/workspace/KiloboltGame/bin/kiloboltgame.StartingClass1388269291513.html

so it had to go in bin>data not the src>data.

though even being in src>data, code should be changed to "../src/data/character.png"

it worked this way also.

Reply
Ethan
1/3/2014 04:34:37 am

I've followed your code very closely, and i didnt have the robot painted at first, so i was a little alarmed. after fooling around a bit i got half of it to load? and at the top left of the emulator. so I movd his coordinates to the bottom left, going off code a little, but still only half the robot was shown. I've reviewed your code many times and there is nothing really flawed within mine but if i set the coordinates to 0, 0, hes just hanging around in the top corner. any insight would be greatly appreciated.

Reply
Ethan
1/4/2014 07:52:59 am

So i tried adding a new picture instead of the character.png, to see if it was just a corruption in the image, but it isn't. When i move the image coordinates to the bottom left, 100, 382, only half the image shows up, and if i g to Applet>restart, the image shows up as half, and another image shows up in the top left corner. this also happens if i resize the window. getting frustrated, as i have been working and reviewing this for a couple of days now. any help, still greatly appreciated

Reply
BoyKot link
1/25/2014 12:25:37 am

For those who have problem with PNG loading in SDK 1.7 here is my solution:
change
base = getDocumentBase();
to
base = getClass().getClassLoader().getResource("gameone");

Reply
BoyKot link
1/25/2014 12:30:18 am

Oops, sorry, I've meant your main package name instead of "gameone" ("gameone" is my package name).

So
base = getClass().getClassLoader().getResource("kiloboltgame");
or whatever you've named it.

Reply
Vicky
1/29/2014 06:08:44 pm

Hello James, thank you for the great tutorial. I do have a small issue. When my robot jump, it goes off from the top of the screen and never comes back to the ground. Is it normal?

Reply
allan
3/5/2014 08:06:21 pm

Are you sure you got jumped = true; in Robot.java?
============================
public void jump() {
if (jumped == false) {
speedY = -15;
jumped = true;
}
===================
If that doesn't do the trick inspect your update methods IF of jumping.
===================
if (jumped == true) {
speedY += 1;
if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}
}
===================

Reply
pranaykarani
4/2/2014 08:07:38 pm

How does the java know that SpeedX is dedicated for horizontal movement and SpeedY is dedicated for vertical movement?
Since both SpeedX and SpeedY are just int variables, how does java differentiate which variable is used for horizontal movement or vertical movement?
thanks in advance

Gajendra link
2/4/2014 03:04:16 am

i have the character.png loading problem.. icant resolve it. im using JavaSe 1.6.. plz help. i wnt to continue as soon as possible.. :(

Reply
Neeraj Gupta
2/19/2014 02:38:14 am

Hi James,

First of all thanks for these awesome tutorials.

I just wanted to know how you calculated the value when you move the robot left or right or when jumped( -6,6,-15).

moveRight(), which sets the character's horizontal speed (speedX) as 6.
moveLeft(), which sets the character's speedX as -6.
stop(), which sets the speedX as zero.
jump(), which sets the vertical speed as -15.

Reply
Edwin
2/23/2014 12:22:04 am

My problem with character.png not loading was that was missing the line below at the end of the update method:

g.drawImage(image, 0, 0, this);

It is working now, hope that helps to others.

Reply
Rick
2/23/2014 06:38:25 am

Thanks so much for this tutorial. Everything worked perfectly for me. That robot pic is really cool =).

Reply
sagar
2/23/2014 10:08:16 pm

it is showing me only a blank screen :(

Reply
sagar
2/23/2014 10:12:31 pm

sorry i have forget to change the name of my character :s

Reply
Karlis link
2/24/2014 04:15:20 am

I found the problem i had !! :D with robot img! :D
1.Bad code on win7 ultimate ! 1.7 eclise
character = getImage(base, "data/character.png");

2. Fixed code ! all works now ! :) Now the img is seen!
character = getImage(base, "../src/data/character.png");

Reply
Rom
3/4/2014 03:54:59 pm

"The Origin (0,0) pixel is at the TOP LEFT. I will talk about this below. This means that if a character has a positive speedY, he is FALLING, not RISING." -- Isn't this supposed to be positive speedY be RISING? In graph upper y axis is positive and lower is negative? I'm a bit confused....

Reply
allan
3/5/2014 08:24:47 pm

Normally yes, but in this instance no. We just happen to call upper left corner the point of origin (0, 0) instead of lower left corner (as we would normally do in graphs).

You may be confused by the fact that in normal graphs we can have negative values for X and Y axis, which isn't the case now. And we draw it like this:

^positive y
|
|
negative x ____|_________> positive x
|
|
| negative y

when we talk about coordinates in screen resolution, we don't have negative values. We just number pixels starting from upper left corner. So when coordinate is (100, 382), its pixel number 101th counting from left and 383th counting from top (remember starting pixel is 0).

Why we start it from the upper corner instead of lower beats me, but that's just how it is.

Reply
allan
3/5/2014 08:46:21 pm

i see that textformatting ruined my awesome graph. So here's another, hope you understand.

http://imgur.com/s4lIXKg

On the left is a GRAPH, on the right is SCREEN.

Rom
3/8/2014 09:08:02 am

Thanks Allan for the help!

Sanjay Kumar link
3/6/2014 09:29:44 pm

What does creating class Robot in robot mean?
Plz help i am not understanding that robot object method.....

fantastic tutorila for freeee

Reply
Valkata
3/8/2014 10:50:32 am

I didn't quite get what you're trying to understand. It would be helpful if you could copy and paste a bit of the code that's unclear to you.

If you're referring to "robot = new Robot();", then I can try to help.
Robot class is just the general set of rules, values and methods for all future robots. It's like a building plan for a house.

And if you call "new Robot()", you're actually creating a robot that will have all the values and methods defined in Robot. It's like a house that is built and has everything that is in the plan.

This way you can create actual objects that can be in your game. And you can name them any way you like. For example, we can create 3 robots:

robot = new Robot();
another_robot = new Robot();
little_one = new Robot();

Just remember that you have to declare their types first.
private Robot robot, another_robot, little_one;

Reply
Valkata
3/8/2014 10:30:30 am

A possible solution to the problem of robot not appearing. I believe this wasn't mentioned before:

I accidentally wrote:
createImage(this.getWidth(), this.getHeight());

Whereas it should be:
image = createImage(this.getWidth(), this.getHeight());

Reply
Gede Etika
3/11/2014 09:49:32 am

wow ! thats work ! thank you for tutorial :)

Reply
Kevin
3/30/2014 12:11:19 pm

How come there's no constructor in the Robot class?

Reply
pranaykarani
4/2/2014 07:50:25 pm

it is not compulsory for a class to have a constructor. Since there will only be one instance(robot) of Robot class, I don't think there is a need for constructor though you can add if you want...

Reply
KBFan
4/2/2014 01:56:30 am

Can you further dilute the code please. Like the "rubber ducky" method? Because some of us ARE rubber duckies.

Just one example of the line I couldn't understand: Frame frame = (Frame) this.getParent().getParent();

Things like these.


Thanks for the tutorial. It's the best I found on the net so far.

Reply
pranaykarani
4/2/2014 08:08:39 pm

How does the java know that SpeedX is dedicated for horizontal movement and SpeedY is dedicated for vertical movement?
Since both SpeedX and SpeedY are just int variables, how does java differentiate which variable is used for horizontal movement or vertical movement?
thanks in advance

Reply
Kevin
4/3/2014 05:05:29 am

It is differentiated in the paint method. The variable SpeedX adds/subtracts the centerX variable and variable SpeedY adds/subtracts the centerY variable. Then these variables are called upon by using getCenterX() and getCenterY() in the paint method. See below:

g.drawImage(img, x coordinate, y coordinate, observer)

@Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

}

Reply
pranaykarani
4/3/2014 02:14:47 pm

Thank you, but still ..
1) how does java know that speedX is meant for moving robot left-right and speedY is for jumping the robot?
2) how does Java know that centerX is meant for X origin and centerY is meant for Y origin?
these are really confusing me since both are just variables without any connection to the game coordinates.
thanks in advance..

Kevin
4/4/2014 01:34:54 am

1) You are correct, Java does not know what speedX or speedY does, other than that it is a type int.

2) Again, Java does not know that centerX is meant for X origin and that centerY is meant for Y origin either. The way java connects these variables to the game coordinates is through g.drawImage(img, x coordinate, y coordinate, observer), this method takes 4 parameters: image, what the x coordinate should be, what the y coordinate should be, and an observer. In this robot code example we are making the call with this g.drawImage(character, robot.getCenterX() – 61, robot.getCenterY() – 63, this); therefore, we have told this method that centerX is x coordinate and centerY is y coordinate. The drawImage() method differentiates the x and y coordinates and draws the robot where you want it to be drawn based on x and y coordinates you have given. Hope this makes more sense? If it is still confusing try switching the coordinates in g.drawImage like this:
g.drawImage(character, robot.getCenterY() – 63, robot.getCenterX() – 61, this);
What we have done here is tell drawImage() method that center is our x coordinate and centerX is our y coordinate. This is how java knows where to draw the robot.

pranaykarani
4/4/2014 06:10:01 pm

thank you once again,
got it neat and clean..

ashish
4/5/2014 08:39:58 pm

hey!!!
when i right click in robot.java file to select setters and getters i get an error - "the operation is not applicable to the current location.select a field which is not declared as type variable or a type that declares such fields:
help me with ths

Reply
jon el sapoman link
4/11/2014 02:16:43 am

For some strange reason, the data folder would not work no matter what I did. I tried everything for about a day or so and only until I just renamed the folder to data1 and added

character = getImage(base, "data1/character.png");

and that fixed it. I realize I just have to zen out when I do this or I will start having anxiety attacks. Eclipse has a mind of it's own.

Reply
JIm
4/20/2014 04:02:43 pm

Can you please help me? :)
I'm done with this day 4 tutorial
What happens is that when i run the project
It displays the character but it is sliding down upon the start of the applet
Like this
Character
::::::::::::::::::::::::::::::::::::::::
: :
: picture :
: | slides :
: | down :
: \/ :
::::::::::::::::::::::::::::::::::::::::
As you can see, upon the start-up, the picture is moving downwards and i'm not clicking anything
And also at the console of java eclipse
it displays: Do not scroll the background, like an infinite loop
I've written the codes in a bond paper because i'm planning to study the whole tutorial further more, please help me so I can move on to the next tutorial :) Thanks

Reply
pranay
4/23/2014 05:33:31 am

Please THOROUGHLY recheck your code. I had similar problem where my robot was appearing on the top-left corner and when right was press is slided down dialgonally. It figured that I had somewhere messed up CenterX with CenterY. So check your code thoroughly.

Reply
Adink
4/23/2014 01:03:31 am

Hi!

Great tutorials man, i just have one question

how can you declare variables like Robot robot; and Thread thread;

are "Robot" and "Thread" a java keyword or something? because i didn't see you importing them from another class.

Thanks James

Reply
pranay
4/23/2014 05:26:00 am

By your query is seems that the concept of using classes and their instances is unclear to you. Here, author creates a 'Robot' class which contains characteristics and methods that it's instance(here, robot) will have. Then by statement-"Robot robot;" you declare(Remember, you are just declaring robot and not initializing it i.e. you are not stating: "Robot robot = new Robot()" in this statement. It means that computer knows that robot is Robot's object but it still can't use it's methods and properties yet) that, robot is an instance of class Robot and it will(if :robot = new Robot() is stated) have all the properties and methods of Robot class.
For "Thread thread" same thing applies, but instead Thread class comes predeclared somewhere in Java library that you don't have to worry about. All you have to do is create an 'Thread' object(here
'thread') and initialize it by " = new Thread(this);" and then you can use its methods and properties .e.g. here in the next line "thread.start()" your Thread object, 'thread' is using method 'start()' defined in Thread class.

For the import part, since your Robot class is in the same package, it does not need any import statement.

If my explanation goes though on you, then i suggest that you should refer Kilobolt's Java basic lessons thoroughly, especially that part which deals with use of classes and their instances or you can mail me at pranaykarani@outlook.com. Thanks for your time.

Reply
Adink
4/23/2014 04:16:06 pm

Thanks a lot for your explanation, you made it very easy to understand. I just confuse about that Robot class, i didn't realize that i created it within the same package as StartingClass class lol.

As for Thread class then, have we import that one from java library?

Thanks pranay!

pranay
4/24/2014 02:11:16 am

I think since StartingClass is extending Applet we don't need any import statement for Thread. But still, I am not completely sure about it, so it will be better if you cross-check it in Kilobolt's earlier tutorials.

Inc
4/23/2014 03:10:46 am

If you don't see a robot (just a black screen) do:
m_Base = getCodeBase();

Now print it to see what path it contains:
System.out.println(m_Base);

Now get the getImage statement right accordingly.
For me it was:
m_Character = getImage(m_Base, "../src/data/character.png");

The second argument is the path relative to the url in the m_Base.

Two dots (..) mean parent directory. You can go up as high as you need: ../../../../../foo/bar.png.
gl hf 0/

Reply
Saurabh
4/25/2014 04:54:07 am

hey! ummm I was not getting the robot image just a black screen and "don't scroll the background" in console(infinite loop) but it was because the .png file was named "robot.png".

so my getImage statement is:
character = getImage(base, "data/robot.png");

I can see the robot now in java applet....so everything will be good in the future???

Reply
Adrian
4/24/2014 01:31:13 am

Hi! First of all, great tutorials, you did a very good job!

A, also, had the problem with the image not appearing, but managed to solve it, eventually, thanks to the other fellas.

But now, I have another problem, and it really gets me nuts. After i add the moving metods and I compile the StartingClass, it show me the robot very well, but it doesn't move. I really do not know what's wrong, since i've triple checked the program and i have no errors.

If this happened to anybody else, please let me know how you managed the situation.
Thanks a lot!

Reply
pranay
4/24/2014 02:05:19 am

See, if you don't see an that does not mean that your code does not have bugs. That's the problem with bugs, it is very hard to locate one in your code. The only solution to them is THOROUGHLY cross-checking your code.
And for your situation, Have you called the movement methods properly in your StartingClass.

Reply
Adrian
4/24/2014 02:39:43 am

I found the problem.
thread.start(); - this line was missing, from when i created the thread. Clearly, it wasn't gonna do anything without that. Now it works very well.

Thanks for you answer, anyway, pranay!

Adrian
4/24/2014 02:39:48 am

I found the problem.
thread.start(); - this line was missing, from when i created the thread. Clearly, it wasn't gonna do anything without that. Now it works very well.

Thanks for you answer, anyway, pranay!

Adrian
4/24/2014 02:39:56 am

I found the problem.
thread.start(); - this line was missing, from when i created the thread. Clearly, it wasn't gonna do anything without that. Now it works very well.

Thanks for you answer, anyway, pranay!

sam
4/29/2014 03:08:58 pm

Thanks for this great tutorial. I'm a small problem and im not able to know why its happening. Note that there are no errors in my code and its exactly the same as the publishd code. The problem is that the code is not "Listening" to my keyboard inputs, i.e. character not moving... all the methods are there, i also tried to replace all motion instances by console outputs, so when i press a key, i expect to see what i wrote on the cobsole, but there is not anything... any clues ??

Reply
pranay
4/29/2014 04:09:26 pm

Since there is no error in your code that does not mean that your code does not have any bugs. I am sure that there must be bug in your code. I suggest you to THOROUGHLY cross-check your code with author's. It helped me every time. Hope it helps you too..

Reply
Sam
4/30/2014 10:35:14 am

Dear Friend,
Honestly, I'm a very experienced programming, though this is the first time I attack video game programming, for that reason I'm there. I checked the code line by line, then i compared it word by word to the author's code, and it is the same. I read today on the net, and it seems that this is a bug with eclipse. To double check, I recopied the authors code, rewrote mine, and still having the problem.

pranay
4/30/2014 03:40:10 pm

Did you try downloading and trying author's code?

letsee
9/3/2014 03:54:29 pm

per your " not "Listening" to my keyboard inputs,...."


addKeyListener(this); // do you have this somewhere? hint StartingClass.java

Reply
Akio
4/30/2014 01:48:55 am

Hi,first of all thanks for these incredible tutorials,i started with zero knowledge and still keeping up,because it's fantastic even for absolute beginners.. my question is: what if i want to modify or change character image,should not be i able to do it? i was curious and changed character image with random same pixel ratio "PNG" file,also changed URL to new image name,still i get no picture in Applet,but when i change back to robot i see it,am i doing something wrong,or are we not able to modify this code and it's data?

Reply
Akio
4/30/2014 02:03:02 am

Sorry to bother you for no reason,i was able to change image,but as i can see it has to do something with transparency ,could you please give me some info about that...

Reply
Akio
4/30/2014 02:03:54 am

Sorry to bother you for no reason,i was able to change image,but as i can see it has to do something with transparency ,could you please give me some info about that..

Reply
Virendra link
5/1/2014 09:59:55 am

Is the main method missing because its in the Applet Superclass?

Reply
Akio
5/2/2014 10:09:05 pm

Thanks for reply , i think everything's fine now . I can normally add anything i want with or without transparent background.Thanks for help

Reply
Rob
5/5/2014 06:08:40 am

hey guys im super new to this stuff, I am unable to even put the png file in the data folder, its ment to be just a regular folder not a source folder right

Reply
Jake
5/9/2014 08:46:04 am

FYI, just above Figure 2-18, where it talks about the setters and getters, it has this code:

public void setSpeedX(int speedX) {
this.height = speedX;
}

But the local variable is "speedX", not "height"; the auto-generated code has "this.speedX = speedX". Had me confused for a minute.

Reply
voidsleep
5/16/2014 03:10:46 am

Although I have tried everyone's suggestions in the comments and have checked and rechecked my code, I cannot get my robot to show up.

Could I e-mail my code to someone for some help, please?
Thank you

Reply
voidsleep
5/17/2014 01:58:22 am

I figured out why my robot wasn't showing up. I was using Backtrack as my operating system. I switch to Ubuntu 14.04 last night and everything worked wonderfully. Thanks!

Reply
Jake
5/21/2014 07:40:48 am

One thing I've noticed with Eclipse is that if I download the images into the appropriate folder and try to use it immediately, they won't appear in the program. If I right-click the project in Package Explorer and choose "Refresh" so that the image file shows up in the list of files, and then try to run it, the images show up.

Reply
Jacob
6/6/2014 10:50:12 am

I'm having a hard time getting my Robot to show up. I downloaded directly into the data folder, and noticed the .png wasn't showing up in my Package Explorer after reading your comment, Jake. I hit refreshed and it showed up!
I went to run my program, but still no Robot! D:
Upon first running of the program, I got an error message that appeared only once, which said something along the lines of: Can't read AppletViewer properties file - Applet
What does this mean and how do I fix it??

EUNY
6/22/2014 12:48:03 am

Thank you so much for advice. I refreshed my Package Explorer and it worked perfectly!XD

anirudh
5/16/2014 08:22:16 pm

how to create those characters????

Reply
amit
5/27/2014 07:21:42 pm

Great tutorila! loved the jumping logic, gravity pull effect feels so real! thanks!!

Reply
Sanket
6/2/2014 06:23:03 pm

Hi every one, I really appreciate those people who made this great series of tutorial.I am taking it very seriously for my further carrer developing.I wanna be Indie game developer and publish my own games to market to generate some revenue from it.

Yet I have just reached here for learning programing 1st time in my life after geting 2yrs of exp. as a 3d artist in Animation industry.

Well, what I want to tell you people is as I have followed each & step of this tut yet.I have copy & paste the Robot.java script and play it.
Then I got found some issues like

1.If I keep pressing jump button , my Robot is getting more heights in the air.
2.If my character reaches to its limit in X co-ordinates.my console menu shows "Background is moving now" or something like that but, In the in between Its also showing me "Background stops..." etc.That means my bg will move by stoping...moving...stoping...moving..I mean not continuesly.
3. I want my jump little tricky to make my game quiet hard play.
So, I did modify a code little bit may be thats helpful for furthure.
Here. FOR "Robot.java"

package kiloboltgame;

public class Robot {
private int CenterX = 100;
private int CenterY = 382;
private int SpeedX = 0;
private double SpeedY = 1;
private double counter = 0;
private boolean jumped = false;
private boolean BGmove = false;// switch to move background only in
// condition.

public void update() {
if (SpeedX < 0) {
CenterX += SpeedX;
} else {
if (CenterX <= 190) {
CenterX += SpeedX;
} else {
SpeedX = 0;
}
}
// BG controller construct.
if (CenterX >= 190 && BGmove == true) {
System.out.println("Background will MOVE NOW");
} else {
System.out.println("Background STOPED");
}

// Stop moving outside the screen.
if (CenterX <= 60) {
CenterX += SpeedX;
CenterX = 61;
}

// Updates Y Position

if (CenterY + SpeedY >= 382) {
CenterY = 382;
SpeedY = 0;
} else {
CenterY += SpeedY;
SpeedY += 1;
SpeedY += counter;
}

// Handles Jumping
if (jumped == true) {
CenterY += SpeedY;
SpeedY += 1;
} else if (counter >= 0.01) { // this will help to prevent double jumping.
CenterY += SpeedY;
jumped = false;
} else {
jumped = true;

if (CenterY + SpeedY >= 382) {
CenterY = 382;
SpeedY = 0;
jumped = false;
}

}
}

// on left key pressed.
public void moveLeft() {
SpeedX = -6;
}

// on Right key pressed.
public void moveRight() {
SpeedX = 6;
BGmove = true;
}

// on up key pressed.
public void jump() {
if (jumped == false) {
SpeedY = -15;
SpeedY += 1;
jumped = true;
}
}

public void stop() {
SpeedX = 0;
SpeedY = 0;
jumped = false;
BGmove = false;
}

public int getCenterX() {
return CenterX;
}

public int getCenterY() {
return CenterY;
}

public int getSpeedX() {
return SpeedX;
}

public double getSpeedY() {
return SpeedY;
}

public boolean isJumped() {
return jumped;
}

public void setCenterX(int centerX) {
CenterX = centerX;
}

public void setCenterY(int centerY) {
CenterY = centerY;
}

public void setSpeedX(int speedX) {
SpeedX = speedX;
}

public void setSpeedY(int speedY) {
SpeedY = speedY;
}

public void setJumped(boolean jumped) {
this.jumped = jumped;
}

}

Reply
lior
6/4/2014 02:14:08 am

The robot not appearing in my game
ן tried everything in the comments and nothing worked

Reply
Sanket
6/5/2014 09:55:00 pm

lets upload your StartingClass.java and we will see.

Reply
Sanket
6/5/2014 09:55:40 pm

lets upload your " Starting Class " code and we will see.

Reply
Sanket
6/5/2014 09:56:55 pm

lets upload your " Starting Class " code and we will see. OR follow the day 4 again.

Reply
chulian
7/7/2014 01:01:58 am

What about the copyright of your source code? Is it CC or ist it completely free?!

Best tut found on the internet yet! Well done! :)

Reply
NIhad link
7/8/2014 05:37:42 am

I can't drag the robot picture into the data folder can anyone help?

Reply
DK
7/8/2014 08:26:15 am

This is really some mindblowing stuff man, really liking the tutorial so far, great work!!! Started from page 1 yesterday and got really into it; thorough explanations, nice descriptions. Can't wait to reach the end and start coding my own beasts :)

Reply
Alvin
7/21/2014 05:03:38 am

Hi,

First I tried to type everything myself from your instructions but got lots of errors then I tried to copy and paste and got same errors. I downloaded your code and opened it and there was no errors. Then when I tried to copy and paste into my whole project the errors come back. It seems to start with the StartingClass and something about a serial ID. Also get some keypressed errors.

I then tried to import the whole project into Eclipse but the errors still exsist. Please help, I really want to get this down before moving to next topic. Thank you!

Reply
Jake
7/21/2014 06:37:39 am

For the serial ID "error", that's actually a warning. You can either put your mouse over the class name and choose "Add generated serial ID" from the tips that pop up, or change the setting under Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Potential Programming Problems -> Serializable class without serialVersionUID to Ignore.

For any other errors, you'd have to be more specific about the error.

Reply
AJL
7/26/2014 05:20:54 am

Possible solution for robot image not showing up:

If your "data" folder is inside the "src" folder along with "kiloboltgame" folder (lower letters ), try the following setup:

character = getImage(base, "../src/data/character.png");


Goodluck!

Reply
Joshcorpia
11/26/2014 01:14:30 am

OMG thank you, i have been trying for ages to figure this out, have tried changing code, build path , version everything and this /\ /\ /\ worked. Also ps James great tut

Reply
Sourav
7/30/2014 03:13:46 pm

why We use to import graphics statement in robot class. I think we aren't use any graphics statement in robot class then how to use import to graphics in robot class.

Reply
Mario
8/8/2014 10:18:20 pm

JUMP

Hi, can anyone help me to understand how the robot jumps?

I made a small experiment by changing the Thread.sleep(17) to Thread.sleep(1000), so every update occurs second by second.

By clicking space bar so that the robot jumps I noticed that it makes in fact 15 iterations (MOVESPEED=-15) but they are not all proportianlly equal. I mean, the jump speed is decreasing as the robot is getting higher, like it happens in real world. As soon his feet get off the ground (1st iteration) the space between his feet and ground it's much bigger than the space between two last iterations when he gets to the top (-15).

I also don't understand how we can see the ascendent movement of the robot and not see him immediately at the maximum height of his jump. I understand the descendent because it's being added 1 to his position until he hits the ground.

Checking the horizontal movement, the robot moves 5 pixels at a time. This doesn't happen with jumping...

Reply
Mario
8/8/2014 10:18:29 pm

JUMP

Hi, can anyone help me to understand how the robot jumps?

I made a small experiment by changing the Thread.sleep(17) to Thread.sleep(1000), so every update occurs second by second.

By clicking space bar so that the robot jumps I noticed that it makes in fact 15 iterations (MOVESPEED=-15) but they are not all proportianlly equal. I mean, the jump speed is decreasing as the robot is getting higher, like it happens in real world. As soon his feet get off the ground (1st iteration) the space between his feet and ground it's much bigger than the space between two last iterations when he gets to the top (-15).

I also don't understand how we can see the ascendent movement of the robot and not see him immediately at the maximum height of his jump. I understand the descendent because it's being added 1 to his position until he hits the ground.

Checking the horizontal movement, the robot moves 5 pixels at a time. This doesn't happen with jumping...

Reply
Mario
8/8/2014 10:18:38 pm

JUMP

Hi, can anyone help me to understand how the robot jumps?

I made a small experiment by changing the Thread.sleep(17) to Thread.sleep(1000), so every update occurs second by second.

By clicking space bar so that the robot jumps I noticed that it makes in fact 15 iterations (MOVESPEED=-15) but they are not all proportianlly equal. I mean, the jump speed is decreasing as the robot is getting higher, like it happens in real world. As soon his feet get off the ground (1st iteration) the space between his feet and ground it's much bigger than the space between two last iterations when he gets to the top (-15).

I also don't understand how we can see the ascendent movement of the robot and not see him immediately at the maximum height of his jump. I understand the descendent because it's being added 1 to his position until he hits the ground.

Checking the horizontal movement, the robot moves 5 pixels at a time. This doesn't happen with jumping...

Reply
Mario
8/8/2014 10:18:59 pm

JUMP

Hi, can anyone help me to understand how the robot jumps?

I made a small experiment by changing the Thread.sleep(17) to Thread.sleep(1000), so every update occurs second by second.

By clicking space bar so that the robot jumps I noticed that it makes in fact 15 iterations (MOVESPEED=-15) but they are not all proportianlly equal. I mean, the jump speed is decreasing as the robot is getting higher, like it happens in real world. As soon his feet get off the ground (1st iteration) the space between his feet and ground it's much bigger than the space between two last iterations when he gets to the top (-15).

I also don't understand how we can see the ascendent movement of the robot and not see him immediately at the maximum height of his jump. I understand the descendent because it's being added 1 to his position until he hits the ground.

Checking the horizontal movement, the robot moves 5 pixels at a time. This doesn't happen with jumping...

Reply
Mario
8/8/2014 10:19:09 pm

JUMP

Hi, can anyone help me to understand how the robot jumps?

I made a small experiment by changing the Thread.sleep(17) to Thread.sleep(1000), so every update occurs second by second.

By clicking space bar so that the robot jumps I noticed that it makes in fact 15 iterations (MOVESPEED=-15) but they are not all proportianlly equal. I mean, the jump speed is decreasing as the robot is getting higher, like it happens in real world. As soon his feet get off the ground (1st iteration) the space between his feet and ground it's much bigger than the space between two last iterations when he gets to the top (-15).

I also don't understand how we can see the ascendent movement of the robot and not see him immediately at the maximum height of his jump. I understand the descendent because it's being added 1 to his position until he hits the ground.

Reply
Peter Pan
8/9/2014 03:38:37 am

The idea behind double buffering (trust it works, no idea why, says the tutorial) is that instead of having to redraw everything on the visible screen, it is first drawn in the memory on an invisible image, then, at once, copied to the visible screen. This helps a lot - if the game drew its image directly on the screen, it would need to erase the old parts, e.g. the robot in the old position, from the visible image and then draw it again in the new position. As the screen might refresh at any time while the drawing is going on, it would cause flickering - maybe the screen refreshed after the erase of the old robot image, before the new one was drawn, for example.

Here, double buffering allows one to completely avoid erasing - each frame will get a new clean image which replaces the old visible one.

(Erasing when there is a real background image would be very difficult too, especially if the background was moving - which part of the background would need to be copied over the old robot image to cleanly erase it? With double buffering, no need to think about that.)

The update(Graphics g) method is automatically called by the "system" before the paint(Graphics g) is called. Here it looks like we have a little bug - update calls paint() to draw the robot on the invisible image, then copies the invisible image to the visible one, and then the "system" calls the paint to draw the robot again on the visible image. So we get two drawings of the robot for each frame, wasting time.

I believe the standard procedure would be to draw the robot in the update(Graphics g), and then copy the invisible image to the visible one in the paint(Graphics g), and only there, not in the update(Graphics g).

/* Actually, it does not matter if the copying is done in update or paint - update and paint are called next to each other by the "system" - drawing in update is ok too technically. But calling paint(Graphics g) in update(Graphics g) is still a bug - causing two paints. If the position of the robot changes between those (maybe from a separate moveRobotThread), it would cause overlapping robots in the image - and it will cause double painting of the robot in any case. */

Reply
Vaibhav
1/13/2015 10:28:22 pm

Thanks dude! That looks like a nice explanation for the concept of double buffering. I was also confused with calling paint inside update method. But i feel i know understand the purpose of double buffering and some of its logic in the code but the bug you figured out is still a mystery for me. As i'm new to game programming and Applets, but have some experience with Java.
And James, we owe you much more than thanks for putting this up. Although i will be donating some amount and spreading it to my friends.

Reply
Google
8/10/2014 10:23:28 pm

Can you please tell me short what you said in that lesson?

Reply
de
8/15/2014 06:49:13 pm

Fisrt, the image (character.png) didn't show. I tried all that was show above, but the image still doesn't show. Help me...

Second, i have a, error message at "public class StartingClass extends Applet implements Runnable, KeyListener ". The message show "The serializable class StartingClass does not declare a static final serialVersionUID field of type long". What it does mean? And how to fix that error?

Thanks for this great tutor...

Reply
de
8/15/2014 06:52:07 pm

The first problem solved. Thanks, AJL.

Reply
mangix
8/20/2014 01:20:35 am

This is the more efficient double-buffering implementation:

private Robot robot;
private Image image, character;
private Graphics second;
private URL base;

...

@Override
public void paint(Graphics g) {
second.clearRect(0, 0, getWidth(), getHeight());
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());

second.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

g.drawImage(image, 0, 0, this);
}

@Override
public void update(Graphics g) {
paint(g);
}

Reply
Elsa
8/25/2014 06:45:53 pm

cant understan ..........
having alot of problems :(

Reply
mangix
8/25/2014 11:10:43 pm

What do you don't understand my dear?

ahmad
8/27/2014 02:37:56 am

the image (character.png) didn't show. I tried all that was show above, but the image still doesn't show

Reply
atriantas
9/4/2014 07:55:50 am

on getImage URL try "file:/C:/Users/YOUR_NAME/IdeaProjects/KiloboltGame/src/data/character.png"

Reply
Ilikegames
9/13/2014 05:30:26 pm

I started with this tutorial two weeks ago without any background in java. I could follow what was being said up until day 3 of unit II.
Now i don't actually understand the logic/algorithm behind the codes. could you please explain how the code actually works with all the minute details?

Let me explain a bit of what I don't understand.
1) In the definition of start() in StartingClass there is a statement that says thread.start();. shouldn't this statement just call the start() again, thereby looping this block of code forever?

2) Where does the control go after the execution of the init()?

3) do all the methods, such as start(), stop(), destroy(), update() etc, have to be in the same sequence as explained?

4)Why is there no main() in StartingClass?

5) in the start() how would i know i should mention 'this' in the thread constructor.

Reply
Sales
10/15/2014 08:40:14 am

Probably a really dumb question but how do you get this to run?
There is no main to run, so I am confused as to how to get this to work

Reply
day 4 is working now
10/20/2014 05:20:34 am

There are lots of comments about how people had to edit the location of the robot picture, or couldn't get the robot to draw. I think this is because the location of where the picture should be is not clearly stated. At first I put mine in ~/workspace/KiloboltGame/src/data. However to get the code to run as written in the tutorial it needs to be in ~/workspace/KiloboltGame/bin/data.

Great tutorial, Thanks!

Reply
day 4 is working now
10/20/2014 05:36:24 am

nevermind I forgot to save after editing. I can't get it to run as written either lol. I have to change the code to character = getImage(base, "../src/data/character.png"); or character = getImage(base, "../bin/data/character.png"); either works now as I have coped the image to two different places. not sure where it is supposed to be to run as written.

Reply
Muhammad Asim
11/4/2014 03:49:44 am

Dear Admin.
i want to know that we are taking these things as veriables.
centerX,
centerY,
speedX,
speedY,

so how the java knows that which is speed and which is center?
i think that these are predefined methods in Library files and if i am wrong please tell me how the java knows about it?
thank you
waiting for your answer

Reply
Muhammad Asim
11/4/2014 04:41:05 am

Dear admin.
Thank you
i got my answer here.
g.drawImage(character, robot.getCenterX() - 61,
robot.getCenterY() - 63, this);

Reply
Muhammad Asim
11/4/2014 04:54:10 am

but still dont know about speedX and speedY

Reply
Bobkov D
11/24/2014 01:35:18 pm

Hi, James. You wrote:
" //In Java, Class Variables should be private so that only its methods can change them
private int centerX = 100;...".
Maybe did you mean "Instance Variables"?

Reply
Tangla
11/26/2014 07:06:15 am

I had to change from java 1.7 to 1.6 in order to select getters and setters.
Great tutorial

Reply
Jay
12/8/2014 01:23:11 pm

Hey,

Is it normal that the robot does not move very far across to the right of the screen? I changed my code to yours and the result was identical?

Reply
Vaibhav
1/13/2015 10:35:40 pm

Yes that is normal, because we have put x-coordinates to a limit after which we want background to look moving.

Reply
San Luong
12/15/2014 04:28:16 am

Hi,
public void jump() {
if (jumped == false) {
speedY = -15;
jumped = true;
}

}
For the Jump method. Why do you need the first statement if (jumped == false) ?. I took it out to try and it's still working. Thank you.

Reply
kislay
12/15/2014 06:32:16 pm

On jump we set speedY=-15 and jumped=true so when robot.update() is called centerY is updated as centerY-15.So why is the robot not instantly drawn 15 pixels above instead we see interediate frames of robot going up??

Reply
Mario
12/18/2014 07:56:39 am

Hi Kislay,
The Robot jumps 15 pixels when jumped is true and it updates centerY. But while jumped is true it is adding 1 to speedY. So the result is CenterY at 382 -14 (=-15+1), -13 (=-14+1), -12, -11, ..., -1, 0, +1, +2,..., until CenterY is 382 again.

Check the following code on eclipse:

package testesaltos;

public class Principal {

public static void main(String[] args) {

Thread thread = new Thread() {

public void run() {
// Constants are Here
int centerY = 382;
boolean jumped = false;

int speedY = 0;

for (int i = 0; i < 30; i++) {
System.out.println("Iteration " + i + ": center Y is at " + centerY + "; speed Y: " + speedY);


if (jumped == false) {
speedY = -15;
jumped = true;

}

// Handles Jumping
if (jumped == true) {
speedY += 1;
centerY += speedY;

if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}
}

}

}

};
thread.start();
}
}

Reply
THE DUDE
12/16/2014 12:34:23 pm

If your picture doesn't work, you have to put it in the data file in bin folder as well as src.

Reply
Faye
12/17/2014 08:51:24 am

Ok so when the game is ran, the init() happens, then start, stop, destroy, and then the run() function, which has our game loop. If that's the thing that's happening until some kind of failure or success satate is reached, then how is it taking key inputs if the key pressed and released are outside of this game loop. Same with a few others.

In the run() game loop I get the update() function is comeing from the Robot.java, but what about the update( Graphics g ) is also outside of this loop. So how are these actually exectued in the code?

Reply
Natalia B.
1/6/2015 07:47:11 am

Hi there! I'm enjoying learning my first Java programming with help of your tutorials. You are explaining things very thoroughly, thank you for that. The code that you gave in the end wouldn't work for me though. I found that 2 lines are missing in the Robot.java code you gave. In public class Robot I added: private int width = 10; private int height = 10; Now code is working and Robot is moving and jumping. Thanks!

Reply
Tautvydas
1/23/2015 09:05:14 pm

Hey, i am having problems with setting the getters and setters, when I choose source>generate getters and setter i get to tick these variables: base, image, character, robot, second and not getCenterY or getCenterX

Reply
burnthills
1/29/2015 11:15:38 pm

robot wasn't showing up for me either, whether I was using GetDocumentBase or GetCodeBase until I added "src" to path, even double-dots didn't help

character = getImage(base, "../src/data/character.png"); //works

Reply
Harvey
2/9/2015 05:10:58 am

Thanks man

Reply
Aidan link
2/2/2015 12:49:25 pm

I have an error that states that e cannot be resolved. If you know how to fix this, please tell me.

Reply
Aidan
2/8/2015 05:07:44 am

Nevermind, I fixed it

Reply
Harvey
2/9/2015 05:30:31 am

Hi, I run the program with no problems but the console outputs ("Do not scroll Backround") over and over and the character does not move. Please help

Reply
Tom Collier
2/18/2015 07:10:25 am

hello, I've compared codes a million times and mine is exactly the same as yours but my character does not move! Robot is working it's starting class that is being the issue! says the error starts at robot.update(); i've looked at this and the update method and it seems to be written out fine.. PLEASE HELP

Reply
Tom Collier
2/18/2015 07:57:42 pm

No worries I had a few @Override missing added them and it worked! Didn't realize they were so important! If anyone has more information on these and their jobs, I'd love to know!

Reply
Arahain
2/23/2015 09:13:56 pm

I did also have problems with the png file.
It didn't work with IntelliJ but this is a problem with the IDE and applets.

I found a solution here: http://valk.id.au/blog/free-stuff/help-applets-are-behaving-weird-in-intellij-idea/

Cheers!

Reply
Huntr
11/19/2015 06:50:49 pm

Wow thank you SO much. I've wasted hours on this and this finally helped me.

Reply
Gianluca
2/28/2015 12:59:32 am

Hi, I am new to Java and I would like to know: where does the program know to execute first. I thought that a java program needed a main method as the entry point of execution, but since this one doesn't I am now confused...

Thanks

Reply
JT
3/1/2015 01:02:12 am

At first the robot image in my environment was flickering. Then I commented out the call to super.update(g) (which came as default from the stub) and flickering stopped. Wonder why the superclass update call cause the flickering, is it clearing the display area, some heavy processing or extra sleeping?

Reply
Bogdan
3/8/2015 01:51:55 am

I DID IT! Guys it will be work if you use:
character = ImageIO.read(new File("YOUR PATH")); insted character = getImage(base, "../src/data/character.png");

Reply
Neven
3/8/2015 07:22:51 am

Hi i have one strange question and im confused

public void moveLeft(){
speedX = -6;

public void moveRight(){
speedX = 6;

when i type these im recieving error it saz for void that is an invalid type and for moveRight and moveLeft saz Ilegal modifier for variable "moveLeft or moveRight" only final is permitted, stop and jump are fine without errors so what to do pls help :( how to solve moving error :/

Reply
Zeldariomon
10/16/2015 05:45:43 am

I also had the same problem... but I later found out that I had put an extra curly brace after all the methods. Deleted that... and Yureka :D

Reply
Santosh
3/29/2015 08:51:25 pm

Why there is not main method

Reply
srinivas link
8/18/2015 05:03:11 am

Applet does not have main method it is a life cycle with predefined methods

Reply
Dave
4/20/2015 04:50:48 pm

// Updates Y Position

if (centerY + speedY >= 382) {
centerY = 382;
}else{
centerY += speedY;
}

--------------------------------
why shall we add speedY to centerY?
Is it possible to make like this?

if (centerY >= 382){
centerY = 382
}

Reply
Mike
5/9/2015 04:51:35 pm

For the longest time, couldn't get that robot to draw. Finally I tried testing the IDE.. whether or not a different IDE would fix it.. I usually use IntellijIDEA, but that wasn't drawing the robot. Then I tried NetBeans..wasn't working right. Then tried Eclipse.. success!! Lesson learned is that even if the code is the same, a different IDE can sometimes fix things.

Also, Bogdan's solution about using ImageIO instead of getImage works for IntellijIDEA (I have version 14) and using Java 1.8. But you have to have the EXACT path, meaning starting from the C:/ drive. Tried this and was relieved that it finally worked, since I didn't want to develop in Eclipse.. love Intellij too much.

Reply
Garegin
7/15/2015 06:35:29 am

So, if i switch to Eclipse it will work?? and how can I get it work on Intellij?

Reply
Surabhi Gupta
5/19/2015 10:44:15 pm

code is not working because of the absence of main() funt.

Reply
Mahesh V N
6/2/2015 08:00:03 pm

The robot (character.png) appears, but shall not move around or take any inputs from the key board (left, right, up, down and jump won't work).

Reply
leister
6/25/2015 07:09:29 pm

Great Tuts man, I run into small problem but I did fixed it and thought I should share it if someone else run into this., Just when I compile it or run the program my character is only showing half of its body, if it happens to you just change the number of getCenterY() of paint method under StartingClass Java and that should fix the problem =)

To the author (James) thanks a lot for this great tutorial ! Kudos! =D

Reply
Hardeek
6/28/2015 01:51:25 pm

Can any1 plzz explain me the public void update(Graphics g) method and public void paint(Graphics g) method step by step..

Thanks

Reply
Frankie
7/4/2015 06:41:00 am

I was trying to save the Day 4 webpage to work offline, but the resources for pictures are not loading when the HTML file for Day 4 is opened, just thought I'd let you know.

Reply
ms
7/9/2015 04:13:19 pm

public void start() {

robot= new Robot();
Thread thread= new Thread(this);
thread.start();
}

I did not understand the need of the code written inside the start() method. Could you please explain it in more detail? I tried commenting the 3 statements written inside the start() method and even then the robot gets displayed perfectly and it shows no error.

Thankyou!

Reply
Derek
8/8/2015 07:38:14 am

I am not sure if anyone else if having this problem but I cannot get the image to display due to the fact that when I run my StartingClass the filepath generated for base is a Temp folder in AppData in User. Not the folder where my Starting Class is located. I am using Intellij so that might have something to do with this but any insight would be appreciated.

Reply
Darron
8/31/2015 08:05:17 am

You're correct its pointing to the temp folder. You'll want to change the line within the Try/Catch to:
base = StartingClass.class.getResource("/data/");

then for the character image:
character = getImage(base, "character.png");

Reply
systemShock
11/5/2015 10:48:49 am

Thanks so much for this, was trying to solve it for half a day.

BMZ
9/3/2016 08:53:10 am

YES!!! Thank you! I've also been trying forever. ^THIS WORKS !

sreenivas link
8/17/2015 08:24:05 pm

Wat a great tutorial making game development easy,but after coding is done my robot is flickering all the time can some one please help me out from this....

Reply
Brian Koren
8/18/2015 04:50:43 am

Where do I put robot.methodName?

Reply
srinivas link
8/18/2015 05:09:22 am

If I remove the super.update(g) method in startingclass.java my robot not listening to keys,can someone help in solving this?thanks in advance

Reply
Dave
9/25/2015 03:38:01 pm

Hi is the robot meant to move at the end because mine doesn't. The commands to move just appear in the console.

Thanks

Reply
Stephen
10/9/2015 12:44:19 pm

Just curious, in the init() method, shouldn't the character Image setup also be included in the try block, because if for some reason base fails to be initialized, you will have an error loading the png file. Then you can put a println("Resources failed to load") into the catch block there.

Reply
deepak
10/12/2015 06:57:54 am

my robot is showing movement but only sometime and the other times it does not move at all.
what should i do?

Reply
Justine
10/22/2015 08:44:10 am

I'm making my own android game and I have a question/concern. First, I can not, for the life of me, fix the getCenter errors in the paint method. I've done everything according to the tutorial and it still says the method is undefined for the type robot. Is it because I'm using different names and images, or is it something else? If it is because of naming differences, are there any other places where I need to change the name?

Reply
Cory
11/27/2015 12:34:59 pm

Hi, I have been following the tutorial but have implemented input slightly differently, without scrolling, and have also implemented running movement. For some reason, I'm getting a few errors and do not understand why.
For one, the character is effectively blocked at the screen edges, but if if play around with pressing left and right alternately, the player will glitch past the screen and keep on going.
Secondly, for some reason my running method will only work if the run key is pressed BEFORE the movement key... behavior is kind of odd for some reason. Help would be appreciated. I can email the code if needed, since I don't think posting a pile of code here would be a good idea.

Reply
Tim
12/10/2015 03:15:21 am

I have gone through all the tutorials so far and it has been a great learning experience. One of the problems I am facing is that the startingClass.java gets quite long. This makes reading to the code rather unclear. Is it also possible to split up the code into different .java files and connect them (one for keypresses, one for graphics and one for the rest)?

Reply
Deepansh
1/5/2016 10:56:08 am

my robot isn't moving

Reply
Yumeito
1/13/2016 12:31:10 pm

First go to Project>CLean..>OK
You'll find Project in the tool bar .

if that didn't fix the issue check if u wrote robot.update(); in the run method in the StartingClass. And then check you're entire code to see if you made any typing errors....

Reply
Ben S
1/26/2016 07:19:31 am

Hi enjoying the tutorial so far (quite over my head as a beginner though!). I am up to "generating Getters and Setters" and on your screenshot it comes up with the same 5 boxes to tick but only brings that to a total of "10 of 10 selected", not the "14 of 14 selected" in your screenshot. Is the screenshot taken from later on in the programming or have I missed something?

Reply
Ulvi
3/26/2016 07:11:24 am

Hi. i run my program but nothing happens. in this turorial we didn't write anything in method "main". I think thats why my program doesnt do anything. what i must do with main method????/

Reply
Rishabh Gupta
6/27/2016 11:27:57 am

There's no main method till now. Check your code again you might be missing something.

Reply
Incerto
5/16/2016 12:11:07 pm

For everybody that left "SUPER.(start, stop, etc)" as it was: IT DOES NOT WORK IF YOU DONT DELETE IT.

Reply
Rishabh Gupta
6/27/2016 11:26:38 am

Thanks! Removing those stopped the flickering.

Reply
Brien Smarandache
10/5/2016 07:17:38 pm

hey guys, so i Cleaned and checked for errors and im all good there, except my character doesn't move. anyone else encountering this?

Reply
Ulfhedinn
10/9/2016 03:56:22 am

My Applet still not showing the character.png image. I tried all that have been said before. I tried to delete and drag-and-drop the image, checked the code, it seems the same as the original, still nothing.
I don't know what i'm doing wrong.

Reply
Sadik
11/26/2016 09:48:33 pm

My robot doesn't move completely from one end to the other of the applet. Is this normal?

Reply
Brandon
12/31/2016 01:41:28 pm

I cannot get the character image to show up, no matter what I do.
I've written the code myself; I've copy-pasted from the site; I've downloaded and imported the project and ran it; I downloaded and installed Eclipse (I was using Intellij IDEA) and ran it through that; I even tried compiling and running it from the command line.
The character is moving with the keyboard (I 'System.out.println'ed the position each frame) and jumping just fine, but it won't actually show up.

Reply
Deepal
12/31/2016 11:59:26 pm

hello guys
when i'm running my they run but my data/character.png is not working
they are not saw the game screen. plzzz tell me why come this problem???

Reply
gvangelatos
5/27/2017 03:34:03 pm

can someone please explain this:
Frame frame = (Frame) this.getParent().getParent();

Reply
Stevo6342
5/27/2017 03:47:52 pm

This is a cast procedure. The getParent() method returns and Object class, but it needs to be cast to a Frame class to be used further.

Reply
fox_acid
5/6/2018 06:31:21 am

Finally, we must create a data folder by right clicking on src and creating a folder named data.
CAN ANYONE TELL ME HOW TO DO IT IN INTELLJ?

Reply
blasp
12/5/2018 02:09:22 am

I managed to solve character.png not showing up by setting the base = getDocumentBase ();
it worked without changing anything to the path.

Reply
Jhemp
3/17/2020 12:11:20 pm

Hello guys, I followed this tutorial a while back and everything was fine, now we have 2020 and Java 11, and the compiler tells me that Java.Applet is deprecated, and executes nothing, looks like the code needs an overhaul...
Does anyone have a clue? Thanks!

Reply



Leave a Reply.

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge. 

© 2014 Kilobolt, LLC. All rights reserved.