Cannot Load Texture in Java (lwjgl) - java

I have been going about on this for the past 3 hours.
I'm trying to make a 2D Strategy game in Java using the lwjg libraries, and for starters, I've got stuck at loading a texture for an object (Farmer).
Its giving me this:
Exception in thread "main" java.lang.NullPointerException
at _2nd_Branch.Farmer.render(Farmer.java:42)
at _1st_Branch.CoreGame.render(CoreGame.java:30)
at _1st_Branch.Game.GameLoop(Game.java:33)
at _1st_Branch.Game.main(Game.java:13)
Here is the code I've been working on (As a way to organize things. Got this from someone on youtube explaining some bits about lwjgl):
Game.java:
package _1st_Branch;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
public class Game {
private static CoreGame coreGame;
public static void main(String [] args)
{
CD();
createGame();
GameLoop();
CleanUp();
}
private static void CD()
{
Window.create(800, 600);
}
private static void createGame()
{
coreGame = new CoreGame();
}
public static void GameLoop()
{
while(!Window.isCloseRequested())
{
Window.Clear();
coreGame.input();
coreGame.logic();
coreGame.render();
Display.update();
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
{
Display.destroy();
System.exit(0);
}
}
}
private static void CleanUp()
{
coreGame.dispose();
Window.Destroy();
}
}
CoreGame.java:
package _1st_Branch;
import _2nd_Branch.Farmer;
import _2nd_Branch.Player;
public class CoreGame {
public final static int TILE_SIZE = 64;
private static Player player;
private static Farmer farmer;
public CoreGame()
{
farmer = new Farmer();
}
public void input()
{
}
public void logic()
{
}
public void render()
{
farmer.render();
}
public void dispose()
{
}
}
Window.java:
package _1st_Branch;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class Window {
public static void create(int width, int height)
{
try
{
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle("Artyas RTS");
Display.create();
initGL();
initInput();
}
catch (LWJGLException e)
{
e.printStackTrace();
}
}
public static void initGL()
{
glClearColor(0.5f, 0.5f, 1, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();
}
private static void initInput()
{
try
{
Keyboard.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
}
}
public static void Clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
public static void Destroy()
{
Keyboard.destroy();
Display.destroy();
System.exit(0);
}
public static void update()
{
Display.update();
Display.sync(60);
}
public static boolean isCloseRequested()
{
return Display.isCloseRequested();
}
}
Farmer.java:
//CIVILIAN UNIT
package _2nd_Branch;
import java.io.IOException;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class Farmer {
public Farmer() {};
private Texture texture;
public void init() {
try {
// load texture from PNG file
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("Farmer.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void render()
{
Color.white.bind();
texture.bind();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0,0);
GL11.glVertex2f(400,500);
GL11.glTexCoord2f(1,0);
GL11.glVertex2f(450,500);
GL11.glTexCoord2f(1,1);
GL11.glVertex2f(450, 550);
GL11.glTexCoord2f(0,1);
GL11.glVertex2f(400, 550);
GL11.glEnd();
}
}
I am literally stuck here. If someone could indicate what needs to be done, I will be eternally grateful! I really need to get going on making this project, to learn more about Java.
The texture.bind() function from the Farmer class gives me the error.
Being stuck here, I don't know what it says about me as a programmer.

You never call Farmer.init() which loads the texture. You only call the constructor in CoreGame. Either you should call init() from inside the Farmer constructor or call init after calling the constructor in CoreGame. I recommend calling init() from CoreGame, and continue to keep texture loading away from the constructor simply because if you initialize and have to call the constructor to Farmer before you have created your display and initialized OpenGL (Window.initGL()) you don't want to load the texture. Loading a texture with slick before the display is created and opengl is initialized can cause a NullpointerException in TextureLoader.

Related

OpenGL doesn't find context while coding shaders.: LWJGL

I was on lwjgl, just coding my engine as I'm gonna reuse it for other projects. But as i was coding my shaders, and tested, it gave this error.
FATAL ERROR in native method: Thread[main,5,main]: No context is current or a function that is not available in the current context was called. The JVM will abort execution.
at org.lwjgl.opengl.GL20C.glCreateShader(Native Method)
at org.lwjgl.opengl.GL20.glCreateShader(GL20.java:253)
at bengine.shaders.ShaderProgram.loadShader(ShaderProgram.java:51)
at bengine.shaders.ShaderProgram.<init>(ShaderProgram.java:13)
at bengine.shaders.StaticShader.<init>(StaticShader.java:10)
at Main.jav$1.init(jav.java:53)
at bengine.window.CustomWindow.gameloop(CustomWindow.java:54)
at bengine.window.WindowRunner.runWindow(WindowRunner.java:7)
at Main.jav.main(jav.java:59)
Process finished with exit code 1
I need answers please do give answers, and tell if this has been a shut down topic.
Heres my code:
ShaderProgram.java:
package bengine.shaders;
import org.lwjgl.opengl.GL20;
import java.io.*;
public abstract class ShaderProgram {
private int shadersID;
private int vertexShaderID;
private int fragmentShaderID;
public ShaderProgram(String vertFile, String fragFile) {
vertexShaderID = ShaderProgram.loadShader(vertFile, GL20.GL_VERTEX_SHADER);
fragmentShaderID = ShaderProgram.loadShader(fragFile, GL20.GL_FRAGMENT_SHADER);
shadersID = GL20.glCreateProgram();
GL20.glAttachShader(shadersID, vertexShaderID);
GL20.glAttachShader(shadersID, fragmentShaderID);
GL20.glLinkProgram(shadersID);
GL20.glValidateProgram(shadersID);
}
public void start() { GL20.glUseProgram(shadersID); }
public void stop() { GL20.glUseProgram(0); }
public void clear() {
stop();
GL20.glDetachShader(shadersID, vertexShaderID);
GL20.glDetachShader(shadersID, fragmentShaderID);
GL20.glDeleteShader(vertexShaderID);
GL20.glDeleteShader(fragmentShaderID);
GL20.glDeleteProgram(shadersID);
}
protected void bindAttribute(int attribute, String variableName) {
GL20.glBindAttribLocation(shadersID, attribute, variableName);
}
protected abstract void bindAttributes();
private static int loadShader(String file, int type) {
StringBuilder shaderSource = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null) {
shaderSource.append(line).append("\n");
}
} catch(IOException e) {
e.printStackTrace();
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID);
return shaderID;
}
}
StaticShader.java:
package bengine.shaders;
import org.lwjgl.glfw.GLFW;
public class StaticShader extends ShaderProgram {
private static final String VERTEX_FILE = "src/bengine/shaders/vertShader.glsl";
private static final String FRAGMENT_FILE = "src/bengine/shaders/fragmentShader.glsl";
public StaticShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
#Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
}
both shaders:
fragment shader:
#version 400 core
in vec3 colour;
out vec4 col;
void main(void) {
col = vec4(colour, 1.0);
}
vertex shader:
#version 400 core
in vec3 position;
out vec3 colour;
void main(void) {
gl_Position = vec4(position, 1.0);
colour = vec3(position.x, position.y, position.z);
}
And the window.
package bengine.window;
import bengine.math.Vector4;
import bengine.shaders.ShaderProgram;
import bengine.shaders.StaticShader;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.glfw.GLFW.*;
public abstract class CustomWindow {
private long window;
public StaticShader shader;
public CustomWindow(int w, int h, String name) {
if(!glfwInit()) {
System.err.println("Bengi engine failure: GLFW initialization failed, this is a internal error, can't be fixed.");
}
glfwDefaultWindowHints();
this.window = glfwCreateWindow(w, h, name, 0, 0);
if(this.window == 0) {
System.err.println("Bengi engine failure: Window is 0.");
}
System.out.println("Window created.");
glfwMakeContextCurrent(window);
System.out.println("Context was made.");
}
public abstract void render();
public abstract void update();
public abstract void init();
public void swapBuffers() {
glfwSwapBuffers(this.window);
}
public void enableGLClearWith(int mode, Vector4 color) {
GL11.glClearColor(color.getX(), color.getY(), color.getZ(), color.getW());
GL11.glClear(mode);
}
public void runTask(Task task) {
task.runTask();
}
protected void gameloop() {
glfwInit(); // to avoid null pointer
//glfwMakeContextCurrent(window);
init();
GL.createCapabilities(true);
while(!glfwWindowShouldClose(this.window)) {
//swapBuffers();
render();
update();
glfwPollEvents();
}
}
}
Main.java:
package Main;
import bengine.math.Vector4;
import bengine.window.*;
import bengine.CONSTANTS;
import bengine.window.WindowRunner;
import bengine.math.Vector3;
import bengine.renderer.Mesh;
import bengine.renderer.Renderer;
import bengine.renderer.Vertex;
import bengine.shaders.StaticShader;
//import org.lwjgl.opengl.GL11;
public class jav {
public static CustomWindow window;
public static void main(String[] args) {
Mesh mesh = new Mesh(
new Vertex[] {
new Vertex(new Vector3(-0.5f, -0.5f, -0.5f)),
new Vertex(new Vector3(-0.5f, 0.5f, -0.5f)),
new Vertex(new Vector3(0.5f, -0.5f, -0.5f)),
new Vertex(new Vector3(0.5f, 0.5f, -0.5f)),
new Vertex(new Vector3(0.0f, 0.6f, -0.5f)),
},
new int[] {
0, 1, 2, 1, 3, 2, 1, 4, 3
}
);
Renderer renderer = new Renderer();
window = new CustomWindow(1200, 800, "hello world") {
#Override
public void render() {
swapBuffers();
enableGLClearWith(CONSTANTS.COLOR, new Vector4(0f, 0f, 0f, 1f));
shader.start();
renderer.renderMesh(mesh, CONSTANTS.TRI_RENDER);
shader.stop();
}
#Override
public void update() {
}
#Override
public void init() {
shader = new StaticShader();
}
};
WindowRunner runner = new WindowRunner();
runner.runWindow(window);
}
}
and the window runner(deprecated later)
package bengine.window;
import org.jetbrains.annotations.NotNull;
public class WindowRunner {
public static void runWindow(#NotNull CustomWindow window) {
window.gameloop();
}
}
I don't know why its happening, all my other packages in the renderer and others had the context. Please answer.
GL.createCapabilities(true); has to be called before init(). Note in the is an abstract method. It is overridden and the StaticShader object is constructed in init. Therefore, the OpenGL capability must be ensured beforehand:
protected void gameloop() {
GL.createCapabilities(true);
init();
while(!glfwWindowShouldClose(this.window)) {
//swapBuffers();
render();
update();
glfwPollEvents();
}
}

libGDX actor draw() not called

Please forgive me for my english.
Began to explore libGDX and have a problem. When I add actor on stage, method draw() not called.
Tried to apply the method to draw a straight line, texture successfully drawn but it is not an actor, and this method is not correct.
Help please.
SpiderHunt.java
package com.spiderhunt;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.spiderhunt.screens.MainMenu;
public class SpiderHunt extends Game{
private SpriteBatch batch;
public MainMenu mainMenu;
private static SpiderHunt instance = new SpiderHunt();
public SpiderHunt(){
}
public static SpiderHunt getInstance() {
return instance;
}
public void create () {
//load textures
Assets.load();
batch = new SpriteBatch();
mainMenu = new MainMenu(batch);
this.setScreen(mainMenu);
}
public void showMainMenu(){
setScreen(mainMenu);
}
public void render (float delta) {
}
public void resize(int width, int height) {
}
public void pause() {
}
public void resume() {
}
public void dispose() {
}
}
MainMenu.java
package com.spiderhunt.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.spiderhunt.Assets;
import com.spiderhunt.buttons.btnPlay;
public class MainMenu implements Screen {
public btnPlay playButton;
public Stage stage;
public SpriteBatch batch;
class GoToGameListener extends ClickListener {
#Override
public void clicked(InputEvent event, float x, float y) {
//some code for click or push
}
}
public MainMenu(SpriteBatch batch_1) {
batch = batch_1;
stage = new Stage(new StretchViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight()), batch);
Gdx.input.setInputProcessor(stage);
playButton = new btnPlay(); //make actor
stage.addActor(playButton);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//make background
batch.begin();
batch.draw(Assets.bgMenuRegion, 0, 0, 540, 960);
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw(); //this action must do method draw() from actor but it not called !!!!!!!!!!
//batch.begin();
//playButton.draw(batch, 0); THIS CODE DRAW BUTTON, BUT IT NOT CORRECTLY ACTOR
//batch.end();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
btnPlay.java
package com.spiderhunt.buttons;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.spiderhunt.Assets;
public class btnPlay extends Actor {
public btnPlay(){
setSize(100, 40);
setPosition(100, 100);
}
public void draw(SpriteBatch batch, float parentAlpha) {
//!!!!!!!!!!!!!!!Error in this place. Draw() not called from stage
batch.setColor(getColor());
batch.draw(Assets.btnPlayRegion, 0, 0);
}
}
Assets.java
package com.spiderhunt;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class Assets {
public static Texture atlas;
//backgrounds
public static TextureRegion bgMenuRegion;
public static TextureRegion bgSelectLevelRegion;
//buttons
public static TextureRegion btnPlayRegion;
//objects
public static TextureRegion objFlyRegion;
public static void load(){
atlas = new Texture("atlas.png");
bgMenuRegion = new TextureRegion(atlas, 0, 0, 540, 960);
btnPlayRegion = new TextureRegion(atlas, 1111, 1244, 418, 112);
}
}
Thanks for the help.
And now i find my bug.
I replace SpriteBatch to Batch and it work.
change
public void draw(SpriteBatch batch, float parentAlpha) {
//!!!!!!!!!!!!!!!Error in this place. Draw() not called from stage
batch.setColor(getColor());
batch.draw(Assets.btnPlayRegion, 0, 0);
}
to
#Override
public void draw(Batch batch, float parentAlpha) {
//!!!!!!!!!!!!!!!Error in this place. Draw() not called from stage
batch.setColor(getColor());
batch.draw(Assets.btnPlayRegion, 0, 0);
}
The problem I believe is at this line:
new Stage(new StretchViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight()), batch);
Remove batch from the Stage Initialization change it to this:
new Stage(new StretchViewport( Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
You are passing the batch from the Screen to the stage and you are calling batch.end() before stage.draw(). However stage has its own batch so you do not have to pass a batch for the stage to draw. If for your own reasons (e.g. batch projection matrix configuration) you still want your Screen batch passed to the stage do not call batch.end() before stage.draw() since your batch of the stage and your main batch are the same. Call batch.end() after stage.draw()

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.

java.lang.RuntimeException: No OpenGL context found in the current thread

im trying to create a applet for a little game i created. when i run the game normally (no applet) it works just fine but when im trying to run it as an applet it gives me the following error.
im using lwjgl 2.8.4 opengl
java.lang.RuntimeException: No OpenGL context found in the current thread.
java.lang.RuntimeException: Unable to create display
at com.base.engine.GameApplet.init(GameApplet.java:202)
at sun.applet.AppletPanel.run(AppletPanel.java:434)
at java.lang.Thread.run(Thread.java:722)
here is the code for the GameApplet.java
package com.base.engine;
import com.base.game.Game;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.util.ArrayList;
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 static org.lwjgl.opengl.GL11.*;
public class GameApplet extends Applet {
Canvas display_parent;
/** Thread which runs the main game loop */
Thread gameThread;
/** is the game loop running */
private static boolean running = false;
private static Game game;
public void startLWJGL() {
//gameThread = new Thread() {
// #Override
//public void run() {
running = true;
try {
initDisplay();
Display.setParent(display_parent);
System.out.println("hij loopt");
//Display.create();
System.out.println("hij loopt");
initGL();
initGame();
gameLoop();
cleanUp();
} catch (LWJGLException e) {
return;
}
//gameLoop();
//}
//};
//gameThread.start();
}
private static void initGame()
{
game = new Game();
}
private static void getInput()
{
System.out.print("before input");
game.getInput();
System.out.print("after input");
}
private static void update()
{
game.update();
}
private static void render()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
game.render();
Display.update();
Display.sync(60);
}
private static void gameLoop()
{
System.out.print("before while");
while(!Display.isCloseRequested())
{
while(running) {
System.out.print("before running shit");
Display.sync(60);
Display.update();
Display.destroy();
//getInput();
update();
render();
System.out.println("running gameLoop..");
}
}
System.out.print("after while");
}
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();
System.out.println("Keyboard created");
Display.setVSyncEnabled(true);
} catch (LWJGLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ArrayList<GameObject> sphereCollide(float x, float y, float radius)
{
return game.sphereCollide(x, y, radius);
}
/**
* Tell game loop to stop running, after which the LWJGL Display will
* be destoryed. The main thread will wait for the Display.destroy().
*/
private void stopLWJGL() {
running = false;
}
#Override
public void start() {
//startLWJGL();
}
#Override
public void stop() {
}
/**
* Applet Destroy method will remove the canvas,
* before canvas is destroyed it will notify stopLWJGL()
* to stop the main game loop and to destroy the Display
*/
#Override
public void destroy() {
remove(display_parent);
super.destroy();
}
#Override
public void init() {
setLayout(new BorderLayout());
try {
display_parent = new Canvas() {
#Override
public final void addNotify() {
super.addNotify();
startLWJGL();
}
#Override
public final void removeNotify() {
stopLWJGL();
super.removeNotify();
}
};
display_parent.setSize(800,600);
add(display_parent);
System.out.println("gaat ie lekker");
display_parent.setFocusable(true);
display_parent.requestFocus();
display_parent.setIgnoreRepaint(true);
setVisible(true);
} catch (Exception e) {
System.err.println(e);
throw new RuntimeException("Unable to create display");
}
}
}
can someone tell me what im doing wrong?

java programming: how to move the display

im making a side scroller and i dont know how to side scroll and im trying to scroll on the x and y axis
this is for a school project so i would like help as soon as possable
heres some of my code if you have question just ask. any advice is welcome.
source code http://www.mediafire.com/?fi1f9lv6qc2t5d7
gameCanvas.java
package Game;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
#SuppressWarnings("serial")
public abstract class GameCanvas extends Canvas implements Runnable,KeyListener{
public static final long ONE_SECOND_MILI = 1000;
protected int frameW;
protected int frameH;
protected long fps;
private long period = 15;
private BufferStrategy buff;
private Graphics graph;
private Color bckGround=(Color.GRAY);
private Image bckGround_img;
private Thread t;
boolean left;
boolean right;
boolean up;
boolean down;
int lastpressed;
int newlastpressed;
private String drawFps = "0";
public GameCanvas(int w,int h){
this.frameW=w;
this.frameH=h;
this.setIgnoreRepaint(true);
this.setBounds(0,0,frameW,frameH);
this.setBackground(Color.GREEN);
this.setVisible(true);
}
public GameCanvas(int w,int h,Color bck){
this.frameW=w;
this.frameH=h;
this.bckGround=bck;
this.setIgnoreRepaint(true);
this.setBounds(0,0,frameW,frameH);
this.setBackground(bckGround);
this.setVisible(true);
}
public void addNotify(){
super.addNotify();
this.createBufferStrategy(2);
this.buff=this.getBufferStrategy();
requestFocus();
startGame();
}
public void startGame(){
if (t==null){
t=new Thread(this);
t.start();
}
}
public void run(){
while(true){
long beginTime=System.currentTimeMillis();
// try {
// Thread.sleep(25);
// } catch (InterruptedException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
Update();
Render();
Draw();
fps=System.currentTimeMillis() - beginTime ;
long sleepTime=period-fps;
if (sleepTime == 30) sleepTime = -1;
fps= ONE_SECOND_MILI / ((period * 2) - sleepTime);
try{
if (sleepTime > 0){
Thread.sleep(sleepTime);
}
}
catch(Exception e){
}
}
}
public void Render(){
graph = buff.getDrawGraphics();
if (!HasImgBackground()){
graph.setColor(bckGround);
graph.fillRect(0, 0, frameW, frameH);
}else{
graph.drawImage(bckGround_img, 0, 0, frameW, frameH,null);
}
graph.setColor(new Color(255,255,255));
graph.drawString("FPS: " + fps , 10, 15);
Paint(graph);
}
private void Draw(){
if(!buff.contentsLost()){
buff.show();
if(graph != null){
graph.dispose();
}
}
}
private boolean HasImgBackground(){
if (bckGround_img==null){
return false;
}
return true;
}
public void setBackgroundImg(Image image){
this.bckGround_img=image;
}
public void deleteBackground(){
this.bckGround_img=null;
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT){
left=true;
if(lastpressed!=4)
newlastpressed=lastpressed;
lastpressed=4;
}
if(e.getKeyCode()==KeyEvent.VK_UP){
up=true;
if(lastpressed!=1)
newlastpressed=lastpressed;
lastpressed=1;
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
right=true;
if(lastpressed!=2)
newlastpressed=lastpressed;
lastpressed=2;
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
down=true;
if(lastpressed!=3)
newlastpressed=lastpressed;
lastpressed=3;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT){
left=false;
if(up||right||down)
if(newlastpressed!=0)
lastpressed=newlastpressed;
}
if(e.getKeyCode()==KeyEvent.VK_UP){
up=false;
if(left||right||down)
if(newlastpressed!=0)
lastpressed=newlastpressed;
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
right=false;
if(up||left||down)
if(newlastpressed!=0)
lastpressed=newlastpressed;
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
down=false;
if(up||right||left)
if(newlastpressed!=0)
lastpressed=newlastpressed;
}
}
public void keyTyped(KeyEvent e) {
}
abstract void Update();
abstract void Paint(Graphics g);
}
main.java
package Game;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
public class Mainth extends GameCanvas{
private long timeDown = 0;
// private StopWatch t = new StopWatch();
static Collision coll=new Collision();
Character character=new Character();
static Image wallImage=ImageLoader.getImg().getImage("data/images/objects/brick_wall.png");
static Image bushImage=ImageLoader.getImg().getImage("data/images/objects/hedge_ver.png");
static ArrayList<Image> wallArray=new ArrayList<Image>();
static ArrayList<Image> wall2Array=new ArrayList<Image>();
static Sprite wallSprite;
static Sprite wall2Sprite;
static IndexCounter devIndex;
static Dude dev;
static Wall wall;
static Wall bush;
static Wall wall2;
/**not used*/
int x=0,y=0;
static ArrayList objects=new ArrayList<Entity>();
static ArrayList chars=new ArrayList<Dude>();
static ArrayList projectiles=new ArrayList<>();
public static void main(String[] args){
Mainth Canvas=new Mainth(1500,1000);
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(Canvas);
frame.pack();
frame.setSize(750, 400);
frame.setVisible(true);
Mainth.chars.add(dev);
Mainth.objects.add(wall);
Mainth.objects.add(bush);
Mainth.objects.add(wall2);
}
public Mainth(int w,int h){
super(w,h);
this.addKeyListener(this);
CharacterCreation();
}
public void CharacterCreation(){
wallArray.add(wallImage);
wall2Array.add(bushImage);
wallSprite=new Sprite(wallArray,1);
wall2Sprite=new Sprite(wall2Array,1);
dev=new Dude(character.LinkStandingDown,character.LinkStandingDown.getID(),100,300);
devIndex=new IndexCounter(character.LinkWalkingDownArray.size(),3);
wall=new Wall(wallSprite,1,100,50){};
bush=new Wall(wall2Sprite,1,185,55){};
wall2=new Wall(wallSprite,1,100,225){};
bush.setHardness(1);
}
Movement movem=new Movement();
void Update() {
movem.movement(dev, character, left, right, up, down, lastpressed, devIndex);
dev.move();
coll.objectCollision(chars,objects);
devIndex.Counter();
}
void Paint(Graphics g) {
bush.Draw(g,0);
wall.Draw(g,0);
wall2.Draw(g,0);
dev.Draw(g,devIndex.getIndex());
Graphics2D g2d= (Graphics2D) g;
}
public void animation(){
String[] animationSprites=dev.getImgs("walk_down");
int aniTime=0;
aniTime++;
}
public ArrayList<Entity> exportObjects(){
return objects;
}
public ArrayList<Dude> getMainChar(){
return chars;
}
}
What exactly isn't working in the game?
Basic side scrolling logic consists of moving the background, the characters, and the obstacles a certain increment as movement keys are held down. If the screen is "moving right," we are actually moving all of these elements to the left. If the screen is "moving left," then we are doing the opposite. Also, if an entity is moving and has a certain target point, make sure and update the coordinates of this point as you scroll, or the entity will keep moving until it reaches its original on-screen destination. You should also implement code that stops the screen from scrolling too far (thus losing the game).
There are many ways to use side-scrolling, such as scrolling when a character moves a certain distance from the center of the screen, or having controls that move the screen independently from a character (such as in an rts when one scrolls around the map). An easier way might be to always have the player be in the center of the screen, and just have the background and other entities scroll back and forth around him.
You need to coordinate systems:
world coordinates - are always constant
(local) frame coordinate - where objects should be shown in your window now
every object has only world coordinates. And you have a window in this big world. This window has its coordinates in world coordinates. To scroll the view in your window you just need to change it's world coordinates.
Of course you need a code, that renders all objects in you window for any correct position of your movable window. It can be like:
void renderFrame(Rectangle frame) {
for(GameObject go : gameObjects) {
if(frame.contains(go.getGlobalCoordinates())) {
Rectangle windowCoordinates = new Rectangle();
windowCoordinates.x = go.getGlobalCoordinates().x - frame.x;
windowCoordinates.x = go.getGlobalCoordinates().y - frame.y;
windowCoordinates.x = go.getGlobalCoordinates().width - frame.width;
windowCoordinates.x = go.getGlobalCoordinates().height - frame.height;
go.paint(g2, windowCoordinates);
}
}
}

Categories

Resources