Slick2d how to check if a shape contains any object? Java - java

i'm new to Slick2d and to this page too, i tried asking the slick forums, but there aren't many people so i couldn't get an answer
Anyway, i've been trying to create a platformer engine in Slick2d java game library, and i was thinking of using the contains and intersects methods of the Shape class.
The thing is, if I want to check if a shape contains any object of any kind (or any object from a specific class), Is there a way to do that? all tutorials i've found explain how to test collision with one single shape, but what if i want to check for any object?
package juegoconslick;
import java.util.ArrayList;
import org.newdawn.slick.*;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;
public class JuegoConSlick extends BasicGame {
Jugador player;
Input entrada;
Shape hitbox;
bloque bloq;
ArrayList<bloque> bloques = new ArrayList<>();
public JuegoConSlick(){
super("Mi prueba");
}
public static void main(String[] args) {
AppGameContainer juegito;
try{
juegito = new AppGameContainer(new JuegoConSlick());
juegito.setDisplayMode(630,400,false);
juegito.setMaximumLogicUpdateInterval(60);
juegito.setMaximumLogicUpdateInterval(50);
juegito.setAlwaysRender(true);
juegito.setVSync(true);
juegito.start();
}catch(Exception ex){
System.exit(0);
}
}
#Override
public void init(GameContainer gc) throws SlickException {
player = new Jugador();
hitbox = new Rectangle(player.X, player.Y, 10, 10);
bloq = new bloque(50,50,50,50);
}
#Override
public void update(GameContainer gc, int i) throws SlickException {
intersecta();
Input entrad = gc.getInput();
if(entrad.isKeyDown(Input.KEY_RIGHT) && player.X<600){
player.X+=3;
player.sprite.update(1);
hitbox.setX(player.X);
}
if(entrad.isKeyDown(Input.KEY_LEFT) && player.X>0){
player.X-=3;
player.sprite.update(1);
hitbox.setX(player.X);
}
if(entrad.isKeyDown(Input.KEY_UP) && player.Y>0){
player.Y-=3;
player.sprite.update(1);
hitbox.setY(player.Y);
}
if(entrad.isKeyDown(Input.KEY_DOWN) && player.Y<370){
player.Y+=3;
player.sprite.update(1);
hitbox.setY(player.Y);
}
}
#Override
public void render(GameContainer gc, Graphics grphcs) throws SlickException {
grphcs.draw(bloq.bloque);
grphcs.draw(hitbox);
}
public void intersecta(){
try{
if(hitbox.contains(null)){//i tried checking if it didnt contain any object,
}else{
System.exit(0);
}
}catch(Exception ex){
}
}
}
EDIT: i think i have found a solution, though im not sure if its the most efficient.
basiaclly, i'll save all objects of the same class in an ArrayList:
ArrayList<bloque> bloques = new ArrayList<>();
bloques.add(new bloque(50,50,100,100));
bloques.add(new bloque(100,100,100,100));
Then, what im going to do is check the entire arraylist each time i call the intersects method:
public boolean intersecta(){
boolean devuelve=false;
for(int i=0; i<bloques.size(); i++){
if(hitbox.intersects(bloques.get(i).bloque)){
devuelve=true;
}
}
return devuelve;
}
then im going to use the value i get from intersects to decide whether the player can move or not
public void update(GameContainer gc, int i) throws SlickException {
Input entrad = gc.getInput();
if(entrad.isKeyDown(Input.KEY_RIGHT) && player.X<600 && intersecta()==false){
player.X+=3;
player.sprite.update(1);
hitbox.setX(player.X);
}
and so on with the other keys....
so im not sure if its the best solution, but as far as i have seen it seems to be working. I hope this results useful for others.

I recommend to create a new Class.
This class Needs to inherit an Slick2d Shape, so for instance:
public class ShapeWithReference extends Rectangle{}
This class can have a list or a single object reference:
public class ShapeWithReference Rectangle{
Object reference = new String("hello"); //This is dirty and can be replaced by any object.
}
Since your new class is a Slick2D shape you can now find out whether it is contained by another shape:
Rectangle rec = new Rectangle();
if(rec.contains(ShapeWithReference)){
if(ShapeWithReference.reference instanceof String){
System.out.println((String)ShapeWithReference.reference);
}
}
Contains checks whether the shape really contains another shape. So they are not just intersecting. So that's the first part you check, the second one is whether the reference Attribute of the Shape is for e.g. a String. So if our first rectangle contains our new class and the reference of this class is type of a String this String is supposed to be written in to the console.
Hope this helps or gives you a hint.
EDIT:
public class SlickGame extends BasicGame {
static AppGameContainer appgc;
Rectangle rec;
ShapeWithReference swr;
public SlickGame(String title) {
super(title);
}
#Override
public void render(GameContainer container, Graphics g) throws SlickException {
}
#Override
public void init(GameContainer container) throws SlickException {
rec = new Rectangle(0, 0, 64, 64);
swr = new ShapeWithReference(0, 0, 1, 1);
}
#Override
public void update(GameContainer container, int delta) throws SlickException {
if(rec.intersects(swr)){
if(swr.reference instanceof String){
System.out.println((String)swr.reference);
}
else if(swr.reference instanceof Integer){
System.out.println((Integer)swr.reference);
}
else if(swr.reference instanceof Shape){
Shape temp = (Shape)swr.reference;
System.out.println(temp.getWidth());
}
}
}
public static void main(String[] args) {
try {
appgc = new AppGameContainer(new SlickGame("title"));
appgc.setDisplayMode(800, 600, false);
appgc.setTargetFrameRate(60);
appgc.setFullscreen(false);
appgc.start();
} catch (SlickException ex) {
ex.printStackTrace();
}
}
}
This is the code you should be able to copy & paste directly.
It does work for me, I'm not sure if I got your problem right but after the instanceof Operator you can just add the Class Name and check for it, I added some examples with an Integer and a Shape.
This is the 2nd class:
public class ShapeWithReference extends Rectangle {
private static final long serialVersionUID = 1L;
public ShapeWithReference(float x, float y, float width, float height) {
super(x, y, width, height);
}
Object reference = new String("hello");
}
Does this work for you?

Related

How to put an picture to an object in Java?

Well I try to make an object an image, an object that goes into an ArrayList. But I don't know how to do it. I tried several methods but none of them I tried did not work. What do you think should be added? And my object is called Apple.Thanks in advance
public class Gamepanel extends JPanel {
public void tick()
{
if(apples.size()==0)
{
//System.out.println(apples.size());
int xC=r.nextInt(79);
int yC=r.nextInt(79);
apple=new Apple(xC,yC,10);
apples.add(apple);
}
for(int i=0;i<apples.size();i++)
{
if(xC==apples.get(i).getxC()&&yC==apples.get(i).getyC())
{
size++;
score++;
apples.remove(i);
i++;
}
}
}
public void paint(Graphics g)
{
//here I draw the snake and his food
if(State==STATE.GAME)
{
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0,0,WIDTH,HEIGHT);
//here i make my map of the game
for(int i=0;i<apples.size();++i)
{
apples.get(i).draw(g);
}
}
public class Apple {
private int xC,yC,width,height;
BufferedImage ap=null;
public Apple(int xC,int yC,int titleSize) {
this.xC=xC;
this.yC=yC;
width=titleSize;
height=titleSize;
}
//here i want to draw a picture for each my objects from ArrayList
public void draw(Graphics g)
{
}
I'm not sure what you're meaning by make an object an image... I don't see any code with the definition for apple...
Have you tried using Textures? You can easily create a Texture[] array containing different textures for use.
Texture[] apples = new Texture[2];
apples[0] = new Texture("apple1.png");
apples[1] = new Texture("apple2.png");
ArrayLists can also be used, but my experience with 2d games is in using libGDx (im guessing your package is graphics2D? with GDx you can...
SpriteBatch batch = new SpriteBatch();
ArrayList<Texture> apples = new ArrayList<Texture>();
//add your textures, then draw using a SpriteBatch
batch.begin();
batch.draw([texture],xpos,ypos); batch.draw(apples.get(i), 150, 500);
batch.end();

libGDX: How to read and display text from a .txt file line by line after pressing a key?

I'm new to Java and I'm trying to make a Visual Novel type of game.
What I'm trying to do is display text from a text file line by line by pressing a space button, like in a usual novel.
I've overlooked different methods but nothing works out for me. I know there are Scanner and BufferedReader, but are they suitable for what I'm doing?
Right now all that happens is when I press "space" the whole text appears on the screen, and when I let go, it dissapears.
This is my game class:
public class NovelGame extends Game {
public static final int WIDTH = 1366;
public static final int HEIGHT = 768;
public SpriteBatch batch;
public String txtFileString;
public String lines[];
public BitmapFont bitmapFont;
#Override
public void create () {
batch = new SpriteBatch();
bitmapFont = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
txtFileString = Gdx.files.internal("script.txt").readString();
String[] anArray = txtFileString.split("\\r?\\n");}
#Override
public void render () {
super.render();
}}
This is my game screen class:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
#Override
public void show() {
img = new Texture("bck.jpg");
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
game.batch.end();
}
I had an idea to display it using while and if, but can't exactly figure out how to do it.
EDIT: I found a way to display text, but now, once I run my game, it starts piling one on another endlessly after I press space.
Code:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
#Override
public void show() {
img = new Texture("bck.jpg");
}
#Override
public void render(float delta) {
try {
BufferedReader br = new BufferedReader (new FileReader("C:\\Users\\hydra\\Documents\\JAVA_PROJECTS\\gamespace\\core\\assets\\startd.txt"));
while((game.strLine = br.readLine()) != null){
game.list.add(game.strLine);
}
br.close();
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
game.showText = true;
}
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(game.showText) {
for(int i = 0; i < game.list.size(); i++) {
System.out.println(game.list.get(i));
game.bitmapFont.draw(game.batch, game.list.get(i), 100, 50);
}
}
game.batch.end();
}
Problem is here. Gdx.input.isKeyPressed returns true if only key is pressing currently.
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
To fix this add a boolean flag activate it after key is only just pressed:
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
showText = true;
}
And in render method:
if (showText) {
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
I found out what I was doing wrong in the end. I put everything in render method, and that's why file was being read endlessly. I need to do it only once in the constructor class and then put it in the render method.

Java Physics loop (repaint on interval) is choppy unless mouse is moving

I have a simple physics loop that does a calculation for a time interval, waits for the interval to pass, and then renders the results on the screen. It's very simple code (even though the timing is probably wrong, but that's exactly what I'm trying to learn about) and works well when I am moving the mouse around the screen.
package physicssim;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PhysicsSim extends JFrame {
private static class PhysicsObject {
public PhysicsObject(double x, double y, double v_x, double v_y) {
this.x = x;
this.y = y;
this.v_x = v_x;
this.v_y = v_y;
}
public double x;
public double y;
public double v_x;
public double v_y;
}
PhysicsObject particle;
boolean running = true;
DrawPane drawPane;
public PhysicsSim() {
particle = new PhysicsObject(10,10, .1, .2);
drawPane = new DrawPane(particle);
this.setSize(800,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(drawPane);
this.setVisible(true);
}
private static class DrawPane extends JPanel {
PhysicsObject p;
public DrawPane(PhysicsObject p) {
this.p = p;
}
#Override
public void paint(Graphics g) {
super.paint(g); //To change body of generated methods, choose Tools | Templates.
g.fillOval((int)p.x, (int) p.y, 10, 10);
}
}
public void start() {
int FPS = 60;
long TIME_BETWEEN_FRAMES_NS = 1000000000/FPS;
// Initial draw
drawPane.repaint();
long lastDrawTime = System.nanoTime();
while(running) {
// Update physics
particle.x+=particle.v_x*(TIME_BETWEEN_FRAMES_NS*.0000001);
particle.y+=particle.v_y*(TIME_BETWEEN_FRAMES_NS*.0000001);
// While there is time until the next draw wait
while(TIME_BETWEEN_FRAMES_NS > (System.nanoTime()-lastDrawTime)) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(PhysicsSim.class.getName()).log(Level.SEVERE, null, ex);
}
}
drawPane.repaint();
long currentTime = System.nanoTime();
System.out.println(currentTime - lastDrawTime);
lastDrawTime = currentTime;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PhysicsSim sim = new PhysicsSim();
sim.start();
}
}
The last bit about printing the time difference was just a sanity check to make sure that it was in fact calling around the requested interval. The results are fairly consistent so I don't see why there should be any choppiness.
As I mentioned above, this code works great if I a moving the mouse around the screen, everything is smooth.
If I am not moving the mouse it becomes very choppy until I start moving the mouse over the application.
I assume this is something simple, but I hope that you guys can help me. Thank you.
Alright, it looks like my problem was I was drawing directly to g in paint(). After replacing with the following everything worked correctly.
#Override
public void paint(Graphics g) {
BufferedImage img = new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR);
img.getGraphics().fillOval((int) p.x, (int) p.y, 10, 10);
g.drawImage(img, 0, 0, null);
}
I was considering deleting this code snippet because it's rough and shameful, but maybe it will help someone else. Happy coding.

How to delete an JPanel Object?

Im on to create a little "game", something like an 2d AirForce Shooter.
So, i have a problem with deleting unused enemys.
An Enemy is an simple JPanel, which is saved in the main logic as an array List.
public static ArrayList<Enemy> enemys = new ArrayList<Enemy>();
The Enemy run logic does the following:
while(!destroyed){
if(Game.running){
x--;
if(getBounds().intersects(Field.player.getBounding())){
Player.death = true;
}
if(x < 0){
Field.deleteEnemy(this);
}
setBounds((int) x, (int) y, 100, 50);
try{Thread.sleep(10);}catch(InterruptedException e){}
}
}
So you can seem there i already tried to call the method deleteEnemy, and just give it the unused Enemy.
But it isnt possible - when i just do this:
public static void deleteEnemy(Enemy e){
System.out.println("test");
enemys.remove(e);
}
It will be just removed from the list, but coninues existing on the Main JPanel.
And i cannot say
remove(e);
Because then i try to call a non static function in a static.
So, how could i delete an Enemy? Someone knows?
Thanks for help!
The hole code: (Game.java)
And, Enemy.java:
package Game;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Field extends JPanel implements Runnable{
public static Player player = new Player();
public static ArrayList<Enemy> enemys = new ArrayList<Enemy>();
private Thread moveBackground = new Thread(this);
private boolean bgMoving = false;
public static boolean addMob = false;
private int x = 0;
private int bgSpeed = -1;
public Field(){
setBounds(0, 0, 800, 600);
setFocusable(true);
setLayout(null);
addKeyListener(new Handler());
add(player);
}
public void paintComponent(Graphics g){
Field.super.paintComponent(g);
g.drawImage(Images.images[0], x, 0, this);
}
public static void deleteEnemy(Enemy e){
System.out.println("test");
enemys.remove(e);
}
public void run(){
while(!Player.death){
if(bgMoving){
bgMoving = true;
x += bgSpeed;
if(x < -(Images.images[0].getWidth(this) - this.getWidth() - 20)){
bgMoving = false;
}
repaint();
try { Thread.sleep(20); } catch (InterruptedException e) {}
}
if(addMob){
enemys.add(new Enemy());
add(enemys.get(enemys.size() - 1));
addMob = false;
}
}
JOptionPane.showMessageDialog(null, "DIED!");
}
public class Handler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
player.KeyPressed(e);
if(!bgMoving){
if(Game.running){
bgMoving = true;
if(moveBackground.getState().toString() == "NEW"){
moveBackground.start();
}
}
}
}
public void keyReleased(KeyEvent e) {
player.KeyReleased(e);
}
}
}
And, Enemy.java:
package Game;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Enemy extends JPanel implements Runnable{
Thread t = new Thread(this);
private double x = Game.width();
private double y = Math.random() * Game.height();
private double xF = 0, yF = 0;
private boolean destroyed = false;
public Enemy(){
setBounds((int) x, (int) y, 100, 50);
setOpaque(false);
t.start();
}
public void paintComponent(Graphics g){
Enemy.super.paintComponent(g);
g.setColor(Color.GREEN);
g.drawImage(Images.images[2], 0, 0, this);
}
public void run() {
while(!destroyed){
if(Game.running){
x--;
if(getBounds().intersects(Field.player.getBounding())){
Player.death = true;
}
if(x < 0){
Field.deleteEnemy(this);
}
setBounds((int) x, (int) y, 100, 50);
try{Thread.sleep(10);}catch(InterruptedException e){}
}
}
}
}
After removing you will need to call revalidate() and repaint()
[Too long for a comment]
I think the problem is in your logic on removing an Enemy/JPanel:
You are removing it from the ArrayList only, what about the containing JPanel/JFrame you added it to?
You must remove the JPanel from its container (maybe another JPanel or the JFrame) not just the ArrayList via Component#remove(Component c).
If you drew the Enemy images directly in paintComponent(...) of your container via iterating the ArrayList; removing it from the ArrayList would be sufficient, as it will no longer be in the Array and thus no longer drawn on the next repaint().
+1 to #Optional, you may need to call revalidate() and repaint() on the container for the affects of the removed JPanel/Enemy to be shown.
Also as #darijan mentioned, the use of static variables along with instance is not really a great design (though for certain designs this may be fine).
In your case if you need access to an instance method of another class, within another class, simply pass the instance of the class whos method you would like to access to the object which will access it.
Here is some psuedo code expressing much of the above mentioned problems / solutions:
public class Field extends JPanel {
private ArrayList<Enemy> enemies;
public Field() {
...
enemies.add(new Enemy(this));//create a new enemy and pas it the JPanel instance so it may access instance methods of this class
}
//ONLY USED IF JPanel for Enemy is ommited and Enemy class created which represents Enemy object and not Enemy object and aJPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
ArrayList<Enemy> enemiesClone = new ArrayList<>(enemies);//copy array into another so we don't get a ConcurrentModificaton exception if removeEnemy is called while iterating the list
if(!enemiesClone.isEmpty())
for(Enemy e:enemiesClone) {//iterate through array of images
draw(e.getImage(),e.getX(),e.getY(),this);
}
}
public void removeEnemy(Enemy e) {
enemies.remove(e);//remove from the array
//ONLY USED IF JPanels are used as Enemy
remove(e);//remove from the JPanel
//so the changes of removed panel can be visible seen
revalidate();
repaint();
}
}
class Enemy extends JPanel //extends JPanel should be ommited for paintComponent method of drawing an enemy onscreen
{
private int x,y;
private BufferedImage image;
private Field f;
public Enemy(Field f) {//constructor accepts Field instance to access instance method for the class
this.f=f;
}
public void update() {
if(offscreen||dead) {
f.removeEnemy(this);//call removeEnemy which is an instance method of Field
}
}
//BELOW METHODS ONLY USED WHEN Enemy represents object and not a JPanel which can draw its image itself (and update position by simply changing co-ordinates)
public BufferedImage getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
For a more detailed look check Game Development Loop, Logic and Collision detection Java Swing 2D I made which will give you the basics needed for most 2D games. However I do not use JPanels rather draw directly to a container.
Where do you add an Enemy to JPanel?
Basically, you should call remove on Field JPanel:
public void deleteEnemy(Enemy e){
System.out.println("test");
enemys.remove(e);
this.remove(e);
}
The method should not be static.

Slick2D smooth movement of object with cursor keys

I'm playing around with Slick2D and I'm running into a problem when trying to move a simple rectangle with the cursor keys.
Functionality wise, the code works. However, if you keep one of the cursor keys pressed, every now and then there is a little hick-up in the movement wen looking at the screen.
Can anyone suggest a code improvement to make the rectangle move smoothly?
Here is the test code I used:
public class SlickGame extends BasicGame {
// ==================================================================================
// Fields
// ==================================================================================
private Rectangle mPlayer;
// ==================================================================================
// Constructor
// ==================================================================================
public SlickGame() {
super("SlickGame");
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public void init(GameContainer pGameContainer) throws SlickException {
// create the player centered on the screen
mPlayer = new Rectangle(pGameContainer.getWidth()/2 - 20, pGameContainer.getHeight()/2 - 20, 40, 40);
}
#Override
public void update(GameContainer pGameContainer, int pDelta) throws SlickException {
Input input = pGameContainer.getInput();
int speed = 200;
float distance = speed * ((float)pDelta/1000);
if (input.isKeyDown(Input.KEY_LEFT)) {
mPlayer.setX(mPlayer.getX() - distance);
}
if (input.isKeyDown(Input.KEY_RIGHT)) {
mPlayer.setX(mPlayer.getX() + distance);
}
if (input.isKeyDown(Input.KEY_UP)) {
mPlayer.setY(mPlayer.getY() - distance);
}
if (input.isKeyDown(Input.KEY_DOWN)) {
mPlayer.setY(mPlayer.getY() + distance);
}
}
#Override
public void render(GameContainer pGameContainer, Graphics pGraphics) throws SlickException {
pGraphics.fill(mPlayer);
}
// ==================================================================================
// Methods
// ==================================================================================
public static void main(String[] args) {
try {
// create the game's container app
AppGameContainer container = new AppGameContainer(new SlickGame());
// adjust the resolution and disable fullscreen
container.setDisplayMode(800, 600, false);
// specify desired FPS
container.setTargetFrameRate(60);
// start the game
container.start();
}
catch (SlickException e ) {
e.printStackTrace();
}
}
}
Thanks, naughty_hacker. Adding container.setVSync(true); did the trick.

Categories