Java Graphics NullPointerException When The Exact Same Thing Works Somewhere Else - java

I'm currently making a simple game with java Graphics and using multiple menus as well. Such as Help, Main, the Game itself, Lose, and Win. All menus have their own render functions that are called depending on the state of the game. All of the menus work, except for the 'Win' menu. There is the 'Lose' and the 'Win' menu both posted. They're pretty much the same thing but 'Win' will not work.
Render in main game:
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(GameState == STATE.Game) {
handler.render(g);
hud.render(g);
} else if(GameState == STATE.Menu) {
menu.render(g);
} else if(GameState == STATE.Help) {
help.render(g);
} else if(GameState == STATE.EndMenu) {
endMenu.render(g);
} else if(GameState == STATE.Win) {
win.render(g);
}
g.dispose();
bs.show();
}
Win:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
public class Win {
public Win(){}
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("SansSerriff", Font.BOLD, 100));
g.drawString("YOU WIN!!!", Game.WIDTH/2 - 280, Game.HEIGHT/2 - 50);
g.setFont(new Font("SansSerriff", Font.PLAIN, 60));
g.drawString("Player Again", 360, 600);
g.drawRect(250, 535, 500, 100);
}
}
Lose:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
public class EndMenu {
public EndMenu() {}
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("SansSerriff", Font.BOLD, 100));
g.drawString("YOU LOSE!!", Game.WIDTH/2 - 280, Game.HEIGHT/2 - 50);
g.setFont(new Font("SansSerriff", Font.PLAIN, 60));
g.drawString("Play Again", 360, 600);
g.drawRect(250, 535, 500, 100);
}
}
Error Message:
Exception in thread "Thread-2" java.lang.NullPointerException
at Main.Game.render(Game.java:132)
at Main.Game.run(Game.java:86)
at java.lang.Thread.run(Unknown Source)
All help is greatly appreciated. Thank you!
EDIT
Game:
package Main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 2287623113957789623L;
public static final int WIDTH = 1000, HEIGHT = WIDTH/12 * 9;
private Thread thread;
public static boolean running = false;
private Handler handler;
private HUD hud;
private Spawner spawner;
private Menu menu;
private Help help;
private EndMenu endMenu;
private Win win;
public static STATE GameState = STATE.Win;
//----------Game()----------//
//---------------------------------------------------------------------------
public Game() {
handler = new Handler();
menu = new Menu(this, handler);
help = new Help();
endMenu = new EndMenu();
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Wave", this);
hud = new HUD();
spawner = new Spawner(handler, hud);
}
//----------Game Modes----------//
//---------------------------------------------------------------------------
public enum STATE {
Menu,
Game,
Help,
EndMenu,
Win,
}
//----------start()----------//
//---------------------------------------------------------------------------
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
//----------stop()----------//
//---------------------------------------------------------------------------
public synchronized void stop() {
try {
thread.join();
running = false;
}catch(Exception e) {
e.printStackTrace();
}
}
//----------run()-----------//
//---------------------------------------------------------------------------
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();
}
//----------tick()----------//
//---------------------------------------------------------------------------
private void tick() {
if(GameState == STATE.Game) {
handler.tick();
hud.tick();
spawner.tick();
}
if(HUD.HEALTH <= 0 && HUD.HEALTH2 <= 0) {
GameState = STATE.EndMenu;
}
}
//----------render()----------//
//---------------------------------------------------------------------------
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(GameState == STATE.Game) {
handler.render(g);
hud.render(g);
} else if(GameState == STATE.Menu) {
menu.render(g);
} else if(GameState == STATE.Help) {
help.render(g);
} else if(GameState == STATE.EndMenu) {
endMenu.render(g);
} else if(GameState == STATE.Win) {
win.render(g);
}
g.dispose();
bs.show();
}
//----------clamp()----------//
//--------------------------------------------------------------------------
public static float clamp(float var, float min, float max) {
if(var >= max)
return var = max;
else if(var < min)
return var = min;
else
return var;
}
//----------main()----------//
//--------------------------------------------------------------------------
public static void main(String args[]) {
new Game();
}
}
Game.java.132: win.render(g);
Game.java.86: render();

You're getting an NPE on this line:
win.render(g);
because win is null. You've defined it, but haven't assigned a value to it.
Based on your code, you should update your Game constructor to include the following line:
win = new Win();

Related

Changing Sprite When You Press a key

I have a sprite sheet that I can change the little slimey's picture from but it only changes like the actual image I want to make them so when I press the right key it takes the pictures and gives it the one where it's facing right. I tried to get it so that it takes a int from the slime's class and uses it when I press right but it only prints the number 2 in the console but isn't changing the picture....... the stuff for the slime....
package com.maprildoll.main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Slimey extends DollObject{
Random r = new Random();
private int x;
private int y;
public int sprites = 0;
private BufferedImage slimey;
public SpriteSheet slimes;
public Slimey(ID id, int x, int y, Slimeball slimeball) {
super(x, y, id);
this.x = x;
this.y = y;
SpriteSheet slimes = new SpriteSheet(slimeball.getSpriteSheet());
slimey = slimes.grabImage(1, 1, 69, 49);
if(sprites == 2) {
slimey = slimes.grabImage(2, 1, 69, 49);
}
}
public void tick() {
x += speedX;
y += speedY;
x = Slimeball.clamp(x, 0, Slimeball.WIDTH - 82);
y = Slimeball.clamp(y, 88, Slimeball.HEIGHT - 278);
}
public void render(Graphics g) {
g.drawImage(slimey, (int)x, (int)y, null);
}
}
the main window thingy....
package com.maprildoll.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
public class Slimeball extends Canvas implements Runnable{
private static final long serialVersionUID = -2882786666891858852L;
public static final int WIDTH = 1700, HEIGHT = 900;
private Thread thread;
private boolean running = false;
private Random r;
private Handler handler;
private BufferedImage spriteSheetSlimes;
private BufferedImage spriteSheetItem = null;
private BufferedImage items;
private Slimey slimey;
public Slimeball (Slimeball slimeball){
handler = new Handler();
this.addMouseListener(new Mousey(handler));
new Windows(WIDTH, HEIGHT, "Slimeballin' >.<!!", this);
r = new Random();
handler.addObject(new Slimeyball(WIDTH/2-32, HEIGHT/2+186, ID.Slimeyball));
}
public void init() {
requestFocus();
ImageLoader loader = new ImageLoader();
try {
spriteSheetItem = loader.loadImage("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\itemsheet.png");
spriteSheetSlimes = loader.loadImage("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\slimebox.png");
}catch(IOException e) {
e.printStackTrace();
}
addKeyListener(new Slimekey(this));
SpriteSheetTew itemsheet = new SpriteSheetTew(spriteSheetItem);
items = itemsheet.grabImage(1, 1, 32, 32);
slimey = new Slimey(ID.Slime, 1040, 620, this);
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
init();
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() {
handler.tick();
slimey.tick();
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Color cyanie = new Color (231, 255, 254);
g.setColor(cyanie);
g.fillRect(0, 0, WIDTH, HEIGHT);
final ImageIcon background = new ImageIcon("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\testbackground.gif");
Image imgback = background.getImage();
g.drawImage(imgback, 0, 0, this);
g.drawImage(items, 865, 636, this);
slimey.render(g);
handler.render(g);
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
slimey.setSpeedX(-5);
} else if (key == KeyEvent.VK_RIGHT) {
slimey.setSpeedX(+5);
slimey.sprites = 2;
System.out.println(slimey.sprites);
} else if (key == KeyEvent.VK_ALT){
slimey.setSpeedY(-8);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
slimey.setSpeedX(0);
} else if (key == KeyEvent.VK_RIGHT) {
slimey.setSpeedX(0);
} else if (key == KeyEvent.VK_ALT);{
slimey.setSpeedY(+4);
}
}
public static int clamp(double x, int min, int max){
if(x >= max)
return (int) (x = max);
else if(x <= min)
return (int) (x = min);
else
return (int) x;
}
public BufferedImage getSpriteSheet() {
return spriteSheetSlimes;
}
}
I tried to put a keylistener to the Slimey but for some reason the keyboard would never work when it was in there..... soo how would I take a image from the sheet and add it to the keypressed stuff I want to put the right facing one when it presses right.....

Java game Mouse input on buttons not working

I'm trying to make mouse input work in my Java game, but i can't seem to figure it out. I want to click where i made my button and it should change my State from End to Game and respawn my player and my bullet enemies. Why does the following code not change my State to Game instead of End?
My End Class
package BullHellSpel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import BullHellSpel.Game.STATE;
public class End extends MouseAdapter{
private Game game;
private Handler handler;
private HUD hud;
private Random r = new Random();
public End(Game game, Handler handler, HUD hud){
this.game = game;
this.handler = handler;
this.hud = hud;
}
public void mouseClicked(MouseEvent e){
int mx = e.getX();
int my = e.getY();
if(game.gameState == STATE.End){
if(mouseOver(mx, my, 75, 100, 200, 70)){
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH, Game.HEIGHT, ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
}
public void mouseReleased(MouseEvent e){
}
private boolean mouseOver(int mx, int my, int x, int y, int width, int height){
if(mx < x && mx > x + width){
if(my < y && my > y + height){
return true;
}else return false;
}else return false;
}
public void tick() {
}
public void render(Graphics g) {
Font fnt = new Font("arial", 1, 20);
Font fnt1 = new Font("arial", 1, 16);
g.setColor(Color.white);
g.setFont(fnt);
g.drawString("You lost with a score of: " + hud.getScore(), 40, 50);
g.setFont(fnt1);
g.drawRect(75, 100, 200, 70);
g.drawString("Retry Game", 90, 140);
g.drawRect(75, 215, 200, 70);
g.drawString("Quit Game", 90, 255);
}
}
In my game Class:
package BullHellSpel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import sun.applet.Main;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import java.util.Random;
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 360, HEIGHT = 640 / 1;
private boolean running = false;
private Thread thread;
private Random r;
private Handler handler;
private HUD hud;
private Spawn spawner;
private End end;
private Menu menu;
public enum STATE {
End,
Menu,
Game;
};
public STATE gameState = STATE.Game;
public Game(){
handler = new Handler();
hud = new HUD();
end = new End(this, handler, hud);
menu = new Menu(this, handler, hud);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(end);
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Space dodgers", this);
spawner = new Spawn(handler, hud);
r = new Random();
if(gameState == STATE.Game){
handler.addObject(new Player(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run()
{
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(){
handler.tick();
if(gameState == STATE.Game)
{
hud.tick();
spawner.tick();
if(HUD.HEALTH <= 0){
HUD.HEALTH = 100;
handler.object.clear();
gameState = STATE.End;
}
}else if(gameState == STATE.End){
end.tick();
}else if(gameState == STATE.Menu){
menu.tick();
}
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//HIER KAN JE SHIT TEKENEN
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
//g.drawImage(bg, 0, 0, this);
handler.render(g);
if(gameState == STATE.Game)
{
hud.render(g);
}else if(gameState == STATE.End){
end.render(g);
}else if(gameState == STATE.Menu){
menu.render(g);
}
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max){
if(var >= max)
return var = max;
else if(var <= min)
return var = min;
else
return var;
}
public static void main(String args[]){
new Game();
}
}

I don't know why next statement is executed before the previous one?

My game is almost complete except for this error which has limited to proceed further. I am newbie programmer. I have the following code
class End
public class End
{
public void render(Graphics g)
{
Font font = new Font("TimesNewRoman", Font.BOLD, 15);
Font font2 = new Font("TimesNewRoman", Font.BOLD, 20);
g.setFont(font);
g.setColor(Color.CYAN);
g.setFont(font2);
g.setColor(Color.WHITE);
tex.setDead();
g.drawString("Died !", 590, 240);
g.drawImage(tex.player, 590, 250, game);
g.drawString("Survival Score: " + game.count, 530, 360);
if(game.count > FileManager.getHighScore())
{
g.setColor(Color.YELLOW);
g.drawString("Your Survival will not be forgotten !", 480, 400);
}
g.drawString("Press 'Enter' for retry...", 500, 600);
g.drawString("Press 'Space' to go Main Menu...", 460, 640);
FileManager.setHighScore(game.count);
game.resetStates();
}
}
game.resetStates is being executed (which resets score count) before displaying current score count. Although other statements working fine. What I wanted to do is to display score (Not highscore, it works fine), but it displays 1 instead of current score. NOTE: the method resetStates() resets it to 1. But i want to do it after display the score.
The main game class, where game.resetStates can be found is below
public class Game extends Canvas implements Runnable
{
public static int count = 1;
private End end;
public static enum STATE{
MENU,
SCORE,
START,
GAME,
PAUSE,
END
};
public static STATE State = STATE.MENU;
public void init()
{
requestFocus();
end = new End(this, tex);
c.createEnemy(count);
score = new Font("TimesNewRoman", Font.BOLD, 15);
}
private synchronized void start()
{
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop()
{
if(!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(1);
}
public void run()
{
//That Frame Rate stuff.
}
private void tick()
{
if(State == STATE.GAME)
{
player.tick();
c.tick();
}
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//================================
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
if(State == STATE.GAME)
{
g.drawImage(map, 0, 0, getWidth(), getHeight(), this);
player.render(g);
c.render(g);
g.drawImage(mapVision, 0, 0, getWidth(), getHeight(), this);
g.setFont(score);
g.setColor(Color.WHITE);
g.drawString("Survival: " + count, 620, 30);
g.drawString("Press 'Enter' to Pause...", 10, 710);
}
else if(State == STATE.MENU)
{
menu.render(g);
}
else if(State == STATE.SCORE)
{
hol.render(g);
}
else if(State == STATE.START)
{
start.render(g);
}
else if(State == STATE.PAUSE)
{
pause.render(g);
}
else if(State == STATE.END)
{
end.render(g);
}
//================================
g.dispose();
bs.show();
}
public void resetStates()
{
count = 1;
player.setX(640);
player.setY(360);
c.removeAllEntities();
c.createEnemy(1);
tex.setDown();
}
}
Lastly, this resetState() occurs when player intersects enemy bounding box, whose class is follow, class Enemy
public void tick()
{
y+= speed;
if(y >= (Game.HEIGHT * Game.SCALE))
{
speed = r.nextInt(3) + 2;
y = 0;
x = r.nextInt(Game.WIDTH * Game.SCALE);
game.count ++;
game.enemyArmy();
}
if(this.getBody().intersects(game.player.getBody()))
{
game.State = STATE.END;
}
}
public void render(Graphics g)
{
g.drawImage(tex.spike, x, y, null);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Rectangle getBody()
{
return new Rectangle(this.x, this.y + 10, this.tex.spike.getWidth(null), this.tex.spike.getHeight(null));
}
}
If my codes are not good, sorry for that, beginner here :P
Your render() methods are part of the code's main run() while loop. Once the game.state is changed to STATE.END your End.render() method starts looping. It is being called repeatedly which results in the resetState() being called repeatedly.
You should move any non-graphic logic out of the render() methods and handle them separately.

JAVA setColor in paintComponent stays blank

I'm trying to change the background of my little programm as soon as someone hits space (32). It just won't work and I have been trying different things and everything I could find on the internet like putting the g.setColor(Color.BLUE);
at the beginning of the public void paintComponent(Graphics g)block.
Here I got the following code.
My Screen.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable{
Thread thread = new Thread(this);
Frame frame;
private int fps = 0;
public int scene = 0;
public boolean running = false;
public Screen(Frame frame){
this.frame = frame;
this.frame.addKeyListener(new KeyHandler(this));
thread.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
super.paint(g);
g.clearRect(0, 0, this.frame.getWidth(),this.frame.getHeight());
g.drawString(fps + "", 10, 10);
if (scene == 0) {
g.setColor(Color.BLUE);
} else if (scene == 1) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.white);
}
g.fillRect(0, 0, getWidth(), getHeight());
}
public void run() {
System.out.println("[Success] Frame Created!");
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
scene = 0;
while(running){
repaint();
frames++;
if(System.currentTimeMillis() - 1000 >= lastFrame){
fps = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
try {
Thread.sleep(2);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.exit(0);
}
public class KeyTyped{
public void keySPACE() {
scene = 1;
}
public void keyESC(){
running = false;
}
}
}
KeyHandler.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener {
public Screen screen;
public Screen.KeyTyped keyTyped;
public KeyHandler(Screen screen){
this.screen = screen;
this.keyTyped = this.screen.new KeyTyped();
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
if(keyCode == 27){
this.keyTyped.keyESC();
}
if(keyCode == 32){
this.keyTyped.keySPACE();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
I don't know why the code isn't in one block. Seems like I'm doing something wrong with it?
You should use InputMap / ActionMap instead of a KeyListener
You need to make sure the JComponent is set to isFocusable(true), and you do component.requestFocus() when first shown to make sure that your action will trigger.
please do the corrections:
1. use JFrame instead of Frame
2. implemement paintComponent like this:
g.clearRect(0, 0, this.frame.getWidth(),this.frame.getHeight());
if (scene == 0) {
g.setColor(Color.BLUE);
} else if (scene == 1) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.white);
}
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
g.drawString(fps + "", 10, 10);
3. make sure Screen is added JFrame
4. make sure to issue setVisible(true) on JFrame

Getting my sprite to face in a certain direction based on Keyboard input - Java Game

So I've pretty much thrown together a basic game in java by following a bunch of different tutorials - the problem is i cant manage to figure out how to get my sprite to move in different directions. Here is the code for my main
package com.game.src.main;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 850;
public static final int HEIGHT = 650;
public static final int SCALE = 1;
public final String TITLE = "Racing Game!";
static ServerSocket serverSocket;
static Socket socket;
static DataOutputStream out;
private boolean running = false;
private Thread thread;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
private BufferedImage spriteSheet = null;
private BufferedImage spriteSheet2 = null;
private BufferedImage background = null;
private BufferedImage MenuBackground = null;
private Player p;
private Player2 p2;
private Menu menu;
public static enum STATE {
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/Sprite_Sheet.png");
background = loader.loadImage("/Track.png");
MenuBackground = loader.loadImage("/MenuBG.fw.png");
}
catch (IOException e) {
e.printStackTrace();
}
menu = new Menu();
addKeyListener(new KeyInput(this));
this.addMouseListener(new MouseInput());
p = new Player(365, 500, this);
p2 = new Player2(365, 550, this);
}
private synchronized void start() {
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop() {
if(!running)
return;
running = false;
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1) {
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " FPS, TICKS " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
private void tick() {
if(State == STATE.GAME){
p.tick();
p2.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.drawImage(MenuBackground, 0, 0, null);
if(State == STATE.GAME){
//Drawing the main games background
g.drawImage(background, 0, 0, null);
p.render(g);
p2.render(g);
}
else if(State == STATE.MENU){
menu.render(g);
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(State == STATE.GAME){
if(key == KeyEvent.VK_RIGHT){
p.setVelX(5);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(5);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(-5);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(-5);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(5);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(5);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(-5);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(-5);
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT){
p.setVelX(0);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(0);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(0);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(0);
}
}
public static void main(String args[]) throws Exception {
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
System.out.println("Starting server....");
serverSocket = new ServerSocket(7777);
System.out.println("Server started");
socket = serverSocket.accept();
System.out.println("Connecting from: " + socket.getInetAddress());
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("This is a test of Java Sockets");
System.out.println("Data has been sent");
}
public BufferedImage getSpriteSheet() {
return spriteSheet;
}
public BufferedImage getSpriteSheet2() {
return spriteSheet2;
}
}
This is my player class
package com.game.src.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class Player {
private double x;
private double y;
private double velX = 0;
private double velY = 0;
private BufferedImage player;
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage SpriteSheet = null;
public Player(double x, double y, Game game) {
this.x = x;
this.y = y;
//New instance of Sprite sheet - reading from buffered image loader
SpriteSheet ss = new SpriteSheet(game.getSpriteSheet());
player = ss.grabImage(1, 1, 50, 50);
try {
SpriteSheet = loader.loadImage("/Sprite_Sheet.png");
}
catch(Exception e) {
e.printStackTrace();
}
}
public void tick() {
x+=velX;
y+=velY;
//Adding basic collision
if(x < 0 + 50) {
x = 0 + 50;
}
if(x >= 850 - 100) {
x = 850 - 100;
}
if(y < 0 + 100) {
y = 0 + 100;
}
if(y >= 650 - 100){
y = 650 - 100;
}
}
public void render(Graphics g){
//Draw Track
Color c1 = Color.green;
g.setColor( c1 );
g.fillRect( 150, 200, 550, 300 ); //grass
Color c2 = Color.black;
g.setColor( c2 );
g.drawRect(50, 100, 750, 500); // outer edge
g.drawRect(150, 200, 550, 300); // inner edge
Color c3 = Color.yellow;
g.setColor( c3 );
g.drawRect( 100, 150, 650, 400 ); // mid-lane marker
Color c4 = Color.white;
g.setColor( c4 );
g.drawLine( 425, 500, 425, 600 ); // start line
g.drawImage(player, (int)x, (int)y, null);
}
public double getX(Graphics g){
return x;
}
public double getY(){
return y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public void setVelX(double velX){
this.velX = velX;
}
public void setVelY(double velY){
this.velY = velY;
}
}
I have two players in this game but i'm really stuck on how i can change the sprites direction by 22.5% in a desired direction so if i pressed the up key for player 1 it would rotate my car 22.5% north etc. I have a sprite sheet with 16 sprites for each player for every change in angle by 22.5% This is really confusing me and i'm not sure how i can implement this,
Thanks for taking the time to look
This is a basic example of spinning a sprite
What this is maintain's a virtual state which the Player object inspects in order to determine how it should be changed accordingly. This separates the action from the result, meaning that it would be possible to substitute the action (arrow up key) with some other action, but still obtain the same result.
This example also uses the key bindings API, which doesn't suffer from the same focus related issues that KeyListener does, but this is a pure Swing API and won't be compatiable with Canvas, but is a nice demonstration ;)
The real magic occurs in the characters paint method...
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
Basically, this creates a AffineTransformation which is then compounded to produce the result we need. That is, first it's anchor position is translated to the characters x/y position and then rotated about the characters center point. Because it's been translated, we can simply paint the character at 0x0. This much easier then try to calculate the characters rotation anchor somewhere else in virtual space - IMHO
The character is rotated by pressing either the Up or Down arrow keys. While pressed, the character will continue to rotate, this is a feature of the example for demonstration purpose.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RotateCharater {
public static void main(String[] args) {
new RotateCharater();
}
public RotateCharater() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultState state;
private Player player;
public TestPane() {
player = new Player();
state = new DefaultState();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "upKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "upKeyReleased");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "downKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "downKeyReleased");
ActionMap am = getActionMap();
am.put("upKeyPressed", new UpKeyAction(state, true));
am.put("upKeyReleased", new UpKeyAction(state, false));
am.put("downKeyPressed", new DownKeyAction(state, true));
am.put("downKeyReleased", new DownKeyAction(state, false));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
player.update(state);
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
player.paint(g2d);
g2d.dispose();
}
public class UpKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public UpKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setUpKeyPressed(pressed);
}
}
public class DownKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public DownKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setDownKeyPressed(pressed);
}
}
}
public interface State {
public boolean isUpKeyPressed();
public boolean isDownKeyPressed();
}
public class DefaultState implements State {
private boolean upKeyPressed;
private boolean downKeyPressed;
public boolean isDownKeyPressed() {
return downKeyPressed;
}
public boolean isUpKeyPressed() {
return upKeyPressed;
}
public void setDownKeyPressed(boolean downKeyPressed) {
this.downKeyPressed = downKeyPressed;
upKeyPressed = false;
}
public void setUpKeyPressed(boolean upKeyPressed) {
this.upKeyPressed = upKeyPressed;
downKeyPressed = false;
}
}
public class Player {
private BufferedImage character;
private int x = 100 - 32, y = 100 - 32;
private double angle;
public Player() {
try {
character = ImageIO.read(getClass().getResource("/Character.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
public void update(State state) {
if (state.isUpKeyPressed()) {
angle -= 22.5;
} else if (state.isDownKeyPressed()) {
angle += 22.5;
}
}
}
}
Remember, this is just an example used to present the concept ;)

Categories

Resources