This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So my Player extends Mob, which extends Entity. In my Level class I have an arraylist and in the main Game class, I add him.
public Level level;
public Player player;
player = new Player(level, 100, 100, input, JOptionPane.showInputDialog(this, "Username:"));
level.addEntity(player);
The problem comes in when I want to REFERENCE the players X and Y so I can plug those into my simple Slime monster AI!
I always get a NullpointerException here (line 7):
public void tick() {
int xa = 0;
int ya = 0;
if (randomWalkTime == 0) {
int xd = level.player.x - x;
int yd = level.player.y - y;
if (xd * xd + yd * yd < 50 * 50) {
xa = 0;
ya = 0;
if (xd < 0) xa = -1;
if (xd > 0) xa = +1;
if (yd < 0) ya = -1;
if (yd > 0) ya = +1;
}
}
move(xa, ya);
randomWalkTime++;
tickCount++;
}
At the first level.player.x :( No matter how I try to reference it. Through game.player.x or anything else I can think of.
Here is the main question: There is a new "Player" that is from an arraylist in another class. How do I reference his x and y in my (Entites>Mob>) Sprite class?
If the code above isn't enough, here is the rest of the important bits:
Here is the LEVEL class where I have my entity arraylist!
public class Level {
private byte[] tiles;
public int width;
public int height;
public List<Entity> entities = new ArrayList<Entity>();
private String imagePath;
private BufferedImage image;
The Entity class!
public abstract class Entity {
public int x, y;
protected Level level;
public Entity(Level level) {
init(level);
}
public final void init(Level level) {
this.level = level;
}
public abstract void tick();
public abstract void render(Screen screen);
}
The Mob Class:
public abstract class Mob extends Entity {
protected String name;
protected int speed;
protected int numSteps = 0;
protected boolean isMoving;
protected int movingDir = 1;
protected int scale = 1;
public Mob(Level level, String name, int x, int y, int speed) {
super(level);
this.name = name;
this.x = x;
this.y = y;
this.speed = speed;
}
public void move(int xa, int ya) {
if (xa != 0 && ya != 0) {
move(xa, 0);
move(0, ya);
numSteps--;
return;
}
numSteps++;
if (!hasCollided(xa, ya)) {
if (ya < 0)
movingDir = 0;
if (ya > 0)
movingDir = 1;
if (xa < 0)
movingDir = 2;
if (xa > 0)
movingDir = 3;
x += xa * speed;
y += ya * speed;
}
}
public abstract boolean hasCollided(int xa, int ya);
protected boolean isSolidTile(int xa, int ya, int x, int y) {
if (level == null) {
return false;
}
Tile lastTile = level.getTile((this.x + x) >> 3, (this.y + y) >> 3);
Tile newTile = level.getTile((this.x + x + xa) >> 3, (this.y + y + ya) >> 3);
if (!lastTile.equals(newTile) && newTile.isSolid()) {
return true;
}
return false;
}
public String getName() {
return name;
}
}
Here is the main part of my SLIME class!
public class Slime extends Mob{
int xa, ya;
private int colour = Colours.get(-1, 111, 145, 543);
private int randomWalkTime = 0;
private boolean isSwimming;
private int tickCount = 0;
public Slime(Level level, String name, int x, int y, int speed) {
super(level, "Slime", x, y, 1);
x = this.x;
y = this.y;
}
public void tick() {
int xa = 0;
int ya = 0;
if (randomWalkTime == 0) {
int xd = level.player.x - x;
int yd = level.player.y - y;
if (xd * xd + yd * yd < 50 * 50) {
xa = 0;
ya = 0;
if (xd < 0) xa = -1;
if (xd > 0) xa = +1;
if (yd < 0) ya = -1;
if (yd > 0) ya = +1;
}
}
move(xa, ya);
randomWalkTime++;
tickCount++;
}
Since level.player.x gives a NPE, you have two posibilities: eitehr level is null or level.player is null. You have two ways to determine which it is:
Preferrably, use a debugger set a breakpoint at the offending line and set a watch on these two variables.
Add System.out.println() calls to print out the values of these two variables.
Related
I'm working on a Java Game using LWJGL. I made a particle system and would like to obtain same result as found on this website: http://play.cubedpixels.de
This is what I got so far:
I tried my best and the problem is it's stopping and they are only moving in one direction. Also the lines are not like on this website. On the website it's smoother and better. They are using OpenGL too.
How to solve these problems and make my implementation better, more like it is one the website?
The code below shows two classes: ParticleGalaxy and Particle. Latter one is inner class of the former, but for clarity I've split them into separate snippets.
ParticleGalaxy:
public class ParticleGalaxy
{
private int count;
private int width;
private int height;
private int mousex;
private int mousey;
public ArrayList<Particle> particles = new ArrayList();
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
int state = 0;
int a = 255;
int r = 255;
int g = 0;
int b = 0;
public ParticleGalaxy(int count, int width, int height)
{
this.count = count;
this.width = width;
this.height = height;
for(int i = 0; i < count; i++)
{
this.particles.add(
new Particle(this.random.nextInt(width),
this.random.nextInt(height)));
}
}
public void drawParticles(int mousex, int mousey)
{
this.mousex = mousex;
this.mousey = mousey;
for(Particle p : this.particles)
{
if(p.reset)
{
p.resetPosSize();
p.reset = false;
}
int x = Math.abs(p.getX() - mousex);
int y = Math.abs(p.getY() - mousey);
if((x < 40 && x > -40) && (y<35 && y>-40))
{
p.setConnect(true);
}
else
{
p.setConnect(false);
}
p.draw();
}
}
}
Particle:
public class Particle
{
private int x;
private int y;
private int k;
private int movey;
private int movex;
private int starty;
private int startx;
private int locationy;
private int locationx;
private float size;
private boolean reset;
private boolean connect;
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
private boolean moving = false;
private boolean start = false;
public Particle(int x, int y)
{
this.x = x;
this.y = y;
this.startx = x;
this.starty = y;
this.size = genRandom(0.57F, 0.71F);
}
public void setConnect(boolean bool)
{
connect = bool;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void drawLine(int xto, int yto, int xfrom, int yfrom)
{
GL11.glLineWidth(1.2f);
GL11.glColor3f(1.0f, 1.0f, 1.0f);
GL11.glBegin(GL11.GL_LINE_STRIP);
GL11.glVertex2d(xto, yto);
GL11.glVertex2d(xfrom, yfrom);
GL11.glEnd();
}
public void draw()
{
if(!start)
{
start = true;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
float speed = 1;
float elapsed = 0.01f;
// On starting movement
float distance = (float)Math.sqrt(Math.pow(movex - startx, 2) +
Math.pow(movey - starty, 2));
float directionX = (movex - startx) / distance;
float directionY = (movey - starty) / distance;
if(moving == true)
{
x += directionX * speed * elapsed;
y += directionY * speed * elapsed;
if(Math.sqrt(Math.pow(x - startx, 2) + Math.pow(y - starty, 2)) >= distance)
{
x = (int)movex;
y = (int)movey;
resetPosSize();
this.reset = true;
moving = false;
}
}
this.k += 1;
int xx = 0;
int yy = 0;
this.locationx = this.x + xx;
this.locationy = this.y + yy;
if(locationx < 0 || locationy < 0)
this.reset = true;
if(locationx > width || locationy > height)
this.reset = true;
GuiUtils.drawCircle(this.x + xx, this.y + yy, this.size, -1);
if(connect)
{
for(Particle p : particles)
{
if(p.connect)
drawLine(locationx, locationy, p.locationx, p.locationy);
}
}
}
public void move(int startX, int startY, int endX, int endY)
{
x = (int)startX;
y = (int)startY;
moving = true;
}
public void resetPosSize()
{
this.x = this.random.nextInt(ParticleGalaxy.this.width);
this.y = this.random.nextInt(ParticleGalaxy.this.height);
startx = x;
starty = y;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
public float genRandom(float min, float max)
{
return (float)(min + Math.random() * (max - min + 1.0F));
}
}
This is the class that i am using
public class Spot {
private static final int IMAGE_HEIGHT = 500;
private static final int IMAGE_WIDTH = 500;
private static final int DOT_HEIGHT = 20;
private static final int DOT_WIDTH = 20;
private static final Color DOT_COLOR = Color.RED;
private Random ran = new Random();
private int x = this.ran.nextInt(IMAGE_WIDTH);
private int y = this.ran.nextInt(IMAGE_HEIGHT);
/**
* Draws spot onto given playfield object
*
* #param playfield
*/
public void drawSpot(Playfield playfield) {
playfield.getGraphicsContext2D().setFill(DOT_COLOR);
playfield.getGraphicsContext2D().fillOval(x, y, DOT_WIDTH, DOT_HEIGHT);
this.drawSpot(playfield);
}
I am trying to figure out a way to write a method that would determine if the given x and y coordinate is inside the bounding box.
public boolean isINSpot(int x, int y){
if (x > this.x && x < this.x + DOT_WIDTH && y > this.y && y < this.y + DOT_HEIGHT) {
return false;
} else {
return true;
}
}
}
}
This may help:
return x > boxX && x < boxX + boxWidth && y > boxY && y < boxY + boxHeight;
If not, I messed up.
I am having trouble serializing this class using the ObjectOutputStream#writeObject method.
Here is my class:
public class InteractedObject implements Serializable{
private static final long serialVersionUID = 537798409913313981L;
protected int id;
protected WorldTile tile;
protected int option;
private long interactionTime;
public InteractedObject(int id, WorldTile tile, int option){
this.id = id;
this.tile = tile;
this.option = option;
}
public long getInteractionTime(){
return interactionTime;
}
public void setInteractionTime(long interactionTime){
this.interactionTime = interactionTime;
}
public boolean isEqualTo(Object o){
if(this == o)
return true;
InteractedObject obj = o instanceof InteractedObject ? (InteractedObject)o : null;
if(obj == null)
return false;
return obj.id == id && obj.tile.equals(tile) && obj.option == option;
}
}
The WorldTile class definitely implements the Serializable interface and only uses fields with types short and byte. I cannot see why this throws a NotSerializableException for my class 'a.rodit.rs.InteractedObject' (the top one).
Any help or guidance about why this is happening would be appreciated.
EDIT:
My WorldTile class is as follows:
public class WorldTile implements Serializable {
private static final long serialVersionUID = -6567346497259686765L;
private short x, y;
private byte plane;
public WorldTile(){
this(0, 0, 0);
}
public WorldTile(int x, int y, int plane) {
this.x = (short) x;
this.y = (short) y;
this.plane = (byte) plane;
}
public final WorldTile getLocation() {
WorldTile tile = new WorldTile(x, y, plane);
return tile;
}
public WorldTile(WorldTile tile) {
this.x = tile.x;
this.y = tile.y;
this.plane = tile.plane;
}
public WorldTile(WorldTile tile, int randomize) {
this.x = (short) (tile.x + Utils.getRandom(randomize * 2) - randomize);
this.y = (short) (tile.y + Utils.getRandom(randomize * 2) - randomize);
this.plane = tile.plane;
}
public void moveLocation(int xOffset, int yOffset, int planeOffset) {
x += xOffset;
y += yOffset;
plane += planeOffset;
}
public final void setLocation(WorldTile tile) {
setLocation(tile.x, tile.y, tile.plane);
}
public final void setLocation(int x, int y, int plane) {
this.x = (short) x;
this.y = (short) y;
this.plane = (byte) plane;
}
public int getX() {
return x;
}
public int getXInRegion() {
return x & 0x3F;
}
public int getYInRegion() {
return y & 0x3F;
}
public int getY() {
return y;
}
public int getPlane() {
if (plane > 3)
return 3;
return plane;
}
public int getChunkX() {
return (x >> 3);
}
public int getChunkY() {
return (y >> 3);
}
public int getRegionX() {
return (x >> 6);
}
public int getRegionY() {
return (y >> 6);
}
public int getRegionId() {
return ((getRegionX() << 8) + getRegionY());
}
public int getLocalX(WorldTile tile, int mapSize) {
return x - 8 * (tile.getChunkX() - (Settings.MAP_SIZES[mapSize] >> 4));
}
public int getLocalY(WorldTile tile, int mapSize) {
return y - 8 * (tile.getChunkY() - (Settings.MAP_SIZES[mapSize] >> 4));
}
public int getLocalX(WorldTile tile) {
return getLocalX(tile, 0);
}
public int getLocalY(WorldTile tile) {
return getLocalY(tile, 0);
}
public int getLocalX() {
return getLocalX(this);
}
public int getLocalY() {
return getLocalY(this);
}
public int get18BitsLocationHash() {
return getRegionY() + (getRegionX() << 8) + (plane << 16);
}
public int get30BitsLocationHash() {
return y + (x << 14) + (plane << 28);
}
public boolean withinDistance(WorldTile tile, int distance) {
if (tile.plane != plane)
return false;
int deltaX = tile.x - x, deltaY = tile.y - y;
return deltaX <= distance && deltaX >= -distance && deltaY <= distance
&& deltaY >= -distance;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + plane;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WorldTile other = (WorldTile) obj;
if (plane != other.plane)
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public boolean withinDistance(WorldTile tile) {
if (tile.plane != plane)
return false;
// int deltaX = tile.x - x, deltaY = tile.y - y;
return Math.abs(tile.x - x) <= 15 && Math.abs(tile.y - y) <= 15;// deltaX
// <= 14
// &&
// deltaX
// >=
// -15
// &&
// deltaY
// <= 14
// &&
// deltaY
// >=
// -15;
}
public int getCoordFaceX(int sizeX) {
return getCoordFaceX(sizeX, -1, -1);
}
public static final int getCoordFaceX(int x, int sizeX, int sizeY,
int rotation) {
return x + ((rotation == 1 || rotation == 3 ? sizeY : sizeX) - 1) / 2;
}
public static final int getCoordFaceY(int y, int sizeX, int sizeY,
int rotation) {
return y + ((rotation == 1 || rotation == 3 ? sizeX : sizeY) - 1) / 2;
}
public int getCoordFaceX(int sizeX, int sizeY, int rotation) {
return x + ((rotation == 1 || rotation == 3 ? sizeY : sizeX) - 1) / 2;
}
public int getCoordFaceY(int sizeY) {
return getCoordFaceY(-1, sizeY, -1);
}
public int getCoordFaceY(int sizeX, int sizeY, int rotation) {
return y + ((rotation == 1 || rotation == 3 ? sizeX : sizeY) - 1) / 2;
}
}
As I mentioned previously, I don't see any problem with it.
NotSerializableException is only thrown when some object to be serialized does not implement the java.io.Serializable interface
I tried to simulate the issue and copied your class. Then I created a sample WorldTile class that looks like that:
public class WorldTile implements Serializable {
short x = 4;
byte y = 1;
}
My piece of code is as follows and it works well:
File file = new File("obj.txt");
file.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(new InteractedObject(4, new WorldTile(), 5));
System.out.println("success");
The only reason for you to fail to achieve this is probably your WorldTile class.
EDIT:
Another problem can be if you have failed to run the latest version of your file. Have you saved all the .java files in your application?
Also are you sure that your Serializable interface you have implemented is indedd java.io.Serializable ?
In my code I have a player class and from that Player class I want to call in a projectile, but whenever I try calling in the projectile in game, I get this error
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at ca.runner.level.Level.tick(Level.java:127)
at ca.runner.game.Game.tick(Game.java:149)
at ca.runner.game.Game.run(Game.java:118)
at java.lang.Thread.run(Unknown Source)
I think it has to do maybe with the fact that both Mob and Projectile both call Entity or something like that, but I'm not sure how to fix this. If anyone could help that would be great.
Player Class:
package ca.runner.game.entities;
import ca.runner.game.Game;
import ca.runner.game.InputHandler;
import ca.runner.gfx.Colours;
import ca.runner.gfx.Screen;
import ca.runner.level.Level;
import ca.runner.game.InputHandler;
import ca.runner.gfx.Colours;
import ca.runner.gfx.Screen;
import ca.runner.level.Level;
public class Player extends Mob{
private InputHandler input;
private int colour = Colours.get(-1, 111, 145, 543);
private int scale = 1;
protected boolean isSwimming = false;
private int tickCount = 0;
private int health = 10;
public Player(Level level, int x, int y, InputHandler input) {
super(level, "Player", x, y, 1);
this.input = input;
this.health = health;
}
public void tick() {
int xa = 0;
int ya = 0;
if(input.up.isPressed()) {ya--;}
if(input.down.isPressed()) {ya++;}
if(input.left.isPressed()) {xa--;}
if(input.right.isPressed()) {xa++;}
if(input.space.isPressed()) {
BasicAttack Fireball = new BasicAttack(level, false, "Fireball", 10, 10, 1, 1, 1, getPlayerMoveDir());
level.addEntity(Fireball);
}
if (xa != 0 || ya != 0) {
move(xa, ya);
isMoving = true;
}else {
isMoving = false;
}
if (level.getTile(this.x >> 3, this.y >> 3).getId() == 4) {
isSwimming = true;
}
if (isSwimming && level.getTile(this.x >> 3, this.y >> 3).getId() != 4) {
isSwimming = false;
}
tickCount++;
}
public void render(Screen screen) {
int xTile = 0;
int yTile = 28;
int walkingSpeed = 4;
int flipTop = (numSteps >> walkingSpeed) & 1;
int flipBottom = (numSteps >> walkingSpeed) & 1;;
if (movingDir == 1) {
xTile += 2;
} else if (movingDir > 1) {
xTile += 4 + ((numSteps >> walkingSpeed) & 1) * 2;
flipTop = (movingDir - 1) % 2;
}
int modifier = 8 * scale;
int xOffset = x - modifier / 2;
int yOffset = y - modifier / 2 - 4;
if (isSwimming) {
int waterColour = 0;
yOffset += 4;
if (tickCount % 60 < 15) {
waterColour = Colours.get(-1, -1, 225, -1);
} else if (15 <= tickCount % 60 && tickCount % 60 < 30) {
yOffset -= 1;
waterColour = Colours.get(-1, 225, 115, -1);
} else if (30 <= tickCount % 60 && tickCount % 60 < 45) {
waterColour = Colours.get(-1, 115, -1, 225);
} else {
yOffset -= 1;
waterColour = Colours.get(-1, 225, 115, -1);
}
screen.render(xOffset, yOffset+3, 0 + 27 * 32, waterColour, 0x00, 1);
screen.render(xOffset + 8, yOffset+3, 0 + 27 * 32, waterColour, 0x01, 1);
}
//Upper Body
screen.render(xOffset + (modifier * flipTop), yOffset, xTile + yTile * 32, colour, flipTop, scale);
screen.render(xOffset + modifier - (modifier * flipTop), yOffset, (xTile + 1) + yTile * 32, colour, flipTop, scale);
if (!isSwimming) {
//Lower Body
screen.render(xOffset + (modifier * flipBottom), yOffset + modifier, xTile + (yTile+1) * 32, colour, flipBottom, scale);
screen.render(xOffset + modifier - (modifier * flipBottom), yOffset + modifier, (xTile+1) + (yTile+1) * 32, colour, flipBottom, scale);
}
}
public boolean hasCollided(int xa, int ya) {
int xMin = 0;
int xMax = 7;
int yMin = 3;
int yMax = 7;
for (int x = xMin; x < xMax; x++) {
if (isSolidTile(xa, ya, x, yMin)) {
return true;
}
}
for (int x = xMin; x < xMax; x++) {
if (isSolidTile(xa, ya, x, yMax)) {
return true;
}
}
for (int y = yMin; y < yMax; y++) {
if (isSolidTile(xa, ya, xMin, y)) {
return true;
}
}
for (int y = yMin; y < yMax; y++) {
if (isSolidTile(xa, ya, xMax, y)) {
return true;
}
}
return false;
}
public int getPlayerHealth() {
return health;
}
public int getPlayerMoveDir() {
return movingDir;
}
}
Projectile Class:
package ca.runner.game.entities;
import ca.runner.level.Level;
import ca.runner.level.tiles.Tile;
public abstract class Projectile extends Entity{
protected String name;
protected int speed;
protected int numSteps = 0;
protected boolean isMoving;
protected int movingDir = 1;
protected int scale;
protected int damage;
protected boolean emitter;
protected int moveDir;
public Projectile(Level level, boolean isEmitter, String name, int x, int y, int speed, int damage, int scale, int MoveDir) {
super(level);
this.name = name;
this.x = x;
this.y = y;
this.speed = speed;
this.damage = damage;
this.emitter = isEmitter;
this.scale = scale;
this.moveDir = moveDir;
}
public boolean isEmitter() {
return emitter;
}
public void move(int xa, int ya) {
//if(!hasCollided(xa, ya)) {
x+= xa * speed;
y += ya * speed;
//} else {
// level.removeEntity(this);
//}
}
//public abstract boolean hasCollided(int xa, int ya);
protected boolean isSolidTile(int xa, int ya, int x, int y) {
if (level == null) { return false;}
Tile lastTile = level.getTile((this.x + x) >> 3, (this.y + y) >> 3);
Tile newTile = level.getTile((this.x + x + xa) >> 3, (this.y + y + ya) >> 3);
if (!lastTile.equals(newTile) && newTile.isSolid()) {
return true;
}
return false;
}
public String getName() {
return name;
}
}
EDIT: Added the full stacktrace
I would guess that the addEntity method of the Level class adds the Fireball to a collection.
The "tick" method in your Player class is probably overriding a tick method in the "Mob" class that is called from something that loops over the same collection that addEntity wants to add to.
Have a look at the documentation for your iterator, it will tell you that it throws the "ConcurrentModificationException" if someone modifies the collection while it is iterating across it.
I can think of several ways to solve the problem.
Add the Fireball to a list of things to be added to your collection after the tick is done.
Keep some kind of reference to the iterator that you can call to make the addition. (Feels like a involved solution since you might need to handle "inTick" and "outsideTick" differently.
Iterate over the collection using an old-style "getAt" to retrieve the values. This will mean you are responsible for the concurrency yourself.
I hope this helps.
Okay, so I'm in the progress of making a game, and I need the collisions to work. I have an if() { } else if() {} -statement, but BOTH of them are being called. Here is my code:
Inside my Player Class:
public Rectangle[] tileRect;
public void update() {
tileRect = new Rectangle[Level1.tiles.size()];
for (int w = 0; w < Level1.tiles.size(); w++) {
Tile m = (Tile) Level1.tiles.get(w);
tileRect[w] = m.getBounds();
if(tileRect[w].intersects(getRect())) {
System.out.println("intersecting");
dy = 0;
} else if (!tileRect[w].intersects(getRect())){
dy = 4;
}
}
x += dx;
y += dy;
}
public Rectangle getRect() {
return new Rectangle(x, y, 32, 32);
}
Here is my Tile class (the Level1.tiles is an arrayList of tiles):
package level;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Tile extends Rectangle {
// Defines the id of the tile, used for setting textures.
private static final long serialVersionUID = 1L;
public int id;
// Location
public int x;
public int y;
// Variables for the terrain sprite sheet.
public BufferedImage image;
public String imageLocation;
public BufferedImage[] sprite;
public int rows = 16;
public int collumns = 16;
public int width = 16;
public int height = 16;
public Tile(int idVal, int xPos, int yPos) {
x = xPos * 32;
y = yPos * 32;
id = idVal;
setBounds(x, y, 32, 32);
createImages();
}
public BufferedImage getImage() {
return sprite[id];
}
public void createImages() {
imageLocation = "res/tile/terrain.png";
try {
image = ImageIO.read(new File(imageLocation));
} catch (IOException e) {
System.out.println("Unable to find file " + imageLocation
+ ", printing stack trace!");
e.printStackTrace();
}
sprite = new BufferedImage[rows * collumns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < collumns; j++) {
sprite[(i * collumns) + j] = image.getSubimage(j * width, i
* height, width, height);
}
}
}
public int getXLoc() {
return x;
}
public int getYLoc() {
return y;
}
public void setX(int xPos) {
x = xPos;
}
public void setY(int yPos) {
y = yPos;
}
}
I'm getting the "intersecting" message in the console, but the player is still falling down (because dy = 4). Please help! I've been trying to solve this all morning...
If and Else cannot both be caught at the same time.
Looks like you are looping through, seeing an intersection, then continuing to loop through regardless.
Try adding a break command to your for loop.
if(tileRect[w].intersects(getRect())) {
System.out.println("intersecting");
dy = 0;
break;
} else if (!tileRect[w].intersects(getRect())){
dy = 4;
}
The break will stop your for loop from continuing and you will exit the loop with dy = 0; rather than going onto the next tile and changing it back to dy = 4;
if and else if cannot be called in the same run. If if condition is true, then any else is never run (not even checked). It's probably different runs. Debug or put a log to see the flow.
Also
if(tileRect[w].intersects(getRect())) {
System.out.println("intersecting");
dy = 0;
} else if (!tileRect[w].intersects(getRect())){
dy = 4;
}
is much simpler written as
if(tileRect[w].intersects(getRect())) {
System.out.println("intersecting");
dy = 0;
} else {
dy = 4;
}