Reputation: 5
I'm new to LWJGL and need help with collision detection. Below I have included the two java classes that I am working with. The Ship.java class draws a square and then you can move the square around. The Enemy.java displays red square.
I would like to have the ship collide with the enemy. I am confused on what to do.
Ship.java
package WallWars;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.input.Keyboard;
public class Ship {
double x;
double y;
double spdX;
double spdY;
double directionLeft;
Enemy enemy = new Enemy();
public Ship(){
x = 100;
y = 100;
}
public void ShipLogic(){
x += spdX;
y += spdY;
//Friction
if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT) && spdX > 0){
spdX = spdX * 0.9;
}
if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && spdX < 0){
spdX = spdX * 0.9;
}
if(!Keyboard.isKeyDown(Keyboard.KEY_UP) && spdY < 0){
spdY = spdY * 0.85;
}
if(!Keyboard.isKeyDown(Keyboard.KEY_DOWN) && spdY > 0){
spdY = spdY * 0.85;
}
//Keyboard Input
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
spdX = Math.max(-5, spdX - 1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){
spdX = Math.min(5, spdX + 1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_UP)){
spdY = Math.max(4.5, spdY + 1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
spdY = Math.min(-4.5, spdY - 1);
}
}
public void ShipCollisions(){
//Wall Collisions
if(x <= 0){
spdX = 0;
x = 0.1;
}
if(x >= 768){
spdX = 0;
x = 767.9;
}
if(y <= 0){
spdY = 0;
y = 0.1;
}
if(y >= 568){
spdY = 0;
y = 567.9;
}
}
public void EnemyCollisions(){
if(x > enemy.x + 60 + 32 && x < enemy.x){
}
}
public void dShip(){
ShipLogic();
ShipCollisions();
EnemyCollisions();
glBegin(GL_QUADS);
glColor3d(1, 1, 1);
glVertex2d(x, y);
glVertex2d(x + 32, y);
glVertex2d(x + 32, y + 32);
glVertex2d(x, y + 32);
glEnd();
}
}
Enemy.java
package WallWars;
import static org.lwjgl.opengl.GL11.*;
public class Enemy {
double x;
double y;
double posX = x;
double posY = y;
public void dEnemy(double x, double y){
glBegin(GL_QUADS);
glColor3d(1, 0, 0);
glVertex2d(x, y);
glVertex2d(x + 32, y);
glVertex2d(x + 32, y + 32);
glVertex2d(x, y + 32);
glEnd();
}
}
Upvotes: 0
Views: 1061
Reputation: 1118
First of all you can use the Rectangle class of the Java API. It can store a position (x, y) and a width and a height.
Once all your objects (your ship and your enemy) use Rectangle, you can simply use the intersects method to know if two Rectangle collide.
The problem you're facing is that you need to encapsulate your behaviour (logic) methods in a "run" (infinite) loop.
Then, in your main loop if you detect a collision (the simple part) you need to do something about it. The first thing you can do is to stop moving your ship. Later you can try to avoid the obstacle by taking another path.
Upvotes: 1