| thejava |
12-06-2012 09:49 PM |
Java Slick2D Platformer Collision Help
So far I've gotten this much code but now I am stuck with the left and right movement collisions. I don't even know how I got the jumping collision to work but I really need help.
Code:
package state;
import java.util.ArrayList;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class StateMenu extends BasicGameState
{
private int id;
private Vector2f playerPos;
private Vector2f enemyPos;
private Vector2f enemyPos2;
private Rectangle playerCol;
private Rectangle enemyCol;
private Rectangle enemyCol2;
private float velocityY;
private float gravity = 0.365f;
private boolean isJumping = false;
private boolean onGround = false;
public StateMenu(int id)
{
this.id = id;
}
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException
{
playerPos = new Vector2f(0, 0);
enemyPos = new Vector2f(0, 150);
enemyPos2 = new Vector2f(50, 100);
playerCol = new Rectangle(playerPos.getX(), playerPos.getY(), 50, 50);
enemyCol = new Rectangle(enemyPos.getX(), enemyPos.getY(), 50, 50);
enemyCol2 = new Rectangle(enemyPos2.getX(), enemyPos2.getY(), 50, 50);
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
{
g.setColor(Color.green);
g.fillOval(playerPos.getX(), playerPos.getY(), 50, 50);
g.setColor(Color.blue);
g.fillRect(enemyPos.getX(), enemyPos.getY(), 50, 50);
g.setColor(Color.red);
g.fillRect(enemyPos2.getX(), enemyPos2.getY(), 50, 50);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
{
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_SPACE) && isJumping == false)
{
velocityY = 7.5f;
isJumping = true;
}
if (input.isKeyDown(Input.KEY_SPACE) && onGround == true)
{
isJumping = false;
onGround = false;
velocityY = 7.5f;
playerPos.set(playerPos.getX(), playerPos.getY() - velocityY);
}
if (isJumping)
{
if (!playerCol.intersects(enemyCol) && !playerCol.intersects(enemyCol2))
{
velocityY -= gravity;
playerPos.set(playerPos.getX(), playerPos.getY() - velocityY);
}
else
{
onGround = true;
}
}
if (input.isKeyDown(Input.KEY_ESCAPE))
{
gc.exit();
}
if (input.isKeyDown(Input.KEY_LEFT))
{
playerPos.set(playerPos.getX() - 2, playerPos.getY());
}
if (input.isKeyDown(Input.KEY_RIGHT))
{
playerPos.set(playerPos.getX() + 2, playerPos.getY());
}
playerCol.setX(playerPos.getX());
playerCol.setY(playerPos.getY());
}
@Override
public int getID()
{
return id;
}
}
|