Varying results with simplistic Java applet game [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I was following a tutorial on some basic game design for Java when I ran across an unusual issue. When I run an applet that simply moves an image based character on the screen, it will not let me use the methods to change position of the image. It raises a NullPointerException in located at my robot.update() method which handles the movement of the image. The odd part is that if I choose the "Restart" option from the drop down list in the Applet frame, it works as normal. Any ideas?
Main Class
package Game;
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 First 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);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("First Game");
addKeyListener(this);
try {
base = getDocumentBase();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Image not accessible");
}
character = getImage(base, "data/character.png");
// TODO Auto-generated method stub
super.init();
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
robot = new Robot();
// TODO Auto-generated method stub
super.start();
}
#Override
public void stop() {
// TODO Auto-generated method stub
super.stop();
}
#Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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) {
// TODO Auto-generated method stub
g.drawImage(character, robot.getCenterX() - 61,
robot.getCenterY() - 63, this);
super.paint(g);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#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;
}
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop UP");
break;
case KeyEvent.VK_DOWN:
System.out.println("Stop DOWN");
break;
case KeyEvent.VK_LEFT:
robot.stop();
break;
case KeyEvent.VK_RIGHT:
robot.stop();
break;
case KeyEvent.VK_SPACE:
robot.stop();
break;
// TODO Auto-generated method stub
}
}
}
Robot Class
package Game;
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() {
if (speedX < 0) {
centerX += speedX;
} else if (speedX == 0){
System.out.println("Do not scroll the background");
} else {
if (centerX <= 300) {
centerX += speedX;
} else {
System.out.println("Scroll background here");
}
}
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 int getCenterX() {
return centerX;
}
public void setCenterX(int centerX) {
this.centerX = centerX;
}
public int getCenterY() {
return centerY;
}
public void setCenterY(int centerY) {
this.centerY = centerY;
}
public boolean isJumped() {
return jumped;
}
public void setJumped(boolean jumped) {
this.jumped = jumped;
}
public int getSpeedX() {
return speedX;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public int getSpeedY() {
return speedY;
}
public void setSpeedY(int speedY) {
this.speedY = speedY;
}
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;
}
}
}
This is the error message I am gettings
Exception in thread "Thread-3" java.lang.NullPointerException
at Game.First.run(First.java:65)
at java.lang.Thread.run(Thread.java:722)

You should initialize robot object first not after running the thread, try:
robot = new Robot();
Thread thread = new Thread(this);
thread.start();
As when you start the thread's execution it may start with null robot.
when you again reload it works as by then it is initialized.

Related

How to make sure the player does not walk through the wall

I am programming my first actually 2D game(Pac-Man). I think game looks good,but I have one big problem - Collision. Object still going through the wall.I'm stuck with it so I decided to ask for help real programmers with great experience. (Of course I did some research, but I don't want to do things like COPY and Paste, because I didn't understand). As I said, game is almost done, just all I need to do is keep pacman from going through. Like example I draw large white rectangle as platform. I hope somebody is able to help me. Throughout this project I've learned much and collision is something which I understand, but don't know how correctly program it. I think I am close to figure it out, but something is missing.
PS: I've created window in WindowBuilder, so compiling might be a problem :(
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame implements ActionListener{
JPanel contentPane;
Rectangle packman ;
Rectangle platform;
Rectangle secondPlat;
private int count = 0;
private int x = 170, y = 50;
private int xVel = 1, yVel = 1;
Timer timer;
public static void main(String[] args) {
// TODO Auto-generated method stub
Main frame = new Main();
frame.setVisible(true);
}
public Main() {
// TODO Auto-generated constructor stub
this.setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
getContentPane().setBackground(Color.gray);
packman = new Rectangle(x,y,50,50);
platform = new Rectangle(100,70,50,100);
secondPlat = new Rectangle(220,50,50,100);
timer = new Timer(0,this);
timer.start();
this.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
switch(e.getKeyCode()) {
case 37: //doleva
count = 1;
repaint();
break;
case 38: //nahorů
count = 2;
repaint();
break;
case 39://doprava
count = 3;
repaint();
break;
case 40://dolů
count =4;
repaint();
break;
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Char" + e.getKeyCode());
System.out.println("Hod" + e.getKeyCode());
}
});
}
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawRect(x,y,packman.width,packman.height);
g.setColor(Color.blue);
g.fillRect(x,y,packman.width,packman.height);
g.drawRect(platform.x,platform.y,platform.width,platform.height);
g.setColor(Color.blue);
g.drawRect(secondPlat.x,secondPlat.y,secondPlat.width,secondPlat.height);
g.setColor(Color.blue);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (count == 1) {
x = x - xVel;
repaint();
zkontrolujKolizi();
}
if (count ==2) {
y = y - yVel;
repaint();
zkontrolujKolizi();
}
if (count ==3) {
x = x + xVel;
repaint();
zkontrolujKolizi();
}
if (count ==4) {
y = y+yVel;
repaint();
zkontrolujKolizi();
}
}
public void zkontrolujKolizi() {
// TODO Auto-generated method stub
if (packman.intersects(platform) || packman.intersects(secondPlat)) {
System.out.println("Got ya!");
}
}
}
In your code you update x and y, but this is not done in the "packman" object, that always sits at its initial position; so when you check intersection with the wall the packman is always at (170,50); I changed both the animation method to reflect the changes in packman and the paint method, so that you use the updated packman coordinates.
Animation:
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (count == 1) {
packman.x = packman.x - xVel;
repaint();
zkontrolujKolizi();
}
if (count ==2) {
packman.y = packman.y - yVel;
repaint();
zkontrolujKolizi();
}
if (count ==3) {
packman.x = packman.x + xVel;
repaint();
zkontrolujKolizi();
}
if (count ==4) {
packman.y = packman.y+yVel;
repaint();
zkontrolujKolizi();
}
}
Paint:
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawRect(packman.x,packman.y,packman.width,packman.height);
g.setColor(Color.blue);
g.fillRect(packman.x,packman.y,packman.width,packman.height);
g.drawRect(platform.x,platform.y,platform.width,platform.height);
g.setColor(Color.blue);
g.drawRect(secondPlat.x,secondPlat.y,secondPlat.width,secondPlat.height);
g.setColor(Color.blue);
}
Of course, there is much more to refactor in the code, but this is the reason why the collisions were not detected.
To avoid moving through the walls, calculate new position, check collision, if true, rollback the position changes:
#Override
public void actionPerformed(ActionEvent arg0) {
int rollbackX=packman.x;
int rollbackY=packman.y;
switch (count) {
case 1:
packman.x = packman.x - xVel;
break;
case 2:
packman.y = packman.y - yVel;
break;
case 3:
packman.x = packman.x + xVel;
break;
case 4:
packman.y = packman.y+yVel;
break;
}
//Collision found, rollback
if (zkontrolujKolizi()) {
packman.x=rollbackX;
packman.y=rollbackY;
} else {
repaint();
}
}
public boolean zkontrolujKolizi() {
return packman.intersects(platform) || packman.intersects(secondPlat);
}
before collision
after collision
I've used exactly same,but just with moving object
#Override
public void actionPerformed(ActionEvent e) {
//This is my actually code I've implemented from your answer
int rollbackX = packRect.x;
int rollbackY = packRect.y;
switch (count) {
case 1:
packman.setCoordinatesX(packman.getCoordinatesX() - xVel);
gifLabel.setLocation(packman.getCoordinatesX(), packman.getCoordinatesY()-38);
packRect.x = packRect.x - xVel;
collectPoint();
// repaint();
break;
case 2:
packman.setCoordinatesY(packman.getCoordinatesY() - yVel);
gifLabel.setLocation(packman.getCoordinatesX(), packman.getCoordinatesY()-38);
packRect.y = packRect.y - yVel;
sbirejBody();
// repaint();
break;
case 3:
packman.setCoordinatesX(packman.getCoordinatesX() + xVel);
gifLabel.setLocation(packman.getCoordinatesX(), packman.getCoordinatesY()-38);
packRect.x = packRect.x + xVel;
collectPoint();
// repaint();
break;
case 4:
packman.setCoordinatesY(packman.getCoordinatesY() + yVel);
gifLabel.setLocation(packman.getCoordinatesX(), packman.getCoordinatesY()-38);
packRect.y = packRect.y+yVel;
collectPoint();
// repaint();
break;
}
int originX = packRect.x;
int originY = packRect.y;
packRect.setLocation(originX, originY);
packman.setCoordinatesX(originX);
packman.setCoordinatesY(originY);
gifLabel.setLocation(originX, originY);
if (checkCollision) {
rollbackX= originX;
rollbackY = originY;
}else {
repaint();
}
packRect.setLocation(originX, originY);
packman.setCoordinatesX(originX);
packman.setCoordinatesY(originY);
gifLabel.setLocation(originX, originY);
}
public boolean checkCollision() {
return packman.intersects(platform) || packman.intersects(secondPlat);
}

Paint method is not working

I'm trying to make a 2D game that should draw a character to the screen. But when I run it, I just get a black screen.
The important bits:
public class StartingClass extends Applet implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
private Walrus walrus;
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("Applet");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "src/data/walrus_right.png");
}
#Override
public void start() {
walrus = new Walrus();
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) {
walrus.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, walrus.getCenterX() - 61, walrus.getCenterY() - 63, this);
}
}
Also, here's my other class:
public class Walrus {
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;
}
}
I haven't gotten any errors at this point, but it's not working right.
The problem is that your image is not loaded. The line
getImage(base, "src/data/walrus_right.png");
tries to read the image for a deployed applet and will fail quietly (not throw errors), which is what caused the confusion. Try to replace it with
ImageIO.read(new File(getClass().getResource("relative/path.png").getPath()));
where you should replace the path as specified under getResource API.
Edit:
Break the call into several calls:
Class<? extends StartingClass> clas = getClass();
URL url = clas.getResource("relative/path.png");
String path = url.getPath();
File file = new File(path);
try {
Image image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
and move with the debugger step by step to see which line throws the error. My guess is that the file is not located in the right place, which causes getResource to return null, which causes new File(path) to throw NullPointerException.

Java Applet repaint from another class

I am learning Java game development and I am having an issue understanding why the "Robot" is not moving.
I know the issue is with the repaint but I can not figure it out.
please help
Thank
Game Class
public class GameMain extends Applet implements KeyListener {
private Image image, character;
private Graphics gpx;
private Droid droid;
private URL base;
private static Background bg1, bg2;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("My First Game");
droid = new Droid();
base = getDocumentBase();
character = getImage(base, "data/char.png");
}
#Override
public void start() {
GameThread thread = new GameThread();
thread.start();
System.out.println("Thread Started");
}
#Override
public void stop() {
}
#Override
public void destroy() {
}
#Override
public void update(Graphics g) {
if(image == null){
image = createImage(this.getWidth(), this.getHeight());
gpx = image.getGraphics();
}
gpx.setColor(getBackground());
gpx.fillRect(0, 0, getWidth(), getHeight());
gpx.setColor(getForeground());
paint(gpx);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
g.drawImage(character, droid.getPositionX() - 61, droid.getPositionY()- 63, this);
}
#Override
public void keyPressed(KeyEvent key) {
switch(key.getKeyCode() ){
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
droid.moveLeft();
break;
case KeyEvent.VK_RIGHT:
droid.moveRight();
break;
case KeyEvent.VK_SPACE:
droid.jump();
break;
}
}
#Override
public void keyReleased(KeyEvent key) {
switch(key.getKeyCode() ){
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
droid.stop();
break;
case KeyEvent.VK_RIGHT:
droid.stop();
break;
case KeyEvent.VK_SPACE:
break;
}
}
#Override
public void keyTyped(KeyEvent key) {
// TODO Auto-generated method stub
}
}
Thread Class
public class GameThread extends Thread {
GameMain game;
Droid droid;
private static Background bg1, bg2;
public GameThread(){
bg1 = new Background(0,0);
bg2 = new Background(2160, 0);
}
#Override
public void run() {
game = new GameMain();
droid = new Droid();
//Game while loop
while(true){
droid.update();
game.repaint();
//bg1.update();
//bg2.update();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Droid Class
public class Droid {
private int positionX = 100;
private int positionY = 382;
private int speedX = 0;
private int speedY = 1;
private boolean jump = false;
public void update(){
//Update X Position
if(speedX < 0){
positionX += speedX;
}else if(speedX == 0){
System.out.println("Do not scroll the background.");
}else{
if(positionX <= 150){
positionX += speedX;
}else{
System.out.println("Scroll Background Here");
}
}
//Update Y Position
if(positionY + speedY >= 382){
positionY = 382;
}else{
positionY += speedY;
}
//update Jump
if(jump == true){
speedY += 1;
if(positionY + speedY >= 382){
positionY = 382;
speedY = 0;
jump = false;
}
}
}
public void moveRight(){
speedX = 6;
System.out.println(speedX);
}
public void moveLeft(){
speedX = -6;
System.out.println(speedX);
}
public void stop(){
speedX = 0;
}
public void jump(){
if(jump == false){
speedY = -15;
jump = true;
}
}
public void setPositionX(int positionX){
this.positionX = positionX;
}
public int getPositionX(){
return positionX;
}
public void setPositionY(int positionY){
this.positionY = positionY;
}
public int getPositionY(){
return positionY;
}
public void setSpeedX(int speedX){
this.speedX = speedX;
}
public int getSpeedX(){
return speedX;
}
public void setSpeedY(int speedY){
this.speedY = speedY;
}
public int getSpeedY(){
return speedY;
}
}
The problem is, the droid you're updating isn't the droid you're painting...in fact, the GameMain you're repainting isn't the one that is one the screen...
public class GameMain extends Applet implements KeyListener {
//...
private Droid droid;
//...
#Override
public void init() {
//...
droid = new Droid();
//...
}
#Override
public void paint(Graphics g) {
g.drawImage(character, droid.getPositionX() - 61, droid.getPositionY()- 63, this);
}
And then in you GameThread;
public class GameThread extends Thread {
GameMain game;
Droid droid;
//...
#Override
public void run() {
// Created a new GameMain
game = new GameMain();
// Created a new Droid...
droid = new Droid();
//Game while loop
while (true) {
droid.update();
game.repaint();
//...
You create new instances of GameMain and Droid, these have no connection what so ever to the screen.
Instead, you should be passing a reference of GameMain to the GameThread and GameThread should be telling GameMain to update the game state...
For example...
Add the method updateGameState
public class GameMain extends Applet implements KeyListener {
//...
public void updateGameState() {
droid.update();
repaint();
}
//...
Then in GameMain's start method, pass a reference of GameMain to GameThread...
GameThread thread = new GameThread(this);
thread.start();
Then in GameMain, store the reference you are passed and remove any reference to Droid
public class GameThread extends Thread {
//...
private GameMain gameMain;
public GameThread(GameMain gameMain) {
this.gameMain = gameMain;
//...
Then in GameTread#run, call gameMain.updateGameState();...
public void run() {
while (true) {
gameMain.updateGameState();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As a side note...
Applet is outdated, you should be using JApplet
I'd be very careful using this.getParent().getParent(), you may not like the results if you deployed this in a browser..
And when you start using JApplet, move you game rendering to something like JPanel, overriding it's paintComponent method, this will give you automatic double buffering and use the Key binding API over KeyListener. It's more easily, programmatically, updatable and doesn't suffer from the same focus related issues as KeyListener

Applet not showing image

I was following this tutorial here
and I downloaded its source code and ran but the image is not showing.
here is the result
I was expecting that the result would be like this
same as the result in the tutorial.
Here is the code:
StartingClass.java
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
System.out.println(e.toString());
}
// Image Setups
character = getImage(base, "data/character.png");
System.out.println(" "+base);
}
#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:
System.out.println("Jump");
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
}
}
Robot.java
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
centerY += speedY;
if (centerY + speedY >= 382) {
centerY = 382;
}
// 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;
}
}
and here is my file structure in intelij
Whats wrong with the code?? I tride the "../data/character.png" and "../src/data/character.png" but it didnt work.
applet.html the page loading the applet.
data (directory)
Character.png
If that is the structure of the server, the image will be available by:
getImage(base, "data/character.png");
I stressed server above since that is apparently not how your IDE is set up.
Can you elaborate more?
You opened the src/kilobolt path to show the locations of the source files, but it you expand the bin folder and trace down, you'll probably find the .class files in the bin/kilobolt directory.
An IDE typically won't use an HTML file for loading the applet, but if IntelliJ did, it would probably put it in the bin directory so it has direct access to the class files.
The path from there to the image would be ../data/character.png, but instead of using that path, suggest you get the IDE to copy the image into the bin.
At this stage it has become about IntelliJ so any further questions you have, will need to be about the IDE and the run-time class-path it uses.
This seems to be an image issue. The computer is not able to find the location of the image, or the image is being drawn under the applet.
IF you are using a linux/Mac/unix machine, most of time, I have had to either start from the root folder such as /Users/.....to the source folder, or when using a directory that is closer, just use '/' in front of it. Example is:
You're using a directory named src, with an 'img' folder inside. To get to the 'img' contents, you have two options:
//......src/img
or
/src/img/....
Hope that helped with anything
Copy your data folder into the bin folder.
Clean the project and run.
It will work.
#Luiggi Mendoza I had the same issue and was able to resolve it by right clicking on 'character.png' and selecting properties and then copying the image's location all the way from its root. In my case it was "/Users/macbookpro/NetBeansProjects/Kilobolt/src/data/character.png" and bingo the robot appeared in the applet window.
And yeah, i am learning game from the same website as you were 3 years back

Java Platformer Collision with Platforms

I'm in dire need of help. I've spent 3 hours pulling my hair over the fact that I don't know how to make my collision with one single platform work!
I want the player to be able to jump on the platform and not glitch on it, or fall through it. However, there is also the case that if the player holds up and the left arrow key or right arrow key and comes in contact with the edge of the platform! I really need your help on how I can make the simple aspects of collision with a platform work with my code.
Here is my code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Form1 extends Applet implements Runnable, KeyListener
{
private Image dbImage;
private Graphics dbg;
Thread t1;
int x = 300;
int y = 300;
boolean jumping = false;
double yVel = 0;
double termVel = 10;
int loop_cnt = 0;
int start_cnt = loop_cnt;
boolean falling = false;
boolean left, right, up, down;
double counter2 = 4;
int counter;
int num = 7;
int prevY = y;
int prevX = x;
int d = 0;
Rectangle player;
Rectangle platform;
public void init()
{
setSize(600, 400);
}
public void start()
{
player = new Rectangle();
platform = new Rectangle();
addKeyListener(this);
t1 = new Thread(this);
t1.start();
}
public void stop()
{
}
public void destroy()
{
}
#Override
public void run()
{
while (true)
{
//this code will be used if the player is on a platform and then walks off it by pressing either right or left
if (y <= 300 && !up)
{
y += 10;
}
if (left)
{
prevX = x;
x -= 2;
}
if (right)
{
prevX = x;
x += 2;
}
if (up)
{
counter2 += 0.05;
prevY = y;
y = y + (int) ((Math.sin(counter2) + Math.cos(counter2)) * 5);
if (counter2 >= 7)
{
counter2 = 4;
up = false;
}
}
if (y >= 300)
{
falling = false;
y = 300;
}
repaint();
try
{
t1.sleep(17);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public Rectangle IntersectPlatform()
{
return platform;
}
public void update(Graphics g)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
// initialize buffer
if (dbImage == null)
{
}
// clear screen in background
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor(getForeground());
paint(dbg);
// draw image on the screen
g.drawImage(dbImage, 0, 0, this);
}
public void paint(Graphics g)
{
String string = String.valueOf(y);
g.setColor(Color.RED);
g.fillRect(x, y, 40, 100);
player.setBounds(x, y, 40, 100);
g.setColor(Color.BLUE);
platform.setBounds(180, 300, 100, 40);
g.fillRect(180, 300, 100, 40);
g.drawString(string, 100, 100);
}
#Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
}
}
#Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
down = false;
break;
}
}
#Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}

Categories

Resources