@Override public int compare(Entity a, Entity b) { if (a.getY() + a.getHeight() < b.getY() + b.getHeight()) { return -1; } return 1; }
public double getNetGravAccel(double x1, double y1, char component, Entity e) { double net = 0; if (ents.size() <= 1) return 0; try { for (Entity other : ents) { double x2 = other.getX(); double y2 = other.getY(); if (x1 == x2 && y1 == y2) // if distance is 0 (testing itself) then it will divide by 0 continue; double distance = Util.distance(x1, y1, x2, y2); // if(Refs.sim.isCollisionType(Simulation.NONCOLLIDE)) //if current collision type is // noncollide if (Util.areColliding(e, other)) // if colliding, no gravitational effect continue; double accel = 0; accel = other.getMass() / Math.pow(distance, 2); double proportion = 1; if (component == 'x') proportion = ((x2 - x1)) / distance; if (component == 'y') proportion = ((y2 - y1)) / distance; net += accel * proportion; } } catch (Exception ex) { } return Refs.sim.getGravitationConstant() * net; }
/** @see org.newdawn.asteroids.entity.Entity#collides(org.newdawn.asteroids.entity.Entity) */ public boolean collides(Entity other) { // We're going to use simple circle collision here since we're // only worried about 2D collision. // // Normal math tells us that if the distance between the two // centres of the circles is less than the sum of their radius // then they collide. However, working out the distance between // the two would require a square root (Math.sqrt((dx*dx)+(dy*dy)) // which could be quite slow. // // Instead we're going to square the sum of their radius and compare // that against the un-rooted value. This is equivilent but // much faster // Get the size of the other entity and combine it with our // own, giving the range of collision. Square this so we can // compare it against the current distance. float otherSize = other.getSize(); float range = (otherSize + getSize()); range *= range; // Get the distance on X and Y between the two entities, then // find the squared distance between the two. float dx = getX() - other.getX(); float dy = getY() - other.getY(); float distance = (dx * dx) + (dy * dy); // if the squared distance is less than the squared range // then we've had a collision! return (distance <= range); }
/** * Spawns a mob somewhere on the map. Ensures it doesn't intersect anything and is on a spawn tile * * @param mob * @return */ public boolean spawnMob(Mob mob) { float x = mob.getX(); float y = mob.getY(); TextureSet textureSet = mob.getWalkingTextureSet(); // Check mob isn't out of bounds. if (x < 0 || x > getMapWidth() - textureSet.getWidth() || y > getMapHeight() - textureSet.getHeight()) { return false; } // Check mob doesn't intersect anything. for (Entity entity : entities) { if (entity instanceof Character && (mob.intersects(entity.getX(), entity.getY(), entity.getWidth(), entity.getHeight()) || mob.collidesX(0) || mob.collidesY(0))) { return false; } } if (getSpawnLayer().getCell((int) x / getTileWidth(), (int) y / getTileHeight()) == null) { return false; } entities.add(mob); return true; }
public void setEntitys(ArrayList<Entity> realEntities) { for (Entity e : realEntities) { JsonEntity JE = new JsonEntity(e.getX(), e.getY(), e.isSolid(), e.getClass().getName()); if (e.isSign()) { JE.setSignText(e.getSignText()); } entities.add(JE); } }
/** Initialise the Camera variables to the player position. */ private void initToPlayerPosition() { // Cycle through all of the map objects // initialise the player when the player object is found for (int i = 0; i < map.getObjectGroupCount(); i++) { for (int j = 0; j < map.getObjectCount(i); j++) { if (map.getObjectName(i, j).equalsIgnoreCase("Player")) { player.setX(map.getObjectX(i, j) + (player.getWidth() / 2)); player.setY(map.getObjectY(i, j)); this.setPlayerStartXY(player.getX(), player.getY()); } } } vPlayerX = player.getX(); vPlayerY = player.getY(); lastPlayerX = (int) vPlayerX / tileWidth; lastPlayerY = (int) vPlayerY / tileHeight; curPlayerX = lastPlayerX; curPlayerY = lastPlayerY; }
private void drawHealthBar(Graphics g, Entity entity, int xOffset, int yOffset) { int width = entity.getTexture().getWidth(); float xPos = entity.getX() + xOffset; int height = entity.getTexture().getHeight(); float yPos = entity.getY() + yOffset + height; g.setColor(new Color(200, 0, 0)); g.fillRect(xPos, yPos, width, 3); g.setColor(new Color(0, 200, 0)); g.fillRect(xPos, yPos, width * (entity.getHealth() / entity.getMaxHealth()), 3); }
/** * Creates a mob and adds it to the list of entities, but only if it doesn't intersect with * another character. * * @param x the initial x coordinate * @param y the initial y coordinate * @param health the initial health of the mob * @param textureSet the texture set to use * @param speed how fast the mob moves in pixels per second * @return true if the mob was successfully added, false if there was an intersection and the mob * wasn't added */ public boolean createMob( Mob mob, float x, float y, int health, TextureSet textureSet, int speed) { // Check mob isn't out of bounds. if (x < 0 || x > getMapWidth() - textureSet.getWidth() || y > getMapHeight() - textureSet.getHeight()) { return false; } // Check mob doesn't intersect anything. for (Entity entity : entities) { if (entity instanceof Character && (mob.intersects(entity.getX(), entity.getY(), entity.getWidth(), entity.getHeight()) || mob.collidesX(0) || mob.collidesY(0))) { return false; } } entities.add(mob); return true; }
public void checkCollisions(Entity e) { try { for (Entity other : ents) if (e != other) { if (Refs.sim.isCollisionType(Simulation.COLLIDE)) { // collision type collide try { // e.subliminalUpdate(); if (!other.hasCheckedCollisions() && !other.shouldKill()) if (Util.areColliding(e, other)) { // e.subliminalUpdate(); e.collide(other, 1); // other.collide(e, 1); while (Util.areColliding(e, other)) { e.subliminalUpdate(); other.subliminalUpdate(); } // e.subliminalUpdate(); // other.subliminalUpdate(); continue; } throw new Exception(); } catch (Exception ex) { } } else if (Refs.sim.isCollisionType(Simulation.ABSORB)) { // collision type absorb if (!other.hasCheckedCollisions() && !other.shouldKill()) if (Util.areColliding(e, other)) { Collision coll = Util.getCollisionType(e, other); // if collision is between 2 balls if (coll == Collision.BALL_X_BALL) { e.setKillMe(true); other.setKillMe(true); Ball product = new Ball( (int) Util.average(e.getX(), other.getX(), e.getMass(), other.getMass()), (int) Util.average(e.getY(), other.getY(), e.getMass(), other.getMass()), (int) Math.sqrt( Math.pow(e.getRadius(), 2) + Math.pow(other.getRadius(), 2)), (int) Util.average(e.getVX(), other.getVX(), e.getMass(), other.getMass()), (int) Util.average(e.getVY(), other.getVY(), e.getMass(), other.getMass()), Util.average( e.getColor(), other.getColor(), e.getMass(), other.getMass())); purgatory.add(product); // if collision is between a ball and a black hole } else if (coll == Collision.BALL_X_BH) { if (e instanceof Ball) e.setKillMe(true); else other.setKillMe(true); // if collision is between a black hole and a black hole } else if (coll == Collision.BH_X_BH) { e.setKillMe(true); other.setKillMe(true); BlackHole product = new BlackHole( (int) Util.average(e.getX(), other.getX(), e.getMass(), other.getMass()), (int) Util.average(e.getY(), other.getY(), e.getMass(), other.getMass()), (int) Math.sqrt( Math.pow(e.getRadius(), 2) + Math.pow(other.getRadius(), 2))); purgatory.add(product); } } } } } catch (Exception ex) { } e.setCheckedCollisions(true); }
/** * Updates all entities in this Round. * * @param delta the time elapsed since the last update */ public void update(float delta) { powerUpManager.update(delta); floatyNumbersManager.update(delta); if (objective != null) { objective.update(delta); if (objective.getStatus() == Objective.OBJECTIVE_COMPLETED) { parent.showWinScreen(player.getScore()); } else if (player.isDead()) { parent.showLoseScreen(); } } // int updateNumber =0, totalNumber=entities.size(), numMobs=0; for (int i = 0; i < entities.size(); i++) { Entity entity = entities.get(i); /* if(entity instanceof Mob) numMobs++;*/ if (entity.isRemoved()) { if (entity instanceof Mob && ((Mob) entity).isDead()) { int score = (int) (((Mob) entity).getScore() * (powerUpManager.getIsActive(PowerupManager.powerupTypes.SCORE_MULTIPLIER) ? Player.PLAYER_SCORE_MULTIPLIER : 1)); player.addScore(score); floatyNumbersManager.createScoreNumber(score, entity.getX(), entity.getY()); if (objective.getObjectiveType() == Objective.objectiveType.BOSS) { spawnRandomMobs(1, 0, 0, 1000, 1000); } } entities.remove(i); } else if ((entity.distanceTo(player.getX(), player.getY()) < UPDATE_DISTANCE_X) && (entity.distanceTo(player.getX(), player.getY()) < UPDATE_DISTANCE_Y)) { // Don't bother updating entities that aren't on screen. entity.update(delta); // updateNumber++; } } if (Gdx.input.isKeyJustPressed(Input.Keys.P)) { for (int x = 0; x < 1000; x++) { createProjectile( MathUtils.random(300, 1500), MathUtils.random(300, 1500), MathUtils.random(300, 1500), MathUtils.random(300, 1500), 500, 0, 0, 0, player); } } // System.out.println("total:"+totalNumber+" updated:"+updateNumber+" numMobs:"+numMobs); }
public void draw(Batch batch, float alpha, Entity entity) { this.update(); if (entity instanceof Protagonist) { Protagonist bernard = (Protagonist) entity; // if (entity.textureRegion.isFlipX()) { // temp = animation.getKeyFrame(elapsed); // temp.flip(true, false); // batch.draw(animation.getKeyFrame(elapsed), entity.getX() - // Constants.TILEDIMENSION * width, entity.getY(), Constants.TILEDIMENSION * width, // Constants.TILEDIMENSION * height); // temp.flip(true, false); // } else { // batch.draw(animation.getKeyFrame(elapsed), entity.getX() + // Constants.TILEDIMENSION, entity.getY(), Constants.TILEDIMENSION * width, // Constants.TILEDIMENSION * height); // } if (bernard.getDirection() == Constants.Direction.LEFT) { batch.draw( animation.getKeyFrame(elapsed), entity.getX() - 50, entity.getY() - 10, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, 180); } else if (bernard.getDirection() == Constants.Direction.RIGHT) { batch.draw( animation.getKeyFrame(elapsed), entity.getX() + Constants.TILEDIMENSION, entity.getY(), Constants.TILEDIMENSION * width, Constants.TILEDIMENSION * height); } else if (bernard.getDirection() == Constants.Direction.UP) { batch.draw( animation.getKeyFrame(elapsed), entity.getX(), entity.getY() + Constants.TILEDIMENSION, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, 90); } else if (bernard.getDirection() == Constants.Direction.DOWN) { batch.draw( animation.getKeyFrame(elapsed), entity.getX(), entity.getY() - Constants.TILEDIMENSION, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, -90); } if (bernard.getLightBarrierLimit() > 0 && elapsed >= 0.25f) { elapsedLight += Gdx.graphics.getDeltaTime(); // if (bernard.textureRegion.isFlipX()) { // temp = light.getKeyFrame(elapsedLight); // temp.flip(true, false); // batch.draw(light.getKeyFrame(elapsedLight), bernard.getX() - // Constants.TILEDIMENSION * width, bernard.getY(), Constants.TILEDIMENSION * width, // Constants.TILEDIMENSION * height); // temp.flip(true, false); // } else { // batch.draw(light.getKeyFrame(elapsedLight), bernard.getX() + // Constants.TILEDIMENSION, bernard.getY(), Constants.TILEDIMENSION * width, // Constants.TILEDIMENSION * height); // } if (bernard.getDirection() == Constants.Direction.LEFT) { batch.draw( light.getKeyFrame(elapsedLight), entity.getX() - 50, entity.getY() - 5, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, 180); } else if (bernard.getDirection() == Constants.Direction.RIGHT) { batch.draw( light.getKeyFrame(elapsedLight), entity.getX() + Constants.TILEDIMENSION, entity.getY(), Constants.TILEDIMENSION * width, Constants.TILEDIMENSION * height); } else if (bernard.getDirection() == Constants.Direction.UP) { batch.draw( light.getKeyFrame(elapsedLight), entity.getX(), entity.getY() + 50, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, 90); } else if (bernard.getDirection() == Constants.Direction.DOWN) { batch.draw( light.getKeyFrame(elapsedLight), entity.getX(), entity.getY() - 50, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION / 2, Constants.TILEDIMENSION * width + 50, Constants.TILEDIMENSION * height, 1, 1, -90); } if (light.isAnimationFinished(elapsedLight)) { bernard.setLightBarrierLimit(bernard.getLightBarrierLimit() - 1); // String l = String.valueOf(bernard.getLightBarrierLimit()); // Gdx.app.log("LightBarrier", l); if (bernard.getLightBarrierLimit() == 0) { bernard.setExecuteLightBarrier(false); bernard.lightningInfusionCooldown = 5; } elapsedLight = 0f; } } } }
public void drawBuffer() { Graphics2D b = buffer.createGraphics(); // DrawPanel Graphics2D pl_b = buffer.createGraphics(); Graphics2D pl_c = buffer.createGraphics(); rkt = buffer.createGraphics(); AffineTransform rkt_aff = new AffineTransform(); Graphics2D envi[] = new Graphics2D[amountEnv]; AffineTransform enviTrans[] = new AffineTransform[amountEnv]; b.setColor(Color.BLACK); b.fillRect(0, 0, w, h); // #if (Default) // @ // #elif (Blue_White) // @ ii_bg = new ImageIcon("imgs/Hintergrund/HgBlauWeiss1.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Blue_White_Green) // @ ii_bg = new ImageIcon("imgs/Hintergrund/HgBlauWeissGruen.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Purple_White) // @ ii_bg = new ImageIcon("imgs/Hintergrund/HgLilaWeiss.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Glass) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundglass05.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Lava) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundlava01.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Limba) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundlimba.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Old) ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundoldpnt01.gif"); img_bg = ii_bg.getImage(); b.drawImage(img_bg, w, w, this); // #elif (Ov_Paper) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundov_paper.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Paper) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundpaper05.gif"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Univ) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrunduniv01.jpg"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Water) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundwater01.jpg"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #elif (Water_2) // @ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundwater05.jpg"); // @ img_bg = ii_bg.getImage(); // @ b.drawImage(img_bg, w, w, this); // #endif b.setColor(Color.gray); b.fillRect(0, 0, w, 25); // oben b.fillRect(0, h - 50, w, 25); // unten b.fillRect(0, 0, 25, h); // links b.fillRect(w - 35, 0, 30, h); // rechts b.setColor(Color.WHITE); // rocket // #if (tar) // #if (Rectangle) // @ if (current_Player.isRocket()){ // @ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); // @ rkt.setTransform(rkt_aff); // @ System.out.println("Rok X:"+sch.getX()+" Rok Y:"+sch.getY()); // @ rkt.drawRect(sch.getX()+ current_Player.getWidth()/2, sch.getY() + // current_Player.getHeight()/2, kaliber, kaliber);} // Rocket 4Eck // #endif // #if (Oval) // @ if (current_Player.isRocket()){ // @ b.drawOval(sch.getX()+ current_Player.getWidth()/2, sch.getY() + // current_Player.getHeight()/2, kaliber, kaliber);} // Rocket Oval // #endif // #if (aa31) // @ if (current_Player.isRocket()){ // @ try { // @ rocketFire = ImageIO.read(new File("imgs/aa31.gif")); // @ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); // @ rkt.setTransform(rkt_aff); // @ rkt.drawImage(rocketFire, null, (int)sch.getX(), (int)sch.getY()); // @ //rkt.drawImage(rocketFire, null, (int)current_Player.getX(), // (int)current_Player.getY()); // @ } catch (IOException e) { // @ } // @ } // #endif // #if (Portal) // @ if (current_Player.isRocket()){ // @ try { // @ rocketFire = ImageIO.read(new File("imgs/portal.gif")); // @ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); // @ rkt.setTransform(rkt_aff); // @ rkt.drawImage(rocketFire, null, // sch.getX()+current_Player.getWidth()/2, sch.getY()+current_Player.getHeight()/2); // @ } catch (IOException e) { // @ } // @ } // #endif // #if (Nino) // @ if (current_Player.isRocket()){ // @ try { // @ rocketFire = ImageIO.read(new File("imgs/nino.gif")); // @ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); // @ rkt.setTransform(rkt_aff); // @ rkt.drawImage(rocketFire, null, // sch.getX()+current_Player.getWidth()/2, sch.getY()+current_Player.getHeight()/2); // @ } catch (IOException e) { // @ } // @ } // #endif // #endif for (int i = 0; i <= amountEnv - 1; i++) { envi[i] = buffer.createGraphics(); enviTrans[i] = new AffineTransform(); envi[i].setTransform(enviTrans[i]); envi[i].drawImage(env[i].getImg(), env[i].getX(), env[i].getY(), this); } for (int i = 0; i < 8; i++) { if (powerUps[i].isAktiv()) { b.setColor(powerUps[i].getCol()); b.drawImage(powerUps[i].getImg(), powerUps[i].getX(), powerUps[i].getY(), this); } } b.setColor(Color.WHITE); b.drawString("BP: " + current_Player.getBp(), 10, 20); b.drawString("TP P1/P2: " + player_1.getTp() + " / " + player_2.getTp(), 100, 20); if (current_Player.getSch().getEnd_X() != 0 && current_Player.getSch().getEnd_Y() != 0) { b.setColor(Color.YELLOW); b.drawLine( (int) current_Player.getSch().getStart_X(), (int) current_Player.getSch().getStart_Y(), (int) current_Player.getSch().getEnd_X(), (int) current_Player.getSch().getEnd_Y()); b.setColor(Color.WHITE); for (int i = 0; i < current_Player.getSch().getArImg().length; i++) { if (current_Player.getSch().getArImg()[i] != null && current_Player.getSch().isIsActive()) { b.drawImage( current_Player.getSch().getArImg()[i], (int) current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this) / 2, (int) current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this) / 2, (int) (current_Player.getSch().getArImg()[i].getWidth(this) * (current_Player.getSch().getSpeed() / 150)), (int) (current_Player.getSch().getArImg()[i].getHeight(this) * (current_Player.getSch().getSpeed() / 150)), this); if (timeCounter == 75) { System.out.println("----------------------><---------------------"); if (player_1 .getBounds() .intersects( (int) current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this) / 2, (int) current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this) / 2, (int) (current_Player.getSch().getArImg()[i].getWidth(this) * (current_Player.getSch().getSpeed() / 150)), (int) (current_Player.getSch().getArImg()[i].getHeight(this) * (current_Player.getSch().getSpeed() / 150)))) { player_1.setTp(player_1.getTp() - (int) current_Player.getSch().getSpeed() / 4); System.out.println("----------------------> P1 <---------------------"); } if (player_2 .getBounds() .intersects( (int) current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this) / 2, (int) current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this) / 2, (int) (current_Player.getSch().getArImg()[i].getWidth(this) * (current_Player.getSch().getSpeed() / 150)), (int) (current_Player.getSch().getArImg()[i].getHeight(this) * (current_Player.getSch().getSpeed() / 150)))) { player_2.setTp(player_2.getTp() - (int) current_Player.getSch().getSpeed() / 4); System.out.println("----------------------> P2 <---------------------"); } } } if (timeCounter >= 150) { timeCounter = 0; current_Player.getSch().setIsActive(false); current_Player.getSch().setEnd_X(0); current_Player.getSch().setEnd_Y(0); } if (current_Player.getSch().isIsActive()) timeCounter += 1; System.out.println("timecounter: " + timeCounter); } } if (player_1.getTp() <= 0) b.drawString("SPIELER 2 HAT GEWONNEN !", w / 2, h / 2); if (player_2.getTp() <= 0) b.drawString("SPIELER 1 HAT GEWONNEN !", w / 2, h / 2); current_Player.setStop(false); b.setColor(Color.red); AffineTransform a = new AffineTransform(); a.rotate( current_Player.getDegree(), current_Player.getX() + current_Player.getWidth() / 2, current_Player.getY() + current_Player.getHeight() / 2); ((Graphics2D) pl_b).setTransform(a); pl_b.drawImage( current_Player.getImg(), (int) current_Player.getX(), (int) current_Player.getY(), this); System.out.println( "P1 X:" + (int) current_Player.getX() + " P1 Y:" + (int) current_Player.getY()); System.out.println("P1 W:" + current_Player.getWidth() + " P1 H:" + current_Player.getHeight()); AffineTransform a2 = new AffineTransform(); a2.rotate( other_Player.getDegree(), other_Player.getX() + other_Player.getWidth() / 2, other_Player.getY() + other_Player.getHeight() / 2); ((Graphics2D) pl_c).setTransform(a2); pl_c.drawImage( other_Player.getImg(), (int) other_Player.getX(), (int) other_Player.getY(), this); if (current_Player.isCollision() == true) { current_Player.setStop(true); if (timecount > 10) { b.setColor(Color.WHITE); b.drawString("C O L L I S I O N !", (int) w / 2 - 50, (int) h / 2); timecount--; } else { timecount = 0; current_Player.setBp(0); current_Player.setX(300); current_Player.setY(100); current_Player.getSch().setEnd_X(1); current_Player.getSch().setEnd_Y(1); current_Player.getSch().setStart_X(1); current_Player.getSch().setStart_Y(1); } b.dispose(); } }
/** Updates the enitities position depending on nearest food and attacking */ public void update() { radarEntity.setX(entity.getX()); radarEntity.setY(entity.getY()); Entity target = entity.getWorld().getNearbyFood(radarEntity, entity); if (entity.getSizeValue() * entity.getBodyParts().size() < prevEntityValue * entity.getBodyParts().size()) runAway = true; if (!runAway) { if (target != null) { int xTarget = target.getX(); int yTarget = target.getY(); if (target.getType() < 3) { entity.setColor(Color.orange); entity.setVelocity(MAX_ATTACK_VELOCITY); entity.setAcceleration(MAX_ATTACK_ACCELERATION); entity.setDeceleration(MAX_ATTACK_ACCELERATION / 2); entity.setTarget(xTarget, yTarget); } else { entity.setColor(Color.white); entity.setVelocity(MAX_VELOCITY); entity.setAcceleration(MAX_ACCELERATION); entity.setDeceleration(MAX_ACCELERATION / 2); entity.setTarget(xTarget, yTarget); } } else { entity.setColor(Color.white); entity.setVelocity(MAX_VELOCITY); entity.setAcceleration(MAX_ACCELERATION); entity.setDeceleration(MAX_ACCELERATION / 2); currTime = timer.milliTime(); // get the time we are at accumulator += currTime - prevTime; // add time taken since last loop to accumulator prevTime = currTime; // set new previous time if (accumulator >= TIMESTEP_MILLIS) { // while there is an update rate in the accumulator boolean bx = rbooleanx.nextBoolean(); boolean by = rbooleany.nextBoolean(); int xTarget = entity.getX(); int yTarget = entity.getY(); if (bx == true) xTarget += rx.nextInt(RANGE); else xTarget += (rx.nextInt(RANGE)) * -1; if (by == true) yTarget += ry.nextInt(RANGE); else yTarget += (ry.nextInt(RANGE)) * -1; entity.setTarget(xTarget, yTarget); accumulator = 0; } } prevEntityValue = entity.getSizeValue(); } else // we're running away { entity.setColor(Color.blue); entity.setVelocity(MAX_ATTACK_VELOCITY); entity.setAcceleration(MAX_ATTACK_ACCELERATION); currTime = timer.milliTime(); // get the time we are at accumulator += currTime - prevTime; // add time taken since last loop to accumulator runningTime += currTime - prevTime; prevTime = currTime; // set new previous time if (accumulator >= TIMESTEP_MILLIS) { // while there is an update rate in the accumulator int xTarget = entity.getX(); int yTarget = entity.getY(); if (xTarget < 0) xTarget -= FLEE_RANGE; else xTarget += FLEE_RANGE; if (yTarget < 0) yTarget -= FLEE_RANGE; else yTarget += FLEE_RANGE; entity.setTarget(xTarget, yTarget); accumulator = 0; } if (runningTime > 10000) { runAway = false; runningTime = 0; prevEntityValue = entity.getSizeValue(); accumulator = TIMESTEP_MILLIS; } } }
@EventHandler public void onPacketProcess(PacketProcessEvent event) { Packet packet = event.getPacket(); if (packet instanceof Packet5PlayerInventory) { Packet5PlayerInventory inventoryPacket = (Packet5PlayerInventory) packet; Entity entity = getEntityById(inventoryPacket.entityID); if (entity == null || !(entity instanceof LivingEntity)) return; LivingEntity livingEntity = (LivingEntity) entity; livingEntity.setWornItemAt(inventoryPacket.slot, inventoryPacket.item); } else if (packet instanceof Packet8UpdateHealth) { Packet8UpdateHealth updateHealthPacket = (Packet8UpdateHealth) packet; MainPlayerEntity player = bot.getPlayer(); player.setHealth(updateHealthPacket.healthMP); player.setHunger(updateHealthPacket.food); } else if (packet instanceof Packet9Respawn) { synchronized (chunks) { chunks.clear(); } } else if (packet instanceof Packet20NamedEntitySpawn) { Packet20NamedEntitySpawn spawnPacket = (Packet20NamedEntitySpawn) packet; PlayerEntity entity = new PlayerEntity(this, spawnPacket.entityId, spawnPacket.name); entity.setX(spawnPacket.xPosition / 32D); entity.setY(spawnPacket.yPosition / 32D); entity.setZ(spawnPacket.zPosition / 32D); entity.setYaw(spawnPacket.rotation); entity.setPitch(spawnPacket.pitch); entity.setWornItemAt(0, new BasicItemStack(spawnPacket.currentItem, 1, 0)); spawnEntity(entity); } else if (packet instanceof Packet21PickupSpawn) { Packet21PickupSpawn spawnPacket = (Packet21PickupSpawn) packet; ItemEntity entity = new ItemEntity(this, spawnPacket.entityId, spawnPacket.item); entity.setX(spawnPacket.xPosition / 32D); entity.setY(spawnPacket.yPosition / 32D); entity.setZ(spawnPacket.zPosition / 32D); spawnEntity(entity); } else if (packet instanceof Packet22Collect) { Entity entity = getEntityById(((Packet22Collect) packet).collectedEntityId); if (entity != null) despawnEntity(entity); } else if (packet instanceof Packet23VehicleSpawn) { Packet23VehicleSpawn spawnPacket = (Packet23VehicleSpawn) packet; Entity entity = null; Class<? extends Entity> entityClass = EntityList.getObjectEntityClass(spawnPacket.type); if (entityClass == null) return; try { Constructor<? extends Entity> constructor = entityClass.getConstructor(World.class, Integer.TYPE); entity = constructor.newInstance(this, spawnPacket.entityId); } catch (Exception exception) { exception.printStackTrace(); return; } entity.setX(spawnPacket.xPosition / 32D); entity.setY(spawnPacket.yPosition / 32D); entity.setZ(spawnPacket.zPosition / 32D); entity.setYaw(0); entity.setPitch(0); spawnEntity(entity); } else if (packet instanceof Packet24MobSpawn) { Packet24MobSpawn mobSpawnPacket = (Packet24MobSpawn) packet; LivingEntity entity = null; Class<? extends LivingEntity> entityClass = EntityList.getLivingEntityClass(mobSpawnPacket.type); if (entityClass == null) return; try { Constructor<? extends LivingEntity> constructor = entityClass.getConstructor(World.class, Integer.TYPE); entity = constructor.newInstance(this, mobSpawnPacket.entityId); } catch (Exception exception) { exception.printStackTrace(); return; } entity.setX(mobSpawnPacket.xPosition / 32D); entity.setY(mobSpawnPacket.yPosition / 32D); entity.setZ(mobSpawnPacket.zPosition / 32D); entity.setYaw((mobSpawnPacket.yaw * 360) / 256F); entity.setPitch((mobSpawnPacket.pitch * 360) / 256F); entity.setHeadYaw((mobSpawnPacket.headYaw * 360) / 256F); if (mobSpawnPacket.getMetadata() != null) entity.updateMetadata(mobSpawnPacket.getMetadata()); spawnEntity(entity); } else if (packet instanceof Packet25EntityPainting) { Packet25EntityPainting paintingPacket = (Packet25EntityPainting) packet; PaintingEntity entity = new PaintingEntity( this, paintingPacket.entityId, ArtType.getArtTypeByName(paintingPacket.title)); entity.setX(paintingPacket.xPosition); entity.setY(paintingPacket.yPosition); entity.setZ(paintingPacket.zPosition); entity.setDirection(paintingPacket.direction); spawnEntity(entity); } else if (packet instanceof Packet26EntityExpOrb) { } else if (packet instanceof Packet29DestroyEntity) { Packet29DestroyEntity destroyEntityPacket = (Packet29DestroyEntity) packet; for (int id : destroyEntityPacket.entityIds) { Entity entity = getEntityById(id); if (entity != null) { despawnEntity(entity); entity.setDead(true); } } } else if (packet instanceof Packet30Entity) { Packet30Entity entityPacket = (Packet30Entity) packet; Entity entity = getEntityById(entityPacket.entityId); if (entity == null) return; entity.setX(entity.getX() + (entityPacket.xPosition / 32D)); entity.setY(entity.getY() + (entityPacket.yPosition / 32D)); entity.setZ(entity.getZ() + (entityPacket.zPosition / 32D)); if (packet instanceof Packet31RelEntityMove || packet instanceof Packet33RelEntityMoveLook) { entity.setYaw((entityPacket.yaw * 360) / 256F); entity.setPitch((entityPacket.pitch * 360) / 256F); } } else if (packet instanceof Packet34EntityTeleport) { Packet34EntityTeleport teleportPacket = (Packet34EntityTeleport) packet; Entity entity = getEntityById(teleportPacket.entityId); if (entity == null) return; entity.setX(teleportPacket.xPosition / 32D); entity.setY(teleportPacket.yPosition / 32D); entity.setZ(teleportPacket.zPosition / 32D); entity.setYaw((teleportPacket.yaw * 360) / 256F); entity.setPitch((teleportPacket.pitch * 360) / 256F); } else if (packet instanceof Packet35EntityHeadRotation) { Packet35EntityHeadRotation headRotatePacket = (Packet35EntityHeadRotation) packet; Entity entity = getEntityById(headRotatePacket.entityId); if (entity == null || !(entity instanceof LivingEntity)) return; ((LivingEntity) entity).setHeadYaw((headRotatePacket.headRotationYaw * 360) / 256F); } else if (packet instanceof Packet39AttachEntity) { Packet39AttachEntity attachEntityPacket = (Packet39AttachEntity) packet; Entity rider = getEntityById(attachEntityPacket.entityId); if (rider == null) return; Entity riding = null; if (attachEntityPacket.vehicleEntityId == -1) { if (rider.getRiding() != null) { rider.getRiding().setRider(null); rider.setRiding(null); } } else { riding = getEntityById(attachEntityPacket.vehicleEntityId); if (riding == null) return; rider.setRiding(riding); riding.setRider(rider); } } else if (packet instanceof Packet40EntityMetadata) { Packet40EntityMetadata metadataPacket = (Packet40EntityMetadata) packet; Entity entity = getEntityById(metadataPacket.entityId); if (entity == null) return; entity.updateMetadata(metadataPacket.getMetadata()); } else if (packet instanceof Packet43Experience) { Packet43Experience experiencePacket = (Packet43Experience) packet; MainPlayerEntity player = bot.getPlayer(); player.setExperienceLevel(experiencePacket.experienceLevel); player.setExperienceTotal(experiencePacket.experienceTotal); } else if (packet instanceof Packet51MapChunk) { if (bot.isMovementDisabled()) return; Packet51MapChunk mapChunkPacket = (Packet51MapChunk) packet; processChunk( mapChunkPacket.x, mapChunkPacket.z, mapChunkPacket.chunkData, mapChunkPacket.bitmask, mapChunkPacket.additionalBitmask, true, mapChunkPacket.biomes); } else if (packet instanceof Packet52MultiBlockChange) { Packet52MultiBlockChange multiBlockChangePacket = (Packet52MultiBlockChange) packet; if (multiBlockChangePacket.metadataArray == null) return; DataInputStream datainputstream = new DataInputStream(new ByteArrayInputStream(multiBlockChangePacket.metadataArray)); try { for (int i = 0; i < multiBlockChangePacket.size; i++) { short word0 = datainputstream.readShort(); short word1 = datainputstream.readShort(); int id = (word1 & 0xfff) >> 4; int metadata = word1 & 0xf; int x = word0 >> 12 & 0xf; int z = word0 >> 8 & 0xf; int y = word0 & 0xff; setBlockIdAt( id, (multiBlockChangePacket.xPosition * 16) + x, y, (multiBlockChangePacket.zPosition * 16) + z); setBlockMetadataAt( metadata, (multiBlockChangePacket.xPosition * 16) + x, y, (multiBlockChangePacket.zPosition * 16) + z); } } catch (IOException exception) { exception.printStackTrace(); } } else if (packet instanceof Packet53BlockChange) { Packet53BlockChange blockChangePacket = (Packet53BlockChange) packet; setBlockIdAt( blockChangePacket.type, blockChangePacket.xPosition, blockChangePacket.yPosition, blockChangePacket.zPosition); setBlockMetadataAt( blockChangePacket.metadata, blockChangePacket.xPosition, blockChangePacket.yPosition, blockChangePacket.zPosition); } else if (packet instanceof Packet56MapChunks) { if (bot.isMovementDisabled()) return; Packet56MapChunks chunkPacket = (Packet56MapChunks) packet; for (int i = 0; i < chunkPacket.primaryBitmap.length; i++) processChunk( chunkPacket.chunkX[i], chunkPacket.chunkZ[i], chunkPacket.chunkData[i], chunkPacket.primaryBitmap[i], chunkPacket.secondaryBitmap[i], chunkPacket.skylight, true); } }
@Override public void render(float delta) { // update and draw stuff Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); batch.setProjectionMatrix(camera.combined); shapes.setProjectionMatrix(camera.combined); shapes.begin(ShapeType.Line); shapes.setColor(Color.RED); for (int x = 0; x < Gdx.graphics.getWidth(); x += Constants.TILE_SIZE) { shapes.line(x, 0, x, Gdx.graphics.getHeight()); } for (int y = 0; y < Gdx.graphics.getHeight(); y += Constants.TILE_SIZE) { shapes.line(0, y, Gdx.graphics.getWidth(), y); } shapes.end(); shapes.begin(ShapeType.Filled); shapes.setColor(Color.CYAN); for (Entity entity : allEntities) { if (entity != null) { for (BoundingShape b : entity.getBoundingShapes()) { Rectangle2D bounds = b.getShape().getBounds2D(); shapes.rect( (float) bounds.getX() + entity.getX(), (float) bounds.getY() + entity.getY(), (float) bounds.getWidth(), (float) bounds.getHeight()); } } } shapes.setColor(Color.GREEN); for (int x = 0; x < staticGrid.length; x++) { for (int y = 0; y < staticGrid[0].length; y++) { if (staticGrid[x][y] == 1) shapes.rect( x * Constants.TILE_SIZE, y * Constants.TILE_SIZE, Constants.TILE_SIZE, Constants.TILE_SIZE); } } shapes.end(); batch.begin(); for (Entity entity : allEntities) { if (entity != null) { if (entity.getSprite() != null) { batch.draw(entity.getSprite(), entity.getX(), entity.getY()); } } } // batch.draw(player.getSprite(), player.getSprite().getX(), // player.getSprite().getY(),player.getSprite().getOriginX(), // player.getSprite().getOriginY(), // // player.getSprite().getWidth(),player.getSprite().getHeight(),player.getSprite().getScaleX(),player. // getSprite().getScaleY(),player.getSprite().getRotation()); batch.end(); batch.begin(); font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 50, 50); font.draw(batch, "Mouse X: " + Gdx.input.getX(), 50, 80); font.draw(batch, "Mouse Y: " + Gdx.input.getY(), 50, 110); batch.end(); // debugRenderer.render(world, debugMatrix); for (Entity entity : allEntities) { if (entity != null) { entity.update(delta); // update all entities before handling collisions } } updateQuad(); ArrayList<BoundingShape> returnObjects = new ArrayList<BoundingShape>(); for (Entity entity : allEntities) { if (entity != null) { ArrayList<BoundingShape> bs = entity.getBoundingShapes(); for (int j = 0; j < bs.size(); j++) { returnObjects.clear(); BoundingShape currentBounding = bs.get(j); quad.retrieve(returnObjects, currentBounding); for (int x = 0; x < returnObjects.size(); x++) { // Run collision detection algorithm between objects BoundingShape other = returnObjects.get(x); // System.out.println(other.getUserData()); if (currentBounding.intersects(other)) { if (currentBounding.getOwner() != other.getOwner()) { currentBounding .getOwner() .collide( new Collision( currentBounding.getOwner(), other.getOwner(), currentBounding, other)); // System.out.println("Collision: " + currentBounding.getUserData() + " + " + // other.getUserData()); } } } } entity.postCollisionUpdate(); } } }
/** * Update Camera variables in the step. * * @param gc Slick GameContainer. * @param delta Time passed since last update. * @throws SlickException */ public void update(GameContainer gc, int delta) throws SlickException { vPlayerX = player.getX(); vPlayerY = player.getY(); if (vPlayerX < (screenWidth / 2)) { camX = 0; screenRight = screenWidth; } else if (vPlayerX > mapWidth - (screenWidth / 2)) { camX = screenWidth - mapWidth; screenRight = mapWidth; } else { camX = (int) ((screenWidth / 2) - vPlayerX); screenRight = vPlayerX + (screenWidth / 2); } // Same as above but for 'Y' axis if (vPlayerY < (screenHeight / 2)) { camY = 0; screenDown = screenHeight; } else if (vPlayerY > mapHeight - (screenHeight / 2)) { camY = screenHeight - mapHeight; screenDown = mapHeight; } else { camY = (int) ((screenHeight / 2) - vPlayerY); screenDown = vPlayerY + (screenHeight / 2); } player.setVisualLocation(vPlayerX, vPlayerY); player.update(delta); if (!((GameplayState) MainGame.getInstance().getState(GameplayState.ID)).isPaused()) for (Entity e : entity) e.update(delta); vX = (int) player.getVisualX(); vY = (int) player.getVisualY(); vAcross = vX / tileWidth; vDown = vY / tileHeight; curPlayerX = (int) (vPlayerX / tileWidth); curPlayerY = (int) (vPlayerY / tileHeight); movedIntoOpen = false; try { if (this.foregroundTiles[lastPlayerX][lastPlayerY] == 1 && this.foregroundTiles[curPlayerX][curPlayerY] == 0) { movedIntoOpen = true; } } catch (Exception e) { // This error occurs when the player character walks off screen, // out of the bounds of the tiled map. } changedPosition = false; if (this.curPlayerX != this.lastPlayerX) { lastPlayerX = curPlayerX; changedPosition = true; } if (this.curPlayerY != this.lastPlayerY) { lastPlayerY = curPlayerY; changedPosition = true; } if (changedPosition) { updateForeground = true; } }