Applet not showing image - java

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

Related

How can i move a shape forward in a certain angle in java?

I'm trying to create a game in which i can turn the rectangle around and move it forward in a certain direction or backward, when i press right it rotates clockwise and if i press left it goes counter-clockwise but i'm having this problem that if i move up or down it only rotates the same when i press right and left but i expected them to move up or down, i have looked unto other programs and tried to copy their methods but i'm still missing something out, somebody please help, thanks in advance
Here is my exact Code below:
public class Rotate extends JPanel implements ActionListener,KeyListener{
Timer t = new Timer(20,this);
boolean right=false;
boolean left=false;
boolean up=false;
boolean down=false;
Rectangle tank;
int tankx=30;
int tanky=50;
double a;
int angle;
Rotate()
{
JFrame f = new JFrame();
f.add(this);
f.addKeyListener(this);
f.setSize(1000,1000);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tank = new Rectangle(400,400,30,50);
}
public static void main(String[] args) {
new Rotate();
}
int i;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d =(Graphics2D)g;
g2d.rotate(a,tank.getWidth()+tankx/2,tank.getHeight()+tanky/2);
g.setColor(Color.red);
g.fillRect(tankx,tanky,tank.width,tank.height);
if(angle>360)
{
angle=0;
}
else if(angle<0)
{
angle=360;
}
a= Math.toRadians(angle);
System.out.println("x");
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(right==true)
{
angle+=4;
}
else if(left==true)
{
angle-=4;
}
else if(down==true)
{
angle-=4;
tank.x-=Math.cos(a);
tank.y-=Math.sin(a);
}
else if(up==true)
{
angle+=4;
tank.x+=Math.cos(a);
tank.y+=Math.sin(a);
}
repaint();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
right=true;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
left=true;
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{
up=true;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
down=true;
}
}
#Override
public void keyReleased(KeyEvent e) {
right=false;
left=false;
up=false;
down=false;
}
}
g.fillRect(tankx, tanky, tank.width, tank.height); 🤔 When does tankx or tanky actually change?
Because you're modifying the underling Graphics context on each paint cycle, you are running the risk of compounding the rotation. Better to use Graphics#create to create a snapshot of its current state and then modify that. Just remember to call Graphics#dispose on the copy
Remember, when you rotating the Graphics context, you are rotating the origin point (0x0) as well, so movement will no longer by "up" or "down", but will be relative to the angle the of rotation.
So, this is a modification of your code. I've updated the paint method (you really should be using paintComponent) so that the origin is translated to the position of the tank (this makes 0x0 the position of the tank), it then becomes much easier to rotate.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
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;
public class Rotate extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(20, this);
boolean right = false;
boolean left = false;
boolean up = false;
boolean down = false;
Rectangle tank;
int angle;
Rotate() {
JFrame f = new JFrame();
f.add(this);
f.addKeyListener(this);
f.setSize(1000, 1000);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tank = new Rectangle(400, 400, 30, 50);
t.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Rotate();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
double radian = Math.toRadians(angle);
g2d.translate(tank.x, tank.y);
g2d.rotate(radian, tank.getWidth() / 2, tank.getHeight() / 2);
g2d.setColor(Color.red);
g2d.fillRect(0, 0, tank.width, tank.height);
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
if (right == true) {
angle += 4;
System.out.println("Right");
} else if (left == true) {
angle -= 4;
System.out.println("Left");
} else if (down == true) {
angle -= 4;
double radian = Math.toRadians(angle);
tank.x -= Math.cos(radian);
tank.y -= Math.sin(radian);
System.out.println("Down: " + tank.x + "x" + tank.y);
} else if (up == true) {
angle += 4;
double radian = Math.toRadians(angle);
tank.x += Math.cos(radian);
tank.y += Math.sin(radian);
System.out.println("Up: " + tank.x + "x" + tank.y);
}
repaint();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
up = true;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
down = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
right = false;
left = false;
up = false;
down = false;
}
}
I also think you have you cos/sin around the wrong way and up should subtract and down should add - but this is solely based on observations.
You might want to have a look at:
https://gamedev.stackexchange.com/questions/36046/how-do-i-make-an-entity-move-in-a-direction
Calculate the movement of a point with an angle in java
Basic rotation and Moving toward angle direction (car movement)
for more ideas

Failing to try to change an image when keypressed

I'm trying to make it so when I press down the right key a new picture pops up making it look like my character is walking, not quite sure how to do that though... Here's my code:
import java.awt.*;
public class Dude {
int x, dx, y;
Image still;
public Dude() {
ImageIcon i = new ImageIcon("Ken3.png");
ImageIcon ii = new ImageIcon("KenTurn1.png");
still = i.getImage();
x = 50;
y = 785;
}
public void move() {
x = x + dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return still;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = -2;
if (key == KeyEvent.VK_D)
dx = 2;
if (key == KeyEvent.VK_SPACE)
dx = 5;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = 0;
if (key == KeyEvent.VK_D)
dx = 0;
Any help would be awesome thanks!
something like this, i commented it. Good luck
public class Dude {
private int walkingIndex;
private Image walkingFrames;
private Image still;
private String state;
public Dude() {
// say were starting off standing
state = "standing";
// init our still frame
still = (new ImageIcon("Ken3.png")).getImage();
// set our walking frame to 0 to start
walkingIndex = 0;
walkingFrames = new Image[3]; // or however many images you have in your walking animation
// go through each frame and initialize the image to KenWalking{index}.png
for(int i=0;i<walkingFrames.length;i++) {
walkingFrames[i] = (new ImageIcon("KenWalking"+i+".png")).getImage();
}
}
public void move() {
x+=dx;
// add 1 to the walking index and make sure its not greater than our number of walking frames, % means get the remainder of
// so 12 % 10 = 2, and 8 % 7 = 1
walkingIndex = (walkingIndex+1)%walkingFrames.length;
}
public Image getImage() {
// if our state is walking then give out a walking frame
if(state.equals("walking")) {
return walkingFrames[walkingIndex];
} else {
// otherwise we can assume were standing, so show that image instead
return still;
}
}
public void keyPressed(KeyEvent e) {
... same stuff
state = "walking";
}
public void keyReleased(KeyEvent e) {
... same stuff
state = "standing";
}
}
If i understand the question right, you are looking for a keyListener. In that case, you can do two things. Add keybindings or add an KeyListener.
Please have in mind that i haven't tested the code on your template, it work well for me in an AWT frame. Hope it helps
First implement the EventListener to Dude
public class Dude implements KeyListener{ ...
For the KeyListener to work you must have a focusable component..
component.addKeyListener(this);
component.setFocusable(true);
component.setFocusTraversalKeysEnabled(false);
The method below will be implemented with the KeyListener
#Override
public void keyPressed(KeyEvent e) {
int x = e.getKeyCode();
switch(x){
case KeyEvent.VK_UP:
// Do Your stuff
break;
case KeyEvent.VK_DOWN:
// Do Your stuff
break;
case KeyEvent.VK_RIGHT:
// Do Your stuff
break;
case KeyEvent.VK_LEFT:
// Do Your stuff
break;
}
}

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

Varying results with simplistic Java applet game [closed]

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.

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