Im trying to create and RPG game based on the youtube series from TheBennyBox, and so far I have 8 classes, which are supposed to display a square with openGL and able to move the square around, although my square is not shwoing up on the screen. Here's my code for the important classes:
Main:
package com.base.engine;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import com.base.game.Game;
import static org.lwjgl.opengl.GL11.*;
public class Main {
private static Game game;
public static void main(String[] args){
initDisplay();
initGL();
initGame();
gameLoop();
}
private static void gameLoop(){
while(!Display.isCloseRequested()){
getInput();
update();
render();
}
}
private static void initGame(){
game = new Game();
}
private static void render() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
Display.update();
Display.sync(60);
game.render();
}
private static void update() {
game.update();
}
private static void getInput() {
game.getInput();
}
private static void initGL(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_DEPTH_TEST);
glClearColor(0,0,0,0);
}
private static void cleanUp(){
Display.destroy();
Keyboard.destroy();
}
private static void initDisplay(){
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
Keyboard.create();
Display.setVSyncEnabled(true);
} catch (LWJGLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null,ex);
}
}
}
Game:
package com.base.game;
import java.util.ArrayList;
import org.lwjgl.opengl.Display;
import com.base.engine.GameObject;
import com.base.game.gameobject.Player;
public class Game {
private ArrayList<GameObject> objects;
private Player player;
public Game(){
objects = new ArrayList<GameObject>();
player = new Player(Display.getWidth()/2-Player.SIZE/2,Display.getHeight()/2-Player.SIZE/2);
objects.add(player);
}
public void getInput(){
player.getInput();
}
public void update(){
for(GameObject go : objects){
go.update();
}
}
public void render(){
for(GameObject go : objects){
go.render();
}
}
}
GameObject:
package com.base.engine;
import static org.lwjgl.opengl.GL11.*;
public abstract class GameObject {
protected float x;
protected float y;
protected float sx;
protected float sy;
protected Sprite spr;
public void update(){
}
public void render(){
glPushMatrix();
{
glTranslatef(x,y,0);
spr.render();
}
glPopMatrix();
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getSx(){
return spr.getSx();
}
public float getSy(){
return spr.getSy();
}
protected void init(float x,float y,float r, float g, float b, float sx, float sy){
this.x=x;
this.y=y;
this.spr = new Sprite(r,g,b,sx,sy);
}
}
Sprite:
package com.base.engine;
import static org.lwjgl.opengl.GL11.*;
public class Sprite {
private float r;
private float g;
private float b;
private float sx;
private float sy;
public Sprite(float r,float g,float b,float sx,float sy){
this.g=g;
this.r=r;
this.b=b;
this.sx=sx;
this.sy=sy;
}
public void render() {
glColor3f(r,g,b);
glBegin(GL_QUADS);
{
glVertex2f(0,0);
glVertex2f(0,sy);
glVertex2f(sx,sy);
glVertex2f(sx,0);
}
glEnd();
}
public float getSx(){
return sx;
}
public float getSy(){
return sy;
}
public void setSx(float sx){
this.sx = sx;
}
public void setSy(float sy){
this.sy=sy;
}
}
Player:
package com.base.game.gameobject;
import org.lwjgl.input.Keyboard;
import com.base.engine.GameObject;
import com.base.engine.Sprite;
public class Player extends GameObject{
public static final float SIZE = 32;
public Player(float x, float y){
init(x,y,0.1f,1f,0.25f,SIZE,SIZE);
}
public void getInput(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
move(0,1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)){
move(0,-1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)){
move(-1,0);
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
move(0,1);
}
}
private void move(float magX,float magY){
x += getSpeed()-magX;
y += getSpeed()-magY;
}
public float getSpeed(){
return 4f;
}
}
And there are others but these are the most important. Sorry for so much code..i just don't know whats going wrong.
I'm not an expert on LWJGL, bit normally you call the sync functions after you rendered. The way it's currently written I presume that you draw the picture after buffer swap (i.e. after contents of the framebuffer were sent to the screen) but the next render iteration will clear it. Try reordering a few things:
private static void render() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
game.render();
Display.update();
Display.sync(60);
}
Note that a lot of other things skewed as well. The standard preamble of a frame render iteration is setting up the viewport and the projection. I.e. the whole code in your initGL belongs at the begin of render.
Related
I'm a beginner in libGdx and I'm making a simple game.
I wrote a nested class. As you can see here:
public class classes{
public class GameObject{
//declaring section
private Texture texture;
private Texture[] spawnAnimation;
private Texture[] deathAnimation;
private Texture[] damageAnimation;
private Texture[] moveAnimation;
private Texture[] fightAnimation;
private Texture[] talkAnimation;
private SpriteBatch batch = new SpriteBatch();
private float width, height;
private float x, y;
private Sound spawnSound, touchSound, deathSound, objSound, moveSound, fightSound;
public GameObject(Texture txtr, float width, float height, float x, float y) {
this.texture = txtr;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
//this method checks wether our game object is over an other object
public boolean isOver(GameObject obj){
if(((this.x >= obj.x) && (this.x <= (obj.x + obj.width))) && ((this.y >= obj.y) && (this.y <= (obj.y + obj.height))))
return true;
return false;
}
//this method sets the object bounds
public void setBounds(float width, float height, float x, float y){
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
//this method draws the object
public void draw(){
batch.draw(this.texture, this.width, this.height, this.x, this.y);
}
//animation setting section
public void setSpawnAnimation(Texture[] texture){
this.spawnAnimation = texture;
}
public void setDeathAnimation(Texture[] texture){
this.deathAnimation = texture;
}
public void setDamageAnimation(Texture[] texture){
this.damageAnimation = texture;
}
public void setMoveAnimation(Texture[] texture){
this.moveAnimation = texture;
}
public void setFightAnimation(Texture[] texture){
this.fightAnimation = texture;
}
public void setTalkAnimation(Texture[] texture){
this.talkAnimation = texture;
}
//sounds setting section
public void setSpawnSound(Sound sound){
this.spawnSound = sound;
}
public void setTouchSound(Sound sound){
this.touchSound = sound;
}
public void setDeathSound(Sound sound){
this.deathSound = sound;
}
public void setObjSound(Sound sound){
this.objSound = sound;
}
public void setMoveSound(Sound sound){
this.moveSound = sound;
}
public void setFightSound(Sound sound){
this.fightSound = sound;
}
//animation and behavior section
public void spawn(){
batch.begin();
for(int i=0;i<=this.spawnAnimation.length;i++){
this.texture = this.spawnAnimation[i];
this.draw();
try
{
Thread.sleep(0, 1);
}
catch (InterruptedException e)
{}
}
batch.end();
}
public void die(Texture[] deathTexture){
}
}
}
I went to the other file, in the other class, and I tried to set the object texture
public class MyGdxGame implements ApplicationListener{
Texture texture;
SpriteBatch batch;
classes.GameObject gun;
#Override
public void create()
{
batch = new SpriteBatch();
gun = new classes.GameObject(new Texture(Gdx.files.internal("gun.png")), 0, 0, 300, 300);
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.end();
}
#Override
public void dispose()
{
}
#Override
public void resize(int width, int height)
{
}
#Override
public void pause()
{
}
#Override
public void resume()
{
}
}
once I try to access it. I face this error: aan instance for an enclosing class is required
note: I'm making this game for android. using AIDE ide which offers developing apps and games directly on your phone.
Inner classes that are declared without the keyword static are tethered to the outer class they exist in.
To fix
public static class GameObject{
Why would you want an inner class without static? Here's an example
public class Game {
private Data gameData;
class MyListener {
public void receiveNewData(Data newData) {
//update gameData with the new data
}
}
}
If MyListener was static, it would not be able to access Game's gameData
I am creating a small game for a java project (Swing GUI), we have to use a MVC pattern and I got the basic model and view down. I just can't get to understand how to use the keyboard keys to -for example- increment the X position of my character. What library should I use?
Here is my code (it's my first time coding):
/*A Thing type object can stand on a Tile,the characters and items class implement this interface.*/
public interface Thing {
public void attacked(int x);
}
public abstract class Character implements Thing{
protected int health;
protected int position[]=new int[2];
protected int direction;
protected void setHealth(int hp){
this.health=hp;
}
public int getHealth(){
return this.health;
}
public void setPositionX(int x){
this.position[0]=x;
}
public void setPositionY(int y){
this.position[1]=y;
}
public int getPositionX(){
return this.position[0];
}
public int getPositionY(){
return this.position[1];
}
public void setDirection(int x){
this.direction=x;
}
public int getDirection(){
return this.direction;
}
public void moveUp(){
int posy=this.getPositionY();
this.setPositionY(posy+1);
}
public void moveDown(){
int posy=this.getPositionY();
this.setPositionY(posy-1);
}
public void moveLeft(){
int posx=this.getPositionX();
this.setPositionX(posx-1);
}
public void moveRight(){
int posx=this.getPositionX();
this.setPositionX(posx+1);
}
public void attack(){
}
public void heavyAttack(){
}
}
/*Only one type of character,just to have a really basic code to test then improve it*/
public class Mage extends Character{
public Mage(){
this.setHealth(5);
this.setPositionX(3);
this.setPositionY(3);
}
public void attacked(int x){
this.setHealth(this.getHealth()-x);
}
}
/*A Tile is a space on which a character/item (Thing) can stand,the level is a matrice of tiles*/
public class Tile {
private Thing[] occupant;
public Tile(){
this.occupant=new Thing[1];
}
public Thing getOccupant(){
return this.occupant[0];
}
public void addThing(Thing a){
this.occupant[0]=a;
}
public void removeThing(){
this.occupant[0]=null;
}
}
public class Terrain {
private String name;
private Tile[][] checker;
private int sizeX;
private int sizeY;
public Terrain(int x,int y,String Name){
this.name=Name;
this.sizeX=x;
this.sizeY=y;
this.checker= new Tile[y][x];
for (int i=0; i<y; i++){
for(int j=0; j<x; j++){
this.checker[i][j]=new Tile();
}
}
}
public int getSizeX(){
return sizeX;
}
public int getSizeY(){
return sizeY;
}
public Thing getTileOccupant(int x,int y){
return this.checker[y][x].getOccupant();
}
public void Spawn(Thing t,int x,int y){
this.checker[y][x].addThing(t);
}
}
/* The View,This was really just to test it out so it only shows the tiles and the mage sprite*/
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;
public class myPanel extends JPanel {
private Terrain terrain;
public myPanel(Terrain checker){
this.terrain=checker;
this.requestFocusInWindow();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
File file=new File("D:\\workspace\\Projet INFO-H-200\\src\\Images\\soltest.png");
BufferedImage sol=null;
try{
sol=ImageIO.read(file);
}
catch (IOException e){
e.printStackTrace();
}
file=new File("D:\\workspace\\Projet INFO-H-200\\src\\Images\\mage.png");
BufferedImage mage=null;
try{
mage=ImageIO.read(file);
}
catch (IOException e){
e.printStackTrace();
}
for (int i=0;i<terrain.getSizeY();i++){
for (int j=0;j<terrain.getSizeX();j++){
g.drawImage(sol, 33*j,33*i, null);
if (terrain.getTileOccupant(j,i)!=null){
g.drawImage(mage, 33*j, 33*i, null);
}
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
Mage blubu=new Mage();
Terrain terrain=new Terrain(10,10,"Test");
terrain.Spawn(blubu, blubu.getPositionX(), blubu.getPositionY());
Controler controler=new Controler(blubu);
JFrame mainWindow=new JFrame();
mainWindow.setSize(new Dimension(1000,800));
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setLocationRelativeTo(null); //au centre
mainWindow.setLayout(new BorderLayout());//gérer les placements
mainWindow.add(new myPanel(terrain), BorderLayout.CENTER); //on ajoute le panel au centre
mainWindow.setVisible(true);
mainWindow.toFront();
}
}
I have been having some issues with loading Textures in LWJGL/Slick Util. I am receiving this error in the texture.bind() method. I would also like advice as to how to improve my code if improvement is needed. Here it is:
The Sprite Class:
package geniushour.engine.animation;
import static org.lwjgl.opengl.GL11.*;
import java.io.IOException;
import org.newdawn.slick.opengl.Texture;
public class Sprite {
private float sx;
private float sy;
private Texture texture;
public Sprite(float sx, float sy, Texture texture) throws IOException{
this.texture = texture;
this.sx = sx;
this.sy = sy;
}
public void render(){
texture.bind();
glBegin(GL_QUADS);
glTexCoord2f(0,0);
glVertex2f(0,0);
glTexCoord2f(1,0);
glVertex2f(0,sy);
glTexCoord2f(1,1);
glVertex2f(sx,sy);
glTexCoord2f(0,1);
glVertex2f(sx,0);
glEnd();
}
public float getSX(){
return sx;
}
public float getSY(){
return sy;
}
public Texture getTexture(){
return texture;
}
public void setSX(float sx){
this.sx = sx;
}
public void setSY(float sy){
this.sy = sy;
}
/*public void setSpriteTexture(String key) throws IOException{
this.texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("img/"+key+".png"));
}*/
}
The GameObject Class:
package geniushour.gameobject;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import static org.lwjgl.opengl.GL11.glTranslatef;
import java.io.IOException;
import org.newdawn.slick.opengl.Texture;
import geniushour.engine.animation.Sprite;
public abstract class GameObject {
protected float x;
protected float y;
protected float sx;
protected float sy;
protected Sprite spr;
protected int type;
protected static final int PLAYER_ID = 0;
protected static final int ENEMY_ID = 1;
protected static final int ITEM_ID = 2;
protected static final int ENTITY_SIZE = 64;
protected static final int ITEM_SIZE = 16;
protected boolean[] flags = new boolean[1];
public void update(){}
public void render(){
glPushMatrix();
glTranslatef(x,y,0);
spr.render();
glPopMatrix();
}
public float getX(){
return x;
}
public float getY(){
return y;
}
public float getSX(){
return spr.getSX();
}
public float getSY(){
return spr.getSY();
}
public int getType(){
return type;
}
public boolean getRemove(){
return flags[0];
}
public void remove(){
flags[0] = true;
}
/*protected void setTexture(String key) throws IOException{
spr.setSpriteTexture(key);
}*/
public Texture getTexture(){
return spr.getTexture();
}
protected void init(float x, float y, float sx, float sy,Texture texture,int type) throws IOException{
this.x = x;
this.y = y;
this.type = type;
this.spr = new Sprite(sx,sy,texture);
}
}
The Player Class:
package geniushour.gameobject.entity;
import java.io.IOException;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.opengl.Texture;
import geniushour.game.Inventory;
import geniushour.game.Stats;
import geniushour.gameobject.GameObject;
import geniushour.gameobject.item.Item;
public class Player extends GameObject {
private Stats stats;
private Inventory inv;
private int stamina;
private int maxStamina = 150;
public Player(float x, float y, Texture texture) throws IOException{
init(x,y,ENTITY_SIZE,ENTITY_SIZE,texture,PLAYER_ID);
stats = new Stats(0,true);
inv = new Inventory(9);
stamina = maxStamina;
}
public void update(){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
stamina--;
}
else if(!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){
stamina++;
if(stamina > maxStamina){
stamina = maxStamina;
}
}
}
public void getInput(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
move(0,1.5);
}
else{
move(0,1);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
move(0,-1.5);
}
else{
move(0,-1);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina != 0){
move(-1.5,0);
}
else{
move(-1,0);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina != 0){
move(1.5,0);
}
else{
move(1,0);
}
}
}
public Texture getTexture(){
return getTexture();
}
private void move(double magX, double magY){
x += getSpeed() * magX;
y += getSpeed() * magY;
}
private int getSpeed(){
return stats.getPlayerSpeed();
}
#SuppressWarnings("unused")
private int getLevel(){
return stats.getLevel();
}
#SuppressWarnings("unused")
private int getXP(){
return stats.getXP();
}
public int getMaxHP(){
return stats.getMaxHP();
}
public int getCurrentHealth(){
return stats.getCurrentHealth();
}
public int getStrength(){
return stats.getStrength();
}
public int getMagic(){
return stats.getMagic();
}
public void addXP(int amt){
stats.addXP(amt);
}
public void addHP(int amt){
stats.addHP(amt);
}
public void addItem(Item item){
inv.add(item);
}
}
The Game Class:
package geniushour.game;
import java.io.IOException;
import java.util.ArrayList;
import org.newdawn.slick.opengl.Texture;
import geniushour.gameobject.*;
import geniushour.gameobject.entity.*;
import geniushour.gameobject.item.*;
public class Game {
private ArrayList<GameObject> obj;
private ArrayList<GameObject> remove;
private Player p; private Texture pTexture;
private ItemEssence essence; private Texture eTexture;
private EnemyBlob blob; private Texture bTexture;
public Game() throws IOException{
obj = new ArrayList<GameObject>();
remove = new ArrayList<GameObject>();
setTexture(pTexture,"raptor");
setTexture(eTexture,"essence");
setTexture(bTexture,"blob");
p = new Player(250,250,pTexture);
essence = new ItemEssence(400, 400, eTexture, p);
blob = new EnemyBlob(300,500,bTexture, 1);
obj.add(essence);
obj.add(p);
obj.add(blob);
}
public void getInput(){
p.getInput();
}
public void update(){
for(GameObject go : obj){
if(!go.getRemove()){
go.update();
}
else{
remove.add(go);
}
}
for(GameObject go : remove){
obj.remove(go);
}
}
public void render(){
for(GameObject go : obj){
go.render();
}
}
public ArrayList<GameObject> sphereCollide(float x, float y, float radius){
ArrayList<GameObject> res = new ArrayList<GameObject>();
for(GameObject go : obj){
if(Util.dist(go.getX(),x,go.getY(),y) < radius){
res.add(go);
}
}
return res;
}
private void setTexture(Texture texture, String key){
}
}
The error occurs in the Sprite class, the first block of code.
I'am making a game, and my JFrame add only one class, i don't getting error, but one of two classes dosen't show. I am try to make JFrame frame 2 = new JFrame();, but nothing.
Game.java:
import java.awt.Component;
import javax.swing.JFrame;
public class Game{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final String TITLE = "Game Dev [ Week #1 ]";
public static void main(String[] args){
JFrame frame = new JFrame();
Player player = new Player();
Rabbit rabbit = new Rabbit();
// Draw on the map
player.setPlayer(250,250);
rabbit.setRabbit(200,200);
// Draw on the map
frame.add(player);
frame.add(rabbit); // Add only this
// Window
frame.setVisible(true);
frame.setSize(WIDTH,HEIGHT);
frame.setTitle(TITLE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Player.java:
public class Player extends JPanel implements ActionListener, KeyListener{
// Varibles
Timer time = new Timer(5, this);
static int x; double velX = 0;
static int y; double velY = 0;
private BufferedImage player;
boolean W = false;
boolean A = false;
boolean S = false;
boolean D = false;
public void setPlayer(int x, int y){
this.x = x;
this.y = y;
}
public Player(){
time.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
try {
player = ImageIO.read(getClass().getResourceAsStream("/Player.png"));
} catch (IOException e){
e.printStackTrace();
}
}
// Draw player
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(player, (int)x, (int)y, 100, 100, null);
}
// Set the start up position of player
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
// Functions for keyEvent
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_W) // UP
velY = -0.5;
if(key == KeyEvent.VK_A) // LEFT
velX = -0.5;
if(key == KeyEvent.VK_S) // DOWN
velY = 1.5;
if(key == KeyEvent.VK_D) // RIGHT
velX = 1.5;
}
public void keyTyped(KeyEvent e){}
// IF any key released
public void keyReleased(KeyEvent arg0) {
velX = 0;
velY = 0;
W = false;
A = false;
S = false;
D = false;
}
}
Rabbit.java:
public class Rabbit extends JPanel implements ActionListener{
static int x; double velX = 0;
static int y; double velY = 0;
BufferedImage rabbit;
public void setRabbit(int x, int y){
this.x = x;
this.y = y;
}
public Rabbit(){
try {
rabbit = ImageIO.read(getClass().getResourceAsStream("/Rabbit.png"));
} catch (IOException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(rabbit, (int)x, (int)y, 100, 100, null);
}
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
}
What's happening is that the JFrame is not combining the graphics for Player and Rabbit; rather, it is placing the player as a panel, and then placing the rabbit. So, the player and the rabbit are always separated. What you want is the Player and Rabbit classes NOT to extend JPanel, but to have a method called paint(Graphics). That way, you can make a class called GamePanel that extends JPanel, and create new methods setPlayer(Player) and setRabbit(Rabbit). The GamePanel class should look like this:
public class GamePanel extends JPanel {
Player player;
Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
player.paint(g);
rabbit.paint(g);
}
}
and your Player class should look like this:
public class Player {
public void paint(Graphics g) {
// How to paint the graphics in the player class
}
}
and your Rabbit class should look the same, except as public class Rabbit.
Hope that helps!
EDIT: Full Script
package game;
import java.awt.Graphics;
public interface Displayable {
public void paint(Graphics graphics);
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Rabbit implements Displayable {
private int x, y;
private Image image;
public Rabbit(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("RABBIT_FILE")); // Replace
// "RABBIT_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player implements Displayable {
private int x, y;
private Image image;
public Player(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("PLAYER_FILE")); // Replace
// "PLAYER_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import javax.swing.JPanel;
public final class GamePanel extends JPanel {
private static final long serialVersionUID = -385535147711891740L;
private Player player;
private Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
public GamePanel(Player player, Rabbit rabbit) {
this.setPlayer(player);
this.setRabbit(rabbit);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.player.paint(g);
this.rabbit.paint(g);
}
}
package game;
import javax.swing.JFrame;
public final class Main {
public static void main(String... args) {
try {
JFrame frame = new JFrame("Player & Rabbit Game"); // Or whatever
// title
// you have in mind
GamePanel panel = new GamePanel(new Player(0, 0), new Rabbit(0, 0));
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setExtendedState(6);
} catch (Exception e) {
// Handle Exception if file is corrupted, unable to be read to an
// image, or does not exist
}
}
}
I am render a square with in 3D space. When I use the glTranslatef() method and add a z coordinate the square is no longer visible. When the z coordinate is above 1 or below -1 then square is no longer displayed (I tested it by setting the z coordinate to 1. If and it didn't display).
Main.java
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
initDisplay();
gameLoop();
cleanUp();
}
public static void initDisplay(){
try {
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("AWESOMENESS!");
Display.create();
} catch (LWJGLException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void gameLoop(){
Camera cam = new Camera(70, (float)Display.getWidth() / (float)Display.getHeight(), 0.3f, 1000);
while(!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
cam.useView();
glPushMatrix();{
glColor3f(1.0f, 0.5f, 0f);
//This is the problematic line. When the 3rd param goes above 1 or below -1 the
//square disappers.
glTranslatef(0,0,-10);
glBegin(GL_QUADS);{
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glVertex3f(1,1,0);
glVertex3f(1,0,0);
}
glEnd();
}
glPopMatrix();
Display.update();
}
}
public static void cleanUp(){
Display.destroy();
}
}
Camera.java
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.*;
public class Camera {
//Position
private float x;
private float y;
private float z;
//Rotation
private float rx;
private float ry;
private float rz;
private float fov;
private float aspect;
private float near;
private float far;
public Camera(float fov, float aspect, float near, float far) {
x = 0;
y = 0;
z = 0;
rx = 0;
ry = 0;
rz = 0;
this.fov = fov;
this.aspect = aspect;
this.near = near;
this.far = far;
initProjection();
}
private void initProjection(){
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
gluPerspective(fov, aspect, near, far);
glMatrixMode(GL_MODELVIEW);
}
public void useView(){
glRotatef(rx, 1, 0, 0);
glRotatef(ry, 0, 1, 0);
glRotatef(rz, 0, 0, 1);
glTranslatef(x, y, z);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRx() {
return rx;
}
public float getRy() {
return ry;
}
public float getRz() {
return rz;
}
public float getFov() {
return fov;
}
public float getAspect() {
return aspect;
}
public float getNear() {
return near;
}
public float getFar() {
return far;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
public void setRx(float rx) {
this.rx = rx;
}
public void setRy(float ry) {
this.ry = ry;
}
public void setRz(float rz) {
this.rz = rz;
}
public void setFov(float fov) {
this.fov = fov;
}
public void setAspect(float aspect) {
this.aspect = aspect;
}
public void setNear(float near) {
this.near = near;
}
public void setFar(float far) {
this.far = far;
}
}
glMatrixMode(GL_PROJECTION_MATRIX);
Instead should be:
glMatrixMode(GL_PROJECTION);
GL_PROJECTION_MATRIX does not render the 3rd dimension. There is no further documentation on this matter.