LWJGL glTranslatef not rendering depth - java

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.

Related

Detecting Collision between two filled Rectangles

I'm trying to make it print out "Game over" when the Green Square(Cuboid) runs over/into the blue(CuboidKiller) one.
GAME class:
package plugin.dev.wristz;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class Game extends JFrame {
private static final long serialVersionUID = 294623570092988970L;
public static ArrayList<CuboidKiller> killers;
public static int h = 1024, w = 768;
public static Game game;
public static Graphics graphics, g2;
public static Image image;
public static Cuboid cuboid;
public Game(String title) {
setTitle(title);
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
setLocationRelativeTo(null);
addKeyListener(new KeyHandler(cuboid));
g2 = getGraphics();
paint(g2);
}
public static void main(String[] args) {
cuboid = new Cuboid();
Thread cubi = new Thread(cuboid);
cubi.start();
killers = new ArrayList<CuboidKiller>();
CuboidKiller a = new CuboidKiller(new Random().nextInt(h), new Random().nextInt(w), new Random().nextInt(50) + 20);
killers.add(a);
game = new Game("Killer Cuboids");
}
#Override
public void paint(Graphics g) {
image = createImage(getWidth(), getHeight());
graphics = image.getGraphics();
paintComponent(graphics);
g.drawImage(image, 0, 0, this);
}
public void paintComponent(Graphics g) {
checkGameOver();
cuboid.draw(g);
for (CuboidKiller killer : killers)
killer.draw(g);
repaint();
}
public void checkGameOver() {
for (CuboidKiller killer : killers)
if (killer.isTouching(cuboid))
System.out.println("Game over!");
}
public int getH() {
return h;
}
public void setH(int wh) {
h = wh;
}
public int getW() {
return w;
}
public void setW(int ww) {
w = ww;
}
}
Cuboid class:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
#SuppressWarnings("static-access")
public class Cuboid implements Runnable {
private int x, y, xDirection, zDirection;
public Cuboid() {
this.x = 799;
this.y = 755;
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(x, y, 25, 25);
}
public void move() {
x += xDirection;
y += zDirection;
if (x <= 10)
x = 0 + 10;
if (y <= 35)
y = 0 + 35;
if (x >= 1024 - 35)
x = 1024 - 35;
if (y >= 768 - 35)
y = 768 - 35;
}
public void keyPressed(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(-5);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(5);
}
if (keyCode == ev.VK_UP) {
setZDirection(-5);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(5);
}
}
public void keyReleased(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(0);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == ev.VK_UP) {
setZDirection(0);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(0);
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getXDirection() {
return xDirection;
}
public void setXDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getZ() {
return y;
}
public void setZ(int z) {
this.y = z;
}
public int getZDirection() {
return zDirection;
}
public void setZDirection(int zDirection) {
this.zDirection = zDirection;
}
}
Cuboid Killer:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
public class CuboidKiller {
private int x, y, radius;
private HashMap<Integer, Integer> points;
public CuboidKiller(int x, int y, int radius) {
this.points = new HashMap<Integer, Integer>();
setPoints();
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, radius, radius);
}
public void setPoints() {
this.points.put(x, y);
this.points.put(x + radius, y);
this.points.put(x + radius, y - radius);
this.points.put(x, y - radius);
}
public boolean isTouching(Cuboid cuboid) {
boolean result = true;
//int a = cuboid.getX(), b = cuboid.getZ();
result = true;
return result;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public HashMap<Integer, Integer> getPoints() {
return points;
}
public void setPoints(HashMap<Integer, Integer> points) {
this.points = points;
}
}
Well, there are two approaches. Either you write it yourself, or you just use what Java 8 provides.
This guy has a very nice explanation on how to detect collision between two rectangles: Java check if two rectangles overlap at any point
But if I were the one writing it, I would just have both classes contain a Rectangle object (http://docs.oracle.com/javase/8/docs/api/java/awt/Rectangle.html), and just call the intersects() function provided by Rectangle. :-)

Multiple balls - Bouncing balls - Java

I am wring the bouncing ball program in java. And I Now have one bouncing ball, I would like to have at least five bouncing balls. I have tried a few ways to do it, however, I only end up with one ball or error.
Do you have any suggestions on how to proceed? This in the piece of code used for the one ball, is it possible to rewrite this piece of code to get multiple balls in a neat way?
import javafx.scene.shape.Rectangle;
public class World {
private final double width, height;
private Ball[] balls;
private final Rectangle pad;
public World(double width, double height) {
this.width = width;
this.height = height;
balls = new Ball[1];
balls[0] = new Ball(10, 10);
balls[0].setVelocity(75.0, 100.0);
pad = new Rectangle(width / 2, 0.9 * height,
width / 8, height / 32);
}
public void move(long elapsedTimeNs) {
balls[0].move(elapsedTimeNs);
constrainBall(balls[0]);
checkForCollisionWithPad(balls[0]);
}
public Ball[] getBalls() {
return (Ball[]) balls.clone();
}
public Rectangle getPad() {
return pad;
}
public void setPadX(double x) {
if (x > width) {
x = width;
}
if (x < 0) {
x = 0;
}
pad.setX(x);
}
private void constrainBall(Ball ball) {
double x = ball.getX(), y = ball.getY();
double dx = ball.getDx(), dy = ball.getDy();
double radius = ball.getRadius();
if (x < radius) {
dx = Math.abs(dx);
} else if (x > width - radius) {
dx = -Math.abs(dx);
}
if (y < radius) {
dy = Math.abs(dy);
} else if (y > height - radius) {
dy = -Math.abs(dy);
}
ball.setVelocity(dx, dy);
}
private void checkForCollisionWithPad(Ball ball) {
if (ball.intersectsArea(
pad.getX(), pad.getY(), pad.getWidth(), pad.getHeight())) {
double dx = ball.getDx();
// set dy negative, i.e. moving "up"
double newDy = -Math.abs(ball.getDy());
ball.setVelocity(dx, newDy);
}
}
}
Main
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Bounce extends Application {
private World world;
private Canvas canvas;
private AnimationTimer timer;
protected class BounceTimer extends AnimationTimer {
private long previousNs = 0;
#Override
public void handle(long nowNs) {
if (previousNs == 0) {
previousNs = nowNs;
}
world.move(nowNs - previousNs);
previousNs = nowNs;
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITESMOKE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
Rectangle pad = world.getPad();
gc.setFill(Color.BLACK);
double x = pad.getX(), y = pad.getY(),
w = pad.getWidth(), h = pad.getHeight();
gc.fillRoundRect(x, y, w, h, h, h);
for (Ball b : world.getBalls()) {
b.paint(gc);
}
}
}
#Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 300, Color.WHITESMOKE);
canvas = new Canvas(scene.getWidth(), scene.getHeight());
root.getChildren().add(canvas);
stage.setTitle("Bounce");
stage.setScene(scene);
stage.setResizable(false);
stage.sizeToScene();
stage.show();
world = new World(canvas.getWidth(), canvas.getHeight());
timer = new BounceTimer();
timer.start();
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
world.setPadX(me.getX());
}
});
}
public static void main(String[] args) {
launch(args);
}
private void showAlert(String message) {
alert.setHeaderText("");
alert.setTitle("Alert!");
alert.setContentText(message);
alert.show();
}
private final Alert alert = new Alert(Alert.AlertType.INFORMATION);
}
Ball
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class Ball {
public static final double BILLION = 1_000_000_000.0;
private double x, y; // position of the balls center
private double dx, dy; // velocity measured in pixels/second
private double radius;
private Color color;
public Ball(double x0, double y0) {
x = x0;
y = y0;
radius = 10;
color = Color.MAGENTA;
}
public Ball(double x0, double y0, double rad, Color col) {
x = x0;
y = y0;
radius = rad;
color = col;
}
Ball(int i, int i0, Color BLUEVIOLET) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setColor(Color col) { // setColor
color = col; }
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setX(double newX) {
x = newX;
}
public void setY(double newY) {
y = newY;
}
public double getRadius() {
return radius;
}
public double getDx() {
return dx;
}
public double getDy() {
return dy;
}
public void setVelocity(double newDx, double newDy) {
dx = newDx;
dy = newDy;
}
public void moveTo(double newX, double newY) {
x = newX;
y = newY;
}
public void move(long elapsedTimeNs) {
x += dx * elapsedTimeNs / BILLION;
y += dy * elapsedTimeNs / BILLION;
}
public void paint(GraphicsContext gc) {
gc.setFill(color);
// arguments to fillOval: see the javadoc for GraphicsContext
gc.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
public boolean intersectsArea(
double rectX, double rectY,
double rectWidth, double rectHeight) {
double closestX = clamp(x, rectX, rectX + rectWidth);
double closestY = clamp(y, rectY, rectY + rectHeight);
double distanceX = x - closestX;
double distanceY = y - closestY;
return (distanceX * distanceX) + (distanceY * distanceY)
< (radius * radius);
}
private double clamp(double value, double lower, double upper) {
if (value < lower) {
return lower;
}
if (value > upper) {
return upper;
}
return value;
}
}
As Stormblessed said, you are only targeting one ball in your move method.
You should do:
public void move(Ball ball, long elapsedTimeNs) {
ball.move(elapsedTimeNs);
constrainBall(ball);
checkForCollisionWithPad(ball);
}
Edit: Since you want the handler method to accept only the elapsedTimeNs argument, do:
public void move(long elapsedTimeNs) {
for (Ball ball : balls) {
ball.move(elapsedTimeNs);
constrainBall(ball);
checkForCollisionWithPad(ball);
}
}
Edit 2: You should probably have a method that creates a new ball, for convenience:
public Ball newBall(double x, double y, double velocity1, double velocity2) {
Ball tmp = new Ball(x, y);
tmp.setVelocity(velocity1, velocity2);
balls.add(tmp);
return tmp;
}
Edit 3: The reason it throws an error is that you designated balls to have only one index position by using balls = new Ball[1]. You should use an ArrayList (java.util.ArrayList) instead, like so:
import java.util.ArrayList;
ArrayList<Ball> balls = new ArrayList<>;
You should now use balls.add and balls.get instead of = and []. References have been updated accordingly.

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

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.

mass change values of arraylist

I have array list of circles, whitch are drawing by canvas. And everything is OK. But I need change all X,Y coordinates of circles, by during the program.
static ArrayList<Circle> mCircles;
private static void createCircles() {
if (mCircles == null) {
mCircles = new ArrayList<Circle>();
}
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
public static void AddCircle() {
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
private void Drawing(Canvas canvas) {
for (Circle c : mCircles) {
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mMalovani);
}
}
public static Circle findCircleClosestToTouchEvent(float x, float y) {
Circle c = mCircles.get(mCircles.size() - 1);
return c;
}
public class Circle extends Shape {
final float mRadius;
public Circle(float x, float y, float r) {
super(x, y);
mRadius = r;
}
final float getRadius() {
return mRadius;
}
}
public class Shape extends Activity {
protected float mStartX = 0f;
protected float mStartY = 0f;
public float mCurrentX = 30f;
public float mCurrentY = 30f;
protected float mActionDownX;
protected float mActionDownY;
protected float mActionMoveOffsetX;
protected float mActionMoveOffsetY;
// x y coordinate of a move action
public Shape (float x, float y) {
mStartX = x;
mStartY = y;
mCurrentX = x;
mCurrentY = y;
}
public void setStartX(float x) { mStartX = x; }
public void setStartY(float y) { mStartY = y; }
public float getCurrentX() { return mCurrentX; }
public float getCurrentY() { return mCurrentY; }
public void setCurrentX(float x) { mCurrentX = x;
}
public void setCurrentY(float y) { mCurrentY = y; }
public void setActionMoveOffsetX(float x) { mActionMoveOffsetX = x; }
public void setActionMoveOffsetY(float y) { mActionMoveOffsetY = y; }
public float getActionMoveOffsetX() { return mActionMoveOffsetX; }
public float getActionMoveOffsetY() { return mActionMoveOffsetY; }
public void setActionDownX(float x) { mActionDownX = x; }
public void setActionDownY(float y) { mActionDownY = y; }
public float getActionDownX() { return mActionDownX; }
public float getActionDownY() { return mActionDownY; }
public void restoreStartPosition() {
mCurrentX = mStartX;
mCurrentY = mStartY;
}
}
Assuming you have setCurrentX and setCurrentY methods opposite the getter methods, just loop through the list of circles.
private void changeCoordinates(List<Circle> circles, int x, int y){
for(Circle c:circles){
c.setCurrentX(x);
c.setCurrentY(y);
}
}

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