Java LWJGL/Slick Util Java Null Pointer Exception Error (Texture Loading) - java

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.

Related

Getting NullPointerException for no reason [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I am getting a NullPointerException for no reason. Please don't redirect me to another post. I have looked at all of them. I am making a game with LibGDX.
Here is the Error
Exception in thread "LWJGL Application" java.lang.NullPointerException
at net.hasanbilal.pr.entities.Entity.getWeight(Entity.java:88)
at net.hasanbilal.pr.entities.Entity.update(Entity.java:25)
at net.hasanbilal.pr.entities.Porter.update(Porter.java:34)
at net.hasanbilal.pr.world.GMap.update(GMap.java:28)
at net.hasanbilal.pr.world.TiledGMap.update(TiledGMap.java:40)
at net.hasanbilal.pr.PrisonRevelations.render(PrisonRevelations.java:59)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
I will be showing each class that the error points too.
This is the Entity Class.
package net.hasanbilal.pr.entities;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import net.hasanbilal.pr.world.GMap;
public abstract class Entity {
protected Vector2 pos;
protected EntityType t;
protected float velocityY = 0;
protected GMap m;
protected boolean grounded = false;
public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
this.pos = new Vector2(snapshot.getX(),snapshot.getY());
this.t = t;
this.m = m;
}
public void update (float delta, float g) {
float newY = pos.y;
this.velocityY += g * delta * getWeight();
newY += this.velocityY * delta;
if (m.doesRectCollideWithMap(pos.x, newY, getWidth(), getHeight())) {
if (velocityY < 0) {
this.pos.y = (float) Math.floor(pos.y);
grounded = true;
}
this.velocityY = 0;
} else {
this.pos.y = newY;
grounded = false;
}
}
public abstract void render (SpriteBatch b);
protected void moveX(float amount) {
float newX = this.pos.x + amount;
if (!m.doesRectCollideWithMap(newX, pos.y, getWidth(), getHeight()))
this.pos.x = newX;
}
public EntitySnapshot getSaveSnapshot(){
return new EntitySnapshot(t.getId(), pos.x, pos.y);
}
public Vector2 getPos() {
return pos;
}
public float getX() {
return pos.x;
}
public float getY() {
return pos.y;
}
public EntityType getT() {
return t;
}
public float getVelocityY() {
return velocityY;
}
public boolean isGrounded() {
return grounded;
}
public int getWidth() {
return t.getWidth();
}
public int getHeight() {
return t.getHeight();
}
public float getWeight() {
return t.getWeight();
}
}
This is the Porter Class.
package net.hasanbilal.pr.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import net.hasanbilal.pr.world.GMap;
public class Porter extends Entity {
private static final int SPEED = 80;
private static final int JUMP_VELOCITY = 5;
Texture img;
public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
super.create(snapshot, type, map);
img = new Texture("porter.png");
}
#Override
public void render(SpriteBatch b) {
b.draw(img, pos.x, pos.y, getWidth(), getHeight());
}
public void update(float delta, float g) {
if (Gdx.input.isKeyPressed(Keys.SPACE) && grounded)
this.velocityY += JUMP_VELOCITY * getWeight();
else if (Gdx.input.isKeyPressed(Keys.SPACE) && !grounded && this.velocityY > 0)
this.velocityY += JUMP_VELOCITY * getWeight() * delta;
super.update(delta, g);
if (Gdx.input.isKeyPressed(Keys.LEFT))
moveX(-SPEED * delta);
if (Gdx.input.isKeyPressed(Keys.RIGHT))
moveX(SPEED * delta);
}
}
This is the GMap
package net.hasanbilal.pr.world;
import java.util.ArrayList;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import net.hasanbilal.pr.entities.Entity;
import net.hasanbilal.pr.entities.EntityLoader;
import net.hasanbilal.pr.entities.Porter;
public abstract class GMap {
protected ArrayList<Entity> entities;
public GMap() {
entities = new ArrayList<Entity>();
entities.addAll(EntityLoader.loadEntities("basic", this, entities));
}
public void render (OrthographicCamera c, SpriteBatch b) {
for (Entity entity : entities) {
entity.render(b);
}
}
public void update (float deltaTime) {
for (Entity entity : entities) {
entity.update(deltaTime, -9.8f);
}
}
public void dispose () {
EntityLoader.saveEntities("basic", entities);
}
/**
* Gets a tile by location
* #param layer
* #param x
* #param y
* #return
*/
public TileType getByLocation(int layer, float x, float y) {
return this.getByCoordinate(layer, (int) (x / TileType.TILE_SIZE), (int) (y / TileType.TILE_SIZE));
}
/**
* Gets Tile by coordinate
* #param layer
* #param col
* #param row
* #return
*/
public abstract TileType getByCoordinate(int layer, int col, int row);
public boolean doesRectCollideWithMap(float x, float y, int width, int height) {
if (x<0 || y < 0 || x + width > getPixelWidth() || y + height > getPixelHeight())
return true;
for (int row = (int) (y / TileType.TILE_SIZE); row < Math.ceil((y + height) / TileType.TILE_SIZE); row++) {
for (int col = (int) (x / TileType.TILE_SIZE); col < Math.ceil((x + width) / TileType.TILE_SIZE); col++) {
for (int layer = 0; layer < getLayers(); layer++) {
TileType type = getByCoordinate(layer, col, row);
if (type != null && type.isCollidable())
return true;
}
}
}
return false;
}
public abstract int getWidth();
public abstract int getHeight();
public abstract int getLayers();
public int getPixelWidth() {
return this.getWidth() * TileType.TILE_SIZE;
}
public int getPixelHeight() {
return this.getHeight() * TileType.TILE_SIZE;
}
}
This is the class for the TiledGMap
package net.hasanbilal.pr.world;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import net.hasanbilal.pr.entities.Entity;
import net.hasanbilal.pr.entities.Porter;
public class TiledGMap extends GMap {
TiledMap lvl1;
OrthogonalTiledMapRenderer otmr;
public TiledGMap() {
lvl1 = new TmxMapLoader().load("level1.tmx");
otmr = new OrthogonalTiledMapRenderer(lvl1);
}
#Override
public void render(OrthographicCamera c, SpriteBatch b) {
otmr.setView(c);
otmr.render();
b.setProjectionMatrix(c.combined);
b.begin();
super.render(c, b);
b.end();
}
#Override
public void update(float deltaTime) {
super.update(deltaTime);
}
#Override
public void dispose() {
lvl1.dispose();
}
#Override
public TileType getByCoordinate(int layer, int col, int row) {
Cell cell = ((TiledMapTileLayer) lvl1.getLayers().get(layer)).getCell(col, row);
if (cell !=null) {
TiledMapTile t = cell.getTile();
if (t != null) {
int id = t.getId();
return TileType.getTileTypeById(id);
}
}
return null;
}
#Override
public int getWidth() {
return ((TiledMapTileLayer) lvl1.getLayers().get(0)).getWidth();
}
#Override
public int getHeight() {
return ((TiledMapTileLayer) lvl1.getLayers().get(0)).getHeight();
}
#Override
public int getLayers() {
return lvl1.getLayers().getCount();
}
}
This is the Prison Revelations class
package net.hasanbilal.pr;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import net.hasanbilal.pr.world.GMap;
import net.hasanbilal.pr.world.TileType;
import net.hasanbilal.pr.world.TiledGMap;
public class PrisonRevelations extends ApplicationAdapter {
OrthographicCamera c;
SpriteBatch b;
GMap gm;
#Override
public void create () {
b = new SpriteBatch();
c = new OrthographicCamera();
c.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
c.update();
gm = new TiledGMap();
}
#Override
public void render () {
Gdx.gl.glClearColor(255, 255, 255, 1);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isTouched()) {
c.translate(-Gdx.input.getDeltaX(), Gdx.input.getDeltaY());
c.update();
}
if (Gdx.input.justTouched()) {
Vector3 pos = c.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
TileType t = gm.getByLocation(1, pos.x, pos.y);
if (t != null) {
System.out.println("You clicked on tile with id" + t.getId() + " " + t.getName()+ " " + t.isCollidable() + " " + t.getDamage());
}
}
c.update();
gm.update(Gdx.graphics.getDeltaTime());
gm.render(c, b);
}
#Override
public void dispose () {
b.dispose();
gm.dispose();
}
}
Please help. Im gonna die. This is due soon.
Looks like you made a mistake with parameters names on your create, change to this:
public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
this.pos = new Vector2(snapshot.getX(),snapshot.getY());
this.t = type;
this.m = map;
}

trying to make my (very simple) libgdx game more object-oriented. added GameObject class - game doesn't launch anymore

what the title says.
first of all, here are my 3 classes:
MyGdxGame:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Sprite sp;
Texture img;
int width;
int height;
Player p;
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("dildo.png");
sp = new Sprite(img);
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
p = new Player(img);
Gdx.input.setInputProcessor(p);
}
#Override
public void render () {
//sp.flip(true, false);
p.update();
Gdx.gl.glClearColor(255,255,255,255);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
//batch.draw(img, 0, height/6, -img.getWidth(), img.getHeight());
p.draw(batch);
//sp.draw(batch);
batch.end();
}
}
Player:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.TimeUtils;
public class Player extends GameObject implements InputProcessor {
private Sprite sp;
private Texture te;
private float xPos;
private float yPos;
private float xSpeed;
private float ySpeed;
private float accelerationX;
private float g;
Vector2 position;
private float accelerationJump = 9f;
private boolean allowJump = true;
private boolean isDragged = false;
public Player(Texture sprite) {
xPos = 0;
yPos = (super.getHeight()/6);
xSpeed = 5.5f;
ySpeed = 0;
te = sprite;
sp.setX(xPos);
sp.setY(yPos);
g = 0.2f;
accelerationX=0.02f;
}
public void update() {
ySpeed -= g;
if(isDragged) {
xSpeed += accelerationX;
moveBy(xSpeed,0);
isDragged = false;
}
if (getxPos() > super.getWidth()) {
setxPos(0);
} else {
moveBy(xSpeed, ySpeed);
}
if (getyPos() < super.getHeight() / 6) {
moveTo(sp.getX(), getHeight() / 6);
}
if (onGround()) {
allowJump = true;
ySpeed = 0;
}
}
public void jump() {
ySpeed += accelerationJump;
}
public boolean onGround() {
return (sp.getY() == super.getHeight()/6);
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (allowJump && isDragged == false) {
allowJump = false;
jump();
}
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
if(isDragged==false) {
isDragged = true;
}
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
GameObject:
package com.mygdx.game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public abstract class GameObject {
private Sprite sp;
private int width;
private int height;
private float xPos;
private float yPos;
private float xSpeed;
private float ySpeed;
public GameObject(int width, int height) {
this.width = width;
this.height = height;
}
public GameObject() {
}
public void moveTo(float xPos2, float yPos2) {
setxPos(xPos2);
setyPos(yPos2);
}
public void moveBy(float dx, float dy) {
sp.setY(sp.getY() + dy);
sp.setX(sp.getX() + dx);
}
public float getxPos() {
return xPos;
}
public float getyPos() {
return yPos;
}
public void setxPos(float xPos2) {
sp.setX(xPos2);
}
public void setyPos(float yPos) {
sp.setY(yPos);
}
public float getxSpeed() {
return xSpeed;
}
public float getySpeed() {
return ySpeed;
}
public void setxSpeed(float xSpeed2) {
xSpeed = xSpeed2;
}
public void setySpeed(float ySpeed2) {
ySpeed = ySpeed2;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height
}
public void draw(SpriteBatch batch) {
sp.draw(batch);
}
}
basically, the game as it is now is just a sprite moving from left to right of the screen - when you tap, it jumps, when you drag the screen it dashes forward. i want to now start adding things like power-ups and platforms so i thought it would be a good idea to create a GameObject class. but now when i run it the screen goes black and the application just crashes, i have a feeling it has something to do with the way i'm initialising my Texture? any ideas?
any help is highly appreciated, many thanks in advance :)
edit: in GameObject constructor width and height are the width and height of the screen
if you have your image in asset folder of android project, test img = new Texture (Gdx.files.internal ("dildo.png"));
example:
AdroidProyect->Asset->YourFile.png
and in player i think
1-
public Player(Texture sprite) {
xPos = 0;
yPos = (super.getHeight()/6);
xSpeed = 5.5f;
ySpeed = 0;
te = sprite;
//add and refactor your code if it works
sp = new Sprite(sprite);
sp.setX(xPos);
sp.setY(yPos);
g = 0.2f;
accelerationX=0.02f;
}
or 2-
I do not want to do, but in your MyGdxGame, your
you say,
..//
img = new Texture ("dildo.png");
         sp = new Sprite (img);
         p = new Player (img);
..//
but after you pass the player a texture, because no sprite or as I said before initializing the player, you could also change the constructor of the player.
public Player(Sprite sprite){t
..//
this.sp = sprite;
ADD NEW:
Musta Been to look at your code and no offense, you have a code a little crazy :)
visibility of variables is somewhat confusing because what you want but do not test well and looks over the access modifiers, aver if they match what you want to do.
my English is also a little crazy too.
in your class MyGdxGame;
..//
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture(Gdx.files.internal("dildo.png"));
sp = new Sprite(img);
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
p = new Player(sp);
Gdx.input.setInputProcessor(p);
}
..//
class GameObject Change;
public abstract class GameObject {
protected Sprite sp;
protected int width;
protected int height;
protected float xPos;
protected float yPos;
protected float xSpeed;
protected float ySpeed;
player class.
public class Player extends GameObject implements InputProcessor {
//private Sprite sp; remove
private Texture te;
//private float xPos; remove
//private float yPos; remove
//private float xSpeed; remove
//private float ySpeed; remove
private float accelerationX;
private float g;
Vector2 position;
private float accelerationJump = 9f;
private boolean allowJump = true;
private boolean isDragged = false;
public Player(Sprite sprite) {
..//
sp = sprite;

LWJGL glTranslatef not rendering depth

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.

Java Game Dev: Checking if player is in-between two y coords

I'm making a game with Slick2D. When a player get's under a window with an enemy in it, they can shoot, and points will be added. I have every mechanic completed besides the shooting one. Here is my "plan" on how it'll work.
When the player gets below the window(which the program picks up on via y coordinate) and fires, points will be added to a counter.
How can I get my program to realize that the player is indeed below a window?
Thanks, and here's my PlayState code.
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.Image;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;
import java.util.Random;
import java.util.TimerTask;
import java.util.Timer;
public class PlayState extends BasicGameState{
int stateID = -1;
int w = SwegBoi.WIDTH;
int h = SwegBoi.HEIGHT;
static int enemylocation;
float s = SwegBoi.SCALE;
Image playbackground;
Image swegboiplayer;
Image quit;
Image enemy1;
Image enemy2;
float playery;
int score = 0;
final static Random ran = new Random();
static Timer tm = new Timer();
static long startTime = System.currentTimeMillis();
public static void main(String args){
}
public PlayState(int stateID){
this.stateID = stateID;
}
#Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
swegboiplayer = new Image("resources/swegboibackgun.png");
playbackground = new Image("resources/playstatebackground.png");
quit = new Image("resources/mainmenuquit.png");
enemy1 = new Image("resources/enemy1.png");
enemy2 = new Image("resources/enemy1.png");
tm.schedule(new TimerTask() {
#Override
public void run() {
enemylocation = ran.nextInt(4) + 1;
}
}, 1, 2000);
}
#Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
playbackground.setFilter(Image.FILTER_NEAREST);
playbackground.draw(0, 0, s*10);
quit.draw((w-175*s),5 *s,s/2);
if(enemylocation==1){
enemy1.setFilter(Image.FILTER_NEAREST);
enemy1.draw(200,170,s*10);
}
if(enemylocation==2){
enemy1.setFilter(Image.FILTER_NEAREST);
enemy1.draw(200,360,s*10);
}
if(enemylocation==3){
enemy1.setFilter(Image.FILTER_NEAREST);
enemy1.draw(950,170,s*10);
}
if(enemylocation==4){
enemy1.setFilter(Image.FILTER_NEAREST);
enemy1.draw(950,360,s*10);
}
swegboiplayer.setFilter(Image.FILTER_NEAREST);
swegboiplayer.draw((w*s)/2-(playery*s), 450*s, s*5);
g.drawString("Alpha V0.1",6,6);
}
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
Input input = gc.getInput();
if(input.isKeyDown(Input.KEY_LEFT)){playery += 17;}
if(input.isKeyDown(Input.KEY_RIGHT)){playery -= 17;}
int mouseX = input.getMouseX();
int mouseY = input.getMouseY();
if(mouseHover(mouseX,mouseY,(w-175*s),5*s,quit.getHeight()/2,quit.getWidth()) == true){
if(input.isMousePressed(0)){
sbg.enterState(SwegBoi.MAINMENUSTATE,new FadeOutTransition(), new FadeInTransition());
}
quit = new Image("resources/mainmenuquithover.png");
}else{
quit = new Image("resources/mainmenuquit.png");
}}
#Override
public int getID() {
return stateID;
}
public boolean mouseHover(int mouseX, int mouseY, float x, float y, float height, float width){
if((mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height)){
return true;
}else{
return false;
}
}}
Something like this should work. Every time you move, check if you are in a range of an enemy x position and determine if shooting should be enabled or disabled. Define some kind of range for each enemies X position.
private void checkShootStatus()
{
// Calculate image bounds X Position + width
float swegboiplayerEndBound = swegboiplayer.getX() + swegboiplayer.getWidth();
float enemyEndBound = enemy.getX() + enemy.getWidth();
// Check enemy 1
if (swegboiplayerEndBound > enemy.getX() && swegboiplayer.getX() < enemyEndBound)
{
canShoot = true;
}
else
{
canShoot = false;
}
}
Since you cannot get the x location of an image, create a wrapper class to track the x/y positions of the player and enemy.
public class Player extends Image
{
private String image;
private float x = 0;
private float y = 0;
public Player(String image) throws SlickException
{
super(image);
this.setImage(image);
}
public float getY()
{
return y;
}
public void setY(float y)
{
this.y = y;
}
public String getImage()
{
return image;
}
public void setImage(String image)
{
this.image = image;
}
public float getX()
{
return x;
}
public void setX(float x)
{
this.x = x;
}
}
Enemy
public class Enemy extends Image
{
private String image;
private int x;
private int y;
public Enemy(String image) throws SlickException
{
super(image);
this.setImage(image);
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
public String getImage()
{
return image;
}
public void setImage(String image)
{
this.image = image;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
}

Using OpenGL with LWJGL won't yield a picture

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.

Categories

Resources