Having trouble animating my player character, and other animated objects - java

Before I start, here is my UML diagram:
I'm trying to animate my player's character, of a gif but split into 5 separate png files. I'd rather work when the 5 frames directly because it's not a detailed image, just an 8-bit character sprite. Also, don't know how to use many Photo editing software, so I'm using the separate files themselves.
I've tried quite a few examples off Stack Overflow and other tutorials but nothing seems to match what I'm trying to do on the framework I have to build for my game. It's for an end of semester project but I'm planning to build upon in after the due date and keep it open source.
Here is some of my code.
Driver. Loads the game loop and other functions.
package cactus;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Driver extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
private Thread t;
private boolean running;
private Controller controller;
public Driver() {
controller = new Controller();
/*--- Add Game Objects ---------------------------------------*/
controller.addObject(new Travis(500, 675, ID.Travis));
/*------------------------------------------------------------*/
}
public synchronized void start() {
t = new Thread(this);
t.start();
running = true;
}
public synchronized void stop() {
try {
t.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
if(running) {
render();
}
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS:" + frames);
frames = 0;
}
}
stop();
}
private void tick() {
controller.tick();
}
private void render() {
BufferStrategy buffer = this.getBufferStrategy();
if (buffer == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = buffer.getDrawGraphics();
g.drawImage(background.getCurrentBG(), 0, 0, Frame.getWidth(), Frame.getHeight(), null);
controller.render(g);
g.dispose();
buffer.show();
}
public static void main(String[] args) {
new Driver();
}
}
Controller. Loops through game objects to execute some of their render functions, which displays what they look like, and their tick functions which controls their locations and some future actions.
package cactus;
import java.awt.Graphics;
import java.util.LinkedList;
public class Controller {
LinkedList<Objects> gameObj = new LinkedList<Objects>();
public void tick() {
for (int i = 0; i < gameObj.size(); i++) {
Objects currentObject = gameObj.get(i);
if (currentObject.getId() == ID.ShootFire && currentObject.getX() > Frame.getWidth() + 30) {
removeObject(currentObject);
System.out.println("Fire Object Removed");
}
currentObject.tick();
}
}
public void render(Graphics g) {
for (int i = 0; i < gameObj.size(); i++) {
Objects currentObject = gameObj.get(i);
currentObject.render(g);
}
}
public void addObject(Objects o) {
this.gameObj.add(o);
}
public void removeObject(Objects o) {
this.gameObj.remove(o);
}
}
Player class. Gets methods from Abstract Objects class
package cactus;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
// import javax.swing.Timer;
public class Travis extends Objects implements ActionListener{
ArrayList<BufferedImage> animation;
// Timer animationTimer;
Graphics g;
// int i = 0;
public Travis(int x, int y, ID id) {
super(x, y, id);
this.animation = createAnimation();
// this.animationTimer = createTimer(animationTimer);
// animationTimer.start();
}
private synchronized ArrayList<BufferedImage> createAnimation() {
animation = new ArrayList<BufferedImage>();
for (int i = 0; i < 6; i++) {
try {
animation.add(ImageIO.read(new File("./src/resources/image/travis/frame_" + i + ".png")));
} catch (IOException e) {e.printStackTrace(); System.exit(0);}
}
return animation;
}
// private synchronized Timer createTimer(Timer animationTimer) {
// animationTimer = new Timer(15, this);
// animationTimer.setDelay(15*1000);
// return animationTimer;
// }
#Override
public void tick() {
x += velocityX;
}
/*
* drawImage(img, posX, posY, observe [null])
*
* (non-Javadoc)
* #see cactus.GameObjects#render(java.awt.Graphics)
*/
#Override
public void render(Graphics g) {
for (int i = 0; i < 6; i++) {
g.drawImage(animation.get(i), x, y, null);
}
if (i == 6)
i = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
I want each object of the ArrayList (although likely will change it to Map), to play with different delays between frames.
* frame_0: 1s
* frame_1: 2s
* frame_2: 2s
* frame_3: 1s
* frame_4: 2s
* frame_5: 5s
I've tried using Timer and some other things and I'm not able to animate it, it just displays the last frame.
I don't have enough rep to post photographs.

The simplest approach is to yield the rendering thread by sleeping it for a few milliseconds between frames:
private static final long PERIOD = 1000 / FRAMES_PER_SECOND;
...
long now = System.currentTimeMillis();
while(running) {
// Perform frame
...
// Wait for next frame
now += PERIOD;
final long duration = now - System.currentTimeMillis();
if(duration > 0) {
Thread.sleep(duration);
}
}
where FRAMES_PER_SECOND is the desired number of frames-per-second.
You could also add a counter to calculate the frame-rate if required.
There are lots of other (and better) ways of creating a render loop but this should do as a starter.

Related

Getting java.io.IOException: closed whenever I close my program

Every time I Run my program it runs fine. But when I close it after running the program for a few seconds, then I get the java.io.IOException: closed error. I've tried looking around and couldn't find a solution. The only fix I could find was just not using the e.printstacktrace in the try-catch block, but that obviously doesn't fix the issue. Here is the Code:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = -661485289446387445L;
private Thread thread;
public int blackPos;
public int whitePos;
public boolean isWhiteTurn; // In single player this determines board orientation, in multiplayer it doesn't
public boolean running;
public final int HEIGHT = 800;
public final int WIDTH = 1200;
//public File[] imgSrc = {new File("/images/urBoard.png"), new File("/rsc/urBackground.jpg")};
public BufferedImage[] img = new BufferedImage[2];
public Board board;
public Main() {
new Window(WIDTH, HEIGHT, this);
board = new Board(this);
}
public void run()
{
requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0D;
double ns = 1.0E9D / amountOfTicks;
double delta = 0.0D;
long timer = System.currentTimeMillis();
int frames = 0;
while (this.running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1.0D)
{
tick();
delta -= 1.0D;
}
if (this.running) {
render();
}
frames++;
if (System.currentTimeMillis() - timer > 1000L)
{
timer += 1000L;
System.out.println("FPS: " + frames);
frames = frames;
frames = 0;
}
}
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running=true;
}
public synchronized void stop() {
try
{
this.thread.join();
this.running = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void tick() {
board.tick();
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
try {
img[0] = ImageIO.read(getClass().getResource("/rsc/urBoard.png"));
img[1] = ImageIO.read(getClass().getResource("/rsc/urBackground.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img[1], 0, 0, WIDTH, HEIGHT, null);
g.setColor(Color.GREEN);
g.drawLine(200, 0, 200, 800);
g.setFont(new Font("times new roman", Font.BOLD, 30));
g.drawString("END PIECES", 10, 30);
board.render(g);
g.dispose();
bs.show();
}
public static void main(String[] args) {
new Main();
}
}
and here is the error that I get whenver I close the GUI after it has ran for a couple seconds:
java.io.IOException: closed
at javax.imageio.stream.ImageInputStreamImpl.checkClosed(ImageInputStreamImpl.java:110)
at javax.imageio.stream.ImageInputStreamImpl.close(ImageInputStreamImpl.java:857)
at javax.imageio.stream.FileCacheImageInputStream.close(FileCacheImageInputStream.java:250)
at javax.imageio.ImageIO.read(ImageIO.java:1451)
at javax.imageio.ImageIO.read(ImageIO.java:1400)
at main.Main.render(Main.java:99)
at main.Main.run(Main.java:54)
at java.lang.Thread.run(Thread.java:745)
I've noticed that if I close the window right after i start the program the error doesn't come. It only comes when I've run the program for about 3-4 seconds, and then I close the window. What would cause this to happen, and what would be the fix?
It looks like your render() method may be running when closing the app. As your resources aren't changing between render() calls, move this block to the start of the Main() constructor so that img[] is set up once, and throws an exception if resources are not found:
try {
img[0] = ImageIO.read(getClass().getResource("/rsc/urBoard.png"));
img[1] = ImageIO.read(getClass().getResource("/rsc/urBackground.jpg"));
} catch (IOException e) {
throw new RuntimeException("Could not find resources");
}
The field running is used in different threads so it should be marked volatile in order that each thread reads consistent values:
public volatile boolean running;

My Mouse Listener Still Wont work?

I made a thread previously that fixed one of the issues why this doesnt work
But why doesnt my mouse listener work now? I try implementing / extending Mouse listener and added and removed #Override to the methods to see if that works and it doesnt.. I have 2 classes and i tried using one, but neither works.
Any ideas?
Am i needing to do something else that im not seeing?
Thanks
Class 1:
package Sound;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class JSound extends JFrame {
//IDK what its for but its important for jframe
private static final long serialVersionUID = 3314065768834871224L;
//Gets General volume
public static double volume = Audio.getMasterOutputVolume()*3*100;
//Universal variables are static, and i usually put them here
public static boolean running = true;
public static String title = "Advanced Java Sound";
public static int width = 410;
public static int height = 600;
public static int ticks = 1;
public static int[] background;
public MouseInput mouseinput;
public JSound() {
//initialises mouse input
//setTitle("Simple Frame");
System.out.println("Initialising Mouse Listener");
Display.frame.addMouseListener(mouseinput);
}
public static void main(String args[]) {
//Creates the display basicly just the empty window you will see all the stuff drawn to
Display.Window();
//Calls the main loop method
//SoundLoad();
//addMouseListener(sound);
new JSound();
mainloop();
}
public static void mainloop() {
render.quickrender();
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
while(running) {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
ticks++;
delta--;
}
if (running)
tick();
render.renderer();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
if (ticks <= 10000) {
System.out.println("FPS: " + frames + " Ticks: " + ticks);
} else {
System.out.println("FPS: " + frames);
}
frames = 0;
}
}
}
}
public static void tick() {
//Put any tick method stuff here, it will be executed in priority to render, and will occur more then 60 times per second
//Audio.setMasterOutputVolume(0.5f);
volume = Audio.getMasterOutputVolume()*4.8*100;
//System.out.println(Audio.getMasterOutputVolume());
//System.out.println((int)volume);
}
}
Class 2:
package Sound;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput extends MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
}
public void mouseEntered(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
}
public void mouseExited(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
}
public void mousePressed(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
System.out.println(e.getX());
System.out.println(e.getY());
}
public void mouseReleased(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
}
}

Android studio 2d game fps issue

I am trying do develop may first android game in 2d. I intend to build it from scratch without the use of an engine. I have manage to create the following thread:
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class MainThread extends Thread {
private int FPS = 30;
private double averageFPS;
private GamePanel gamePanel;
private SurfaceHolder surfaceHolder;
private boolean running;
public static Canvas canvas;
public MainThread(SurfaceHolder surfaceHolder, GamePanel gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
#Override
public void run() {
long startTime;
long timeMillis;
long waitTime;
long totalTime = 0;
int frameCount = 0;
// how many milliseconds it take to run through the loop
long targetTime = 1000 / FPS;
while (running) {
startTime = System.nanoTime();
canvas = null;
// try to lock the canvas for pixel editing
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
// the main game loop
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
} catch (Exception e) {
} finally {
if (canvas != null) {
try {
surfaceHolder.unlockCanvasAndPost(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
}
timeMillis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMillis;
try {
System.out.println(waitTime);
this.sleep(waitTime);
} catch (Exception e) {
}
totalTime += System.nanoTime() - startTime;
frameCount++;
if (frameCount == FPS) {
averageFPS = 1000 / ((totalTime / frameCount) / 1000000);
frameCount = 0;
totalTime = 0;
System.out.println(averageFPS);
}
}
}
The problem I have is that the averageFPS keeps dropping when adding stuff to my game. With only the background it works at 30 on my Nexus 5 but upon adding character and obstacles it drops to 22-21.
Is there anyway I can do to optimize this ?
Thank you
UPDATE: my GamePanel looks like this:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.Random;
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
public static final int WIDTH = 1920;
public static final int HEIGHT = 1080;
public static float MOVESPEED = -12;
private Random rand = new Random();
private MainThread thread;
private Background bg;
private Treadmill tm;
private Player player;
private ArrayList<Box> boxes;
private int minDistance = 600;
private int score;
public GamePanel(Context context) {
super(context);
// add callback service to the holder to intercept events
getHolder().addCallback(this);
// make gamePanel focusable so it can handle events
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.setRunning(false);
thread.join();
retry = false;
thread = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// instantiate objects
thread = new MainThread(getHolder(), this);
bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.background));
tm = new Treadmill(BitmapFactory.decodeResource(getResources(), R.drawable.ground));
player = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.character));
boxes = new ArrayList<Box>();
//start game loop
thread.setRunning(true);
thread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (player.jump == false) {
player.setVelocity(-14f);
player.setJump(true);
}
return true;
}
return super.onTouchEvent(event);
}
public void update() {
bg.update();
tm.update();
player.update();
if (boxes.size() == 0) {
boxes.add(new Box(BitmapFactory.decodeResource(getResources(), R.drawable.box),
WIDTH));
} else if (boxes.get(boxes.size() - 1).getX() < WIDTH) {
if (WIDTH - boxes.get(boxes.size() - 1).getX() < minDistance) {
boxes.add(new Box(BitmapFactory.decodeResource(getResources(), R.drawable.box),
rand.nextInt(400 - 50) + WIDTH + minDistance));
}
}
for (int i = 0; i < boxes.size(); i++) {
if (boxes.get(i).getX() <= player.getX() && boxes.get(i).getX() >= player.getX() - 12) {
score++;
MOVESPEED -= 0.2;
System.out.println(MOVESPEED);
}
if (collision(boxes.get(i), player)) {
boxes.remove(i);
break;
}
if (boxes.get(i).getX() < -100) {
boxes.remove(i);
break;
}
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).update();
}
}
#Override
public void draw(Canvas canvas) {
final float scaleFactorX = getWidth() / (WIDTH * 1.f);
final float scaleFactorY = getHeight() / (HEIGHT * 1.f);
if (canvas != null) {
final int saveState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
// draw the background
bg.draw(canvas);
tm.draw(canvas);
player.draw(canvas);
for (Box bx : boxes) {
bx.draw(canvas);
}
drawText(canvas);
canvas.restoreToCount(saveState);
}
}
public boolean collision(GameObject a, GameObject b) {
if (Rect.intersects(a.getRectangle(), b.getRectangle())) {
return true;
}
return false;
}
public void drawText(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(50);
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
canvas.drawText("Score: " + (score), 15, HEIGHT - 20, paint);
}
Thank you for all the help so far
The problem doesn't seem to be in the Main Thread Activity, you followed tutorial fine (Except for the line - System.out.println(waitTime); - but i don't think thats the problem cause.)
The problem is most likely in the GamePanel. ;)
Don't ever use Thread.sleep() in game loops. It is not guaranteed to sleep for the specified amount of time.
Anyway, I think that this is pretty much expected behaviour when using Canvas. If I were you I'd consider using OpenGL ES for anything like graphics rendering. Definitely, this makes it much more complex (even though Android has a lot of things already done for you). But the benefit is quite obvious - you get actual real-time graphics performance.

JPanel not rendering when added to other JPanel

This is my Game Class:
package Game;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel implements Runnable {
Thread thread;
private boolean running = true;
private double FPS = 1.0/60.0;
private Level level;
public Game(){
level = new LevelOne();
level.setBackground(Color.BLACK);
add(level);
}
public synchronized void start() {
thread = new Thread(this, "Game");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
double firstTime = 0;
double lastTime = System.nanoTime() / 1000000000.0;
double passedTime = 0;
double updateTime = 0;
double timer = System.nanoTime() / 1000000000.0;
int rendered = 0;
int updates = 0;
while (running) {
firstTime = System.nanoTime() / 1000000000.0;
passedTime = firstTime - lastTime;
lastTime = firstTime;
updateTime += passedTime;
while(updateTime > FPS){
updates++;
update();
updateTime -= FPS;
}
render();
rendered++;
if((System.nanoTime() / 1000000000) - timer > 1){
timer += 1;
System.out.println("FPS:"+rendered+" Updates:"+updates);
updates = 0;
rendered = 0;
}
}
}
private void update() {
}
private void render() {
this.repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
level.repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLocationRelativeTo(null);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setTitle("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Game game = new Game();
frame.add(game);
game.start();
}
}
My LevelOne class:
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LevelOne extends Level {
private BufferedImage spriteSheet;
private BufferedImage[] player = new BufferedImage[4]; //0 = down, 1 = right, 2 = up, 3 = left
private int dir = 0;
private String UP = "W";
private String DOWN = "S";
private String LEFT = "A";
private String RIGHT = "D";
private int speedX = 0;
private int speedY = 0;
public LevelOne(){
try {
spriteSheet = ImageIO.read(new File("images/sprites.png"));
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 4; i++) {
player[i] = spriteSheet.getSubimage((i * 18), 0, 18, 28);
}
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
String key = e.getKeyText(e.getKeyCode());
if (key.equals(UP)) {
dir = 2;
speedY = -5;
} else if (key.equals(LEFT)) {
dir = 3;
speedX = -5;
} else if (key.equals(RIGHT)) {
dir = 1;
speedX = 5;
} else if (key.equals(DOWN)) {
dir = 0;
speedY = 5;
}
}
#Override
public void keyReleased(KeyEvent e) {
String key = e.getKeyText(e.getKeyCode());
if (key.equals(UP)) {
speedY = 0;
} else if (key.equals(LEFT)) {
speedX = 0;
} else if (key.equals(RIGHT)) {
speedX = 0;
} else if (key.equals(DOWN)) {
speedY = 0;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(player[dir], 0, 0, 18, 28, null);
}
}
LevelOne extends Level, which is currently empty(And extends JPanel), I'm not sure if I need to add anything to Level. I just dont get what I need to do to make the player image show up...
And sorry if my code is sloppy, I'm trying to get into higher level Java, and im not sure if I am just approaching it wrong.
Thanks.
Six things...
Don't call level.repaint from within the paintComponent method of Game, this could cause an infinite loop of repaint requests which is going to screw with your frame rate. Consider calling it within your render method
paintComponent should never public, there's no reason for anybody to ever call it directly.
Use key bindings over KeyListener, they will solve focus related issues. How to Use Key Bindings
Move frame.setVisible AFTER frame.add(game);, in fact, it really should the last thing you do
Make sure your images are loading properly
Set the layout manager for Game to BorderLayout

I'm getting Thread [main] (Suspended (entry into method <init> in Game)) and I can't find the error anywhere

Thread [main] (Suspended (entry into method <init> in Game))
Game.<init>() line: 36
Game.main(String[]) line: 134
I keep receiving this error for some reason and I can't figure it out. all help appreciated
It says that there is some sort of error with the public Game() { and the new Game().start(); and I just can't find it
Here's my Game file:
package ca.vanzeben.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import ca.vanzeben.game.gfx.Screen;
import ca.vanzeben.game.gfx.SpriteSheet;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH /12*9;
public static final int SCALE = 3;
public static final String NAME = "Wake Me Up...";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH,HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
private Screen screen;
public Game() {
setMinimumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void init() {
screen = new Screen(WIDTH,HEIGHT, new SpriteSheet("/SpriteSheet.png"));
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
init();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime)/nsPerTick;
lastTime = now;
boolean ShouldRender = true;
while (delta >= 1) {
ticks++;
tick();
delta -= 1;
ShouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ShouldRender) {
frames++;
render();
}
if (System.currentTimeMillis()- lastTimer >= 1000){
lastTimer += 1000;
System.out.println(ticks+ "," +frames);
frames = 0;
ticks = 0;
}
}
}
public void tick() {
tickCount++;
for (int i = 0; i <pixels.length; i++) {
pixels[i] = i + tickCount;
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.render(pixels, 0, WIDTH);
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(),null);
g.dispose();
bs.show();
}
public static void main(String[] args){
new Game().start();
}
As I said, all help appreciated. It keeps saying that there's an error and I can't find it
You are using Eclipse, right?
You don't have an error, just a method entry breakpoint. Check the left bar beside the code. There will be a blue circle, with a tick and an arrow.
You have multiple options:
Double click that, it should go away (and restart execution, of course)
Right click, toggle: breakpoint goes away
Right click, disable: the breakpoint will be there, but not active
Instead of Debug (the green buggy button), use Run (green play button) -- breakpoints stay where they are, but not taken into acccount
pressing F8: breakpoints stay where they are, execution continues until next breakpoint
This does not look like an error. You are running your application inside a debugger or similar development tool which seems to be instructed to suspend your program at the specified location either by a breakpoint or a rule like “stop at instance creation”.
You should check your environment. Running with a plain java launcher does not produce such an error.

Categories