List of usage examples for com.badlogic.gdx.maps.objects RectangleMapObject getRectangle
public Rectangle getRectangle()
From source file:com.anythingmachine.tiledMaps.TiledMapHelper.java
License:Apache License
/** * Reads a file describing the collision boundaries that should be set * per-tile and adds static bodies to the boxd world. * /*from w ww . jav a 2 s .c om*/ * @param collisionsFile * @param world * @param pixelsPerMeter * the pixels per meter scale used for this world */ public void loadCollisions(String collisionsFile, World world, float pixelsPerMeter, int level) { /** * Detect the tiles and dynamically create a representation of the map * layout, for collision detection. Each tile has its own collision * rules stored in an associated file. * * The file contains lines in this format (one line per type of tile): * tileNumber XxY,XxY XxY,XxY * * Ex: * * 3 0x0,31x0 ... 4 0x0,29x0 29x0,29x31 * * For a 32x32 tileset, the above describes one line segment for tile #3 * and two for tile #4. Tile #3 has a line segment across the top. Tile * #1 has a line segment across most of the top and a line segment from * the top to the bottom, 30 pixels in. */ // FileHandle fh = Gdx.files.internal(collisionsFile); // String collisionFile = fh.readString(); // String lines[] = collisionFile.split("\\r?\\n"); // HashMap<Integer, ArrayList<LineSegment>> tileCollisionJoints = new // HashMap<Integer, ArrayList<LineSegment>>(); // /** // * Some locations on the map (perhaps most locations) are "undefined", // * empty space, and will have the tile type 0. This code adds an empty // * list of line segments for this "default" tile. // */ // tileCollisionJoints.put(Integer.valueOf(0), new // ArrayList<LineSegment>()); // for (int n = 0; n < lines.length; n++) { // String cols[] = lines[n].split(" "); // int tileNo = Integer.parseInt(cols[0]); // // ArrayList<LineSegment> tmp = new ArrayList<LineSegment>(); // // for (int m = 1; m < cols.length; m++) { // String coords[] = cols[m].split(","); // // String start[] = coords[0].split("x"); // String end[] = coords[1].split("x"); // // tmp.add(new LineSegment(Integer.parseInt(start[0]), // Integer.parseInt(start[1]), // Integer.parseInt(end[0]), Integer.parseInt(end[1]), "")); // } // // tileCollisionJoints.put(Integer.valueOf(tileNo), tmp); // } ArrayList<LineSegment> collisionLineSegments = new ArrayList<LineSegment>(); for (int l = 0; l < getMap().getLayers().getCount(); l++) { MapLayer nextLayer = getMap().getLayers().get(l); if (!nextLayer.getName().equals("AINODEMAP") && !nextLayer.getName().equals("DOORS")) { TiledMapTileLayer layer = (TiledMapTileLayer) nextLayer; if (layer.getProperties().containsKey("collide")) { for (int y = 0; y < layer.getHeight(); y++) { for (int x = 0; x < layer.getWidth(); x++) { Cell tile = layer.getCell(x, y); if (tile != null) { int tileID = tile.getTile().getId(); int start = 0; String type = ""; if (tile.getTile().getProperties().containsKey("type")) { type = (String) getMap().getTileSets().getTile(tileID).getProperties() .get("type"); } if (layer.getProperties().containsKey("WALLS")) { type = "WALLS"; addOrExtendCollisionLineSegment(x * 32 + 16, y * 32, x * 32 + 16, y * 32 + 32, collisionLineSegments, type); } else if (layer.getProperties().containsKey("STAIRS")) { if (!type.equals("LEFTSTAIRS")) { type = "STAIRS"; addOrExtendCollisionLineSegment(x * 32, y * 32, x * 32 + 32, y * 32 + 32, collisionLineSegments, type); } else { addOrExtendCollisionLineSegment(x * 32, y * 32 + 32, x * 32 + 32, y * 32, collisionLineSegments, type); } } else if (layer.getProperties().containsKey("PLATFORMS")) { type = "PLATFORMS"; addOrExtendCollisionLineSegment(x * 32, y * 32 + 32, x * 32 + 32, y * 32 + 32, collisionLineSegments, type); } } } } } } else { MapObjects objects = nextLayer.getObjects(); for (MapObject o : objects) { RectangleMapObject rect = (RectangleMapObject) o; if (rect.getProperties().containsKey("set") || rect.getProperties().containsKey("to_level")) { Rectangle shape = rect.getRectangle(); BodyDef nodeBodyDef = new BodyDef(); nodeBodyDef.type = BodyDef.BodyType.StaticBody; nodeBodyDef.position.set((shape.x + shape.width * 0.5f) * Util.PIXEL_TO_BOX, (shape.y + shape.height * 0.5f) * Util.PIXEL_TO_BOX); Body nodeBody = GamePlayManager.world.createBody(nodeBodyDef); if (!nextLayer.getName().equals("DOORS")) { String set = (String) rect.getProperties().get("set"); nodeBody.setUserData(new AINode(Integer.parseInt(set))); } else { if (rect.getProperties().containsKey("to_level") && rect.getProperties().containsKey("exitX") && rect.getProperties().containsKey("exitY")) { String to_level = (String) rect.getProperties().get("to_level"); String xPos = (String) rect.getProperties().get("exitX"); String yPos = (String) rect.getProperties().get("exitY"); nodeBody.setUserData(new Door(to_level, xPos, yPos)); } else { nodeBody.setUserData(new Door("9999", "1024", "256")); } } PolygonShape nodeShape = new PolygonShape(); nodeShape.setAsBox(shape.width * 0.5f * Util.PIXEL_TO_BOX, shape.height * 0.5f * Util.PIXEL_TO_BOX); FixtureDef fixture = new FixtureDef(); fixture.shape = nodeShape; fixture.isSensor = true; fixture.density = 0; fixture.filter.categoryBits = Util.CATEGORY_PLATFORMS; fixture.filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER; nodeBody.createFixture(fixture); nodeShape.dispose(); } } } } int platnum = 0; for (LineSegment lineSegment : collisionLineSegments) { BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyDef.BodyType.StaticBody; groundBodyDef.position.set(0, 0); Body groundBody = GamePlayManager.world.createBody(groundBodyDef); if (lineSegment.type.equals("STAIRS") || lineSegment.type.equals("LEFTSTAIRS")) { groundBody.setUserData( new Stairs("stairs_" + level + "_" + platnum, lineSegment.start(), lineSegment.end())); } else if (lineSegment.type.equals("WALLS")) { groundBody.setUserData(new Entity().setType(EntityType.WALL)); } else { Platform plat = new Platform("plat_" + level + "_" + platnum, lineSegment.start(), lineSegment.end()); groundBody.setUserData(plat); if (GamePlayManager.lowestPlatInLevel == null || lineSegment.start().y < GamePlayManager.lowestPlatInLevel.getDownPosY()) { GamePlayManager.lowestPlatInLevel = plat; } } EdgeShape environmentShape = new EdgeShape(); environmentShape.set(lineSegment.start().scl(1 / pixelsPerMeter), lineSegment.end().scl(1 / pixelsPerMeter)); FixtureDef fixture = new FixtureDef(); fixture.shape = environmentShape; fixture.isSensor = true; fixture.density = 1f; fixture.filter.categoryBits = Util.CATEGORY_PLATFORMS; fixture.filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER | Util.CATEGORY_PARTICLES; groundBody.createFixture(fixture); environmentShape.dispose(); } /** * Drawing a boundary around the entire map. We can't use a box because * then the world objects would be inside and the physics engine would * try to push them out. */ TiledMapTileLayer layer = (TiledMapTileLayer) getMap().getLayers().get(3); BodyDef bodydef = new BodyDef(); bodydef.type = BodyType.StaticBody; bodydef.position.set(0, 0); Body body = GamePlayManager.world.createBody(bodydef); // left wall EdgeShape mapBounds = new EdgeShape(); if (level == 1) { mapBounds.set(new Vector2(0.0f, 0.0f), new Vector2(0, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX)); body.setUserData(new Entity().setType(EntityType.WALL)); Fixture fixture = body.createFixture(mapBounds, 0); Filter filter = new Filter(); filter.categoryBits = Util.CATEGORY_PLATFORMS; filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER; fixture.setFilterData(filter); } else { mapBounds.set(new Vector2(0f * Util.PIXEL_TO_BOX, 0.0f), new Vector2(0f, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX)); body.setUserData(new LevelWall(level - 1)); Fixture fixture = body.createFixture(mapBounds, 0); Filter filter = new Filter(); filter.categoryBits = Util.CATEGORY_PLATFORMS; filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER; fixture.setFilterData(filter); } // right wall body = GamePlayManager.world.createBody(bodydef); body.setUserData(new LevelWall(level + 1)); EdgeShape mapBounds2 = new EdgeShape(); mapBounds2.set(new Vector2((layer.getWidth() * 32), 0.0f).scl(Util.PIXEL_TO_BOX), new Vector2((layer.getWidth() * 32), layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX)); Fixture fixture = body.createFixture(mapBounds2, 0); Filter filter = new Filter(); filter.categoryBits = Util.CATEGORY_PLATFORMS; filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER; fixture.setFilterData(filter); // roof body = GamePlayManager.world.createBody(bodydef); body.setUserData(new Platform("roof_" + level, new Vector2(0.0f, layer.getHeight() * 32), new Vector2(layer.getWidth() * 32, layer.getHeight()))); EdgeShape mapBounds3 = new EdgeShape(); mapBounds3.set(new Vector2(0.0f, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX), new Vector2(layer.getWidth() * 32, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX)); fixture = body.createFixture(mapBounds3, 0); fixture.setFilterData(filter); mapBounds.dispose(); mapBounds2.dispose(); mapBounds3.dispose(); }
From source file:com.mygdx.game.Play.java
public boolean checkCollision(Gameplayer player) { boolean value = false; // Checking for wall collisions. Point p1 = new Point(player.Coordx + 3, player.Coordy + 3); Point p2 = new Point(player.Coordx + 3, player.Coordy + 3); Rectangle spriteRectangle = new Rectangle(p1.x, p1.y, 30, 30); Rectangle spriteEnemyRectangle = new Rectangle(p2.x, p2.y, 1, 1); for (RectangleMapObject rectangleObject : map.getLayers().get("Collision").getObjects() .getByType(RectangleMapObject.class)) { Rectangle rectangle = rectangleObject.getRectangle(); if (Intersector.overlaps(rectangle, spriteRectangle)) { value = true;//from w w w.j a va 2 s .co m } } return value; }
From source file:com.nuliy.example.GameScreen.java
@Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1);/*ww w.j a va2 s . c o m*/ Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //aim the player at where the screen has been touched if (Gdx.input.isTouched()) { p.mouseAngle(touched.x, touched.y); touched.x = Gdx.input.getX(); touched.y = Gdx.input.getY(); if (isHeldDown == false) { isClicked = true; } camPlayer.unproject(touched); isHeldDown = true; } else { isHeldDown = false; } //player running if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT)) { playerSpeed = 300; } else { playerSpeed = 160; } if (p.isDead()) { p = null; } //player weapon switching if (Gdx.input.isKeyPressed(Input.Keys.Q)) { if (isQHeld == false) { isQDown = true; System.out.println(isQDown); } isQHeld = true; } else { isQHeld = false; } if (isQDown == true) { p.rotateWeps(); isQDown = false; } //player movements if (Gdx.input.isKeyPressed(Input.Keys.D)) { p.setDX(playerSpeed); } else if (Gdx.input.isKeyPressed(Input.Keys.A)) { p.setDX(-playerSpeed); } else { p.setDX(0); } if (Gdx.input.isKeyPressed(Input.Keys.W)) { p.setDY(playerSpeed); } else if (Gdx.input.isKeyPressed(Input.Keys.S)) { p.setDY(-playerSpeed); } else { p.setDY(0); } //make the Ai scared and run away from the player //player punching if (p.getGunID() == 0 && Gdx.input.isKeyPressed(Input.Keys.SPACE)) { p.angleRound(); p.punch(); } else { p.stopPunch(); } for (Pedestrian AI1 : Peds) { if (AI1 != null && p.getGunID() == 0 && (Gdx.input.isKeyPressed(Input.Keys.SPACE) || (p.getGunID() == 1 && isClicked == true))) { AIscaredtimer = 200; } } if (AIscaredtimer > 0) { AIisscared = true; AIscaredtimer--; } else { AIisscared = false; } //move all the AI for (Pedestrian AI1 : Peds) { if (AI1 != null && AIisscared == false) { AI1.move(75); } else if (AI1 != null && AIisscared == true && AI1.distanceFrom(p) < 200) { AI1.scared(p, 75 * 2); } } //move all police for (Police cop : police) { if (p.getWantedLvl() >= 100 && cop.distanceFrom(p) > 200) { cop.setLastRot(p); cop.chase(p); } else if (p.getWantedLvl() >= 100 && cop.distanceFrom(p) < 200) { System.out.println("shot"); cop.stop(); cop.setLastRot(p); cop.shootPlayer(p); p.isDead(); } else { cop.move(AIspeed); } } //player decrease wanted level if less than three stars wanted p.wantedLvlDecrease(); //player regen health p.regenHealth(); //player shoot M4 //pedestrians and police getting shot if (isClicked == true && p.getGunID() == 1) { p.shootM4(); for (Pedestrian Ped : Peds) { AIscaredtimer = 200; if (Ped != null && Ped.getBounds().contains(touched.x, touched.y)) { Ped.shot(); Ped.isDead(); System.out.println("shot"); } } for (Police cop : police) { AIscaredtimer = 200; if (cop != null && cop.getBounds().contains(touched.x, touched.y)) { cop.shot(); cop.isDead(); System.out.println("shot"); } } isClicked = false; } else { p.stopShootM4(); } //map collisions objects = map.getLayers().get("Object Layer 1").getObjects(); for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) { Rectangle rectangle = rectangleObject.getRectangle(); if (Intersector.overlaps(rectangle, p.getBounds())) { p.handleCollision(rectangle); } for (Pedestrian AI1 : Peds) { if (AI1 != null && Intersector.overlaps(rectangle, AI1.getBounds())) { AI1.handleCollision(rectangle); } } for (Police cop : police) { if (cop != null && Intersector.overlaps(rectangle, cop.getBounds())) { cop.handleCollision(rectangle); } } } //pedestrians getting punched for (Pedestrian Ped : Peds) { if (Ped != null && p.getBounds().overlaps(Ped.getBounds())) { p.handleCollision(Ped.getBounds()); if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) { Ped.punched(); } } } //cops getting punched for (Police cop : police) { if (cop != null && p.getBounds().overlaps(cop.getBounds())) { p.handleCollision(cop.getBounds()); if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) { cop.punched(); } } } //pedestrains get killed once in the water for (int i = 0; i < Peds.length; i++) { if (Peds[i] != null && ((Peds[i].getX() > (mapPixelWidth - 200)) || (Peds[i].getX() < 230) || (Peds[i].getY() > (mapPixelHeight - 200)) || Peds[i].getY() < 200)) { Peds[i] = null; } } //police get killed once in the water for (int i = 0; i < police.length; i++) { if (police[i] != null && ((police[i].getX() > (mapPixelWidth - 200)) || (police[i].getX() < 230) || (police[i].getY() > (mapPixelHeight - 200)) || police[i].getY() < 200)) { police[i] = null; } } //collision between pedestrians for (int h = 0; h < Peds.length; h++) { for (int i = 0; i < Peds.length; i++) { if (i != h && Peds[h] != null && Peds[i] != null && Peds[h].getBounds().overlaps(Peds[i].getBounds())) { Peds[h].handleCollision(Peds[i].getBounds()); } } } //collision between police for (int h = 0; h < police.length; h++) { for (int i = 0; i < police.length; i++) { if (i != h && police[h] != null && police[i] != null && police[h].getBounds().overlaps(police[i].getBounds())) { police[h].handleCollision(police[i].getBounds()); } } } //pedestrians dying for (int i = 0; i < Peds.length; i++) { if (Peds[i] != null) { if (Peds[i].isDead() == true) { numDeadPeds = (numDeadPeds + 1) % (ogNumDeadPeds); deadPeds[numDeadPeds] = new DeadPed(Peds[i].getX(), Peds[i].getY(), Peds[i].getLastRot(), Peds[i].getColor()); p.wantedKilledPed(); playerScore.addScoreKilledPed(p); Peds[i] = null; } } } //camera positioning if (p.getX() - Gdx.graphics.getWidth() / 2 - tilePixelWidth * 2 - 16 > 0 && p.getX() + Gdx.graphics.getWidth() / 2 < mapPixelWidth) { camx = (int) p.getX(); } else if (p.getX() - Gdx.graphics.getWidth() / 2 - tilePixelWidth * 2 - 16 <= 0) { camx = Gdx.graphics.getWidth() / 2 + tilePixelWidth * 2 + 16; } else if (p.getX() + Gdx.graphics.getWidth() / 2 >= mapPixelWidth) { camx = mapPixelWidth - Gdx.graphics.getWidth() / 2; } if (p.getY() - Gdx.graphics.getHeight() / 2 - tilePixelHeight * 2 > 0 && p.getY() + Gdx.graphics.getHeight() / 2 < mapPixelHeight) { camy = (int) p.getY(); } else if (p.getY() - Gdx.graphics.getHeight() / 2 - tilePixelHeight * 2 <= 0) { camy = Gdx.graphics.getHeight() / 2 + tilePixelWidth * 2; } else if (p.getY() + Gdx.graphics.getHeight() / 2 >= mapPixelHeight) { camy = mapPixelHeight - Gdx.graphics.getHeight() / 2; } camPlayer.position.set(camx, camy, 0); camPlayer.update(); camMiniMap.update(); mapRender.setView(camPlayer); mapRender.render(); batch.setProjectionMatrix(camPlayer.combined); batch.begin(); //draw dead people for (DeadPed dPed : deadPeds) { if (dPed != null) { dPed.drawDead(batch, delta); } } //update positions of characters for (Pedestrian Ped : Peds) { if (Ped != null) { Ped.update(delta); } } for (Police cop : police) { if (cop != null) { cop.update(delta); } } //Update position of player p.update(delta); //draw characters for (Pedestrian AI1 : Peds) { if (AI1 != null) { AI1.draw(batch, AI1.getColor()); } } for (Police cop : police) { if (cop != null) { cop.draw(batch, p, delta); } } //respawn a new pedestrian if they are dead for (int i = 0; i < Peds.length; i++) { if (Peds[i] == null) { Peds[i] = new Pedestrian((float) Math.random() * 4000 + 1000, (float) Math.random() * 4000 + 1000, (int) (Math.random() * 6 + 1)); } } //respawn a new cop if they are dead for (int i = 0; i < police.length; i++) { if (police[i] == null) { police[i] = new Police((float) Math.random() * 4000 + 1000, (float) Math.random() * 4000 + 1000); } } //draw player p.draw(batch, delta); batch.end(); //HUD Rendering batchMiniMap.setProjectionMatrix(camMiniMap.combined); miniMapRender.setView(camMiniMap); miniMapRender.render(); batchMiniMap.begin(); batchMiniMap.draw(playermarker, p.getX() - (playermarker.getWidth() / 2), p.getY() - (playermarker.getHeight() / 2)); for (Pedestrian AI : Peds) { if (AI != null) { AI.draw(batchMiniMap, 1); } } batchMiniMap.end(); batch.setProjectionMatrix(UI.combined); batch.begin(); font.draw(batch, "Health: " + (int) p.getHealth() / 2, 685, 520); font.draw(batch, "Score: " + playerScore.returnScore(), 685, 500); font.draw(batch, "Multiplier: x" + (int) ((Math.ceil(p.getWantedLvl() / 100)) + 1), 685, 480); if (p.getWantedLvl() >= 100) { font.draw(batch, "Wanted: " + (int) (Math.ceil((int) p.getWantedLvl() / 100)), 685, 460); } if (p.getGunID() == 0) { batch.draw(HUDfist, 712, 533, 50, 50); } else if (p.getGunID() == 1) { batch.draw(HUDm4, 687, 530, 100, 50); } batch.end(); }
From source file:com.prisonbreak.game.entities.Character.java
private boolean haveCollision(float newX, float newY) { // if out of world map -> no need to check -> stop checking if (newX < 0 || newX + width > MapControlRenderer.WORLD_WIDTH || newY < 0 || newY + height > MapControlRenderer.WORLD_HEIGHT) { return true; }//from w w w . j a v a 2s.co m // get bounding rectangle of current Character Rectangle characterBounding = new Rectangle(newX, newY, width, height); /* With Guard (when as Player) */ // if current character == Player float offset = 4f; if (this instanceof Player) { Rectangle rectPlayer = new Rectangle(characterBounding.getX() + offset, characterBounding.getY() + offset, characterBounding.getWidth() - 2 * offset, characterBounding.getHeight() - 2 * offset); // check with Guards for (Guard guard : renderer.getListGuards()) { Rectangle rectGuard = new Rectangle(guard.getSprite().getBoundingRectangle().getX() + offset, guard.getSprite().getBoundingRectangle().getY() + offset, guard.getSprite().getBoundingRectangle().getWidth() - 2 * offset, guard.getSprite().getBoundingRectangle().getHeight() - 2 * offset); if (rectPlayer.overlaps(rectGuard)) return true; } } /* End */ /* With static (blocked) objects */ // consider each objects for (MapObject object : renderer.getStaticObjects()) { // cast to rectangle object if (object.isVisible() && object.getProperties().get("blocked", Boolean.class) != null && object.getProperties().get("blocked", Boolean.class) && object instanceof RectangleMapObject) { RectangleMapObject rectObject = (RectangleMapObject) object; // check for overlapping ~ collision if (rectObject.getRectangle().overlaps(characterBounding)) return true; } } /* End */ /* With locked doors */ // for each object for (MapObject object : renderer.getDoorObjects()) { if (object.isVisible() && (object.getProperties().get("locked", null, Boolean.class) != null) && object.getProperties().get("locked", Boolean.class) && object instanceof RectangleMapObject) { RectangleMapObject rectObject = (RectangleMapObject) object; if (rectObject.getRectangle().overlaps(characterBounding)) return true; } } /* End */ /* With walls */ // position of two points that bound the Player's image int lowerBoundX, lowerBoundY, upperBoundX, upperBoundY, temp; float alpha = (float) 0.25; temp = (int) (newX / 32f); // account for less than 12.5% of the if ((newX / 32f - temp) > (1 - alpha)) { // left tile -> do not consider lowerBoundX = temp + 1; } else { // otherwise; consider when checking lowerBoundX = temp; // for collision } temp = (int) (newY / 32f); // account for less than 12.5% of the if ((newY / 32f - temp) > (1 - alpha)) { // below tile -> do not consider lowerBoundY = temp + 1; } else { lowerBoundY = temp; } temp = (int) ((newX + width) / 32f); // account for less than 12.5% of the if (((newX + width) / 32f - temp) < alpha) { // right tile -> do not consider upperBoundX = temp - 1; } else { upperBoundX = temp; } temp = (int) ((newY + height) / 32f); // account for less than 12.5% of the if (((newY + height) / 32f - temp) < alpha) { // above tile -> do not consider upperBoundY = temp - 1; } else { upperBoundY = temp; } // check all the tiles (32x32 pixels) the Player's image accounts for int[][] grid = renderer.getBlockedWallsGrid(); for (int i = (int) lowerBoundX; i <= (int) upperBoundX; ++i) { for (int j = (int) lowerBoundY; j <= (int) upperBoundY; ++j) { if (grid[i][j] == 1) return true; } } /* End */ return false; }
From source file:com.prisonbreak.game.MapControlRenderer.java
private void initializeGuards() { String type, sheetName, direction; guards = new Array<Guard>(); // extract all guard objects in map MapObjects guardObjects = map.getLayers().get("Guards").getObjects(); // for each object for (MapObject guard : guardObjects) { RectangleMapObject rectGuard = (RectangleMapObject) guard; // if current guard is "not visible" -> ignore if (!rectGuard.isVisible()) { continue; }/*from www. j a v a 2 s . co m*/ // extract values of attributes of 'guard' object type = rectGuard.getProperties().get("type", "none", String.class); sheetName = rectGuard.getProperties().get("sheetName", "", String.class); if (type.equalsIgnoreCase("none")) { Gdx.app.log("Error: ", "'type' attribute not found"); return; } // if stationary guard if (type.equalsIgnoreCase("stationary")) { direction = rectGuard.getProperties().get("direction", "none", String.class); if (direction.equalsIgnoreCase("none")) { Gdx.app.log("Error: ", "invalid value for direction attribute"); return; } // create the specified guard Guard specifiedGuard = new StationGuard(sheetName, direction, rectGuard.getRectangle().getX(), rectGuard.getRectangle().getY()); specifiedGuard.setMapControlRenderer(this); // add the corresponding guard to the array guards.add(specifiedGuard); } // if patrol guard else if (type.equalsIgnoreCase("patrol")) { float secondDelay = rectGuard.getProperties().get("delay", Float.class); // create the specified guard (without setting mark points) Guard specifiedGuard = new PatrolGuard(sheetName, rectGuard.getRectangle().getX(), rectGuard.getRectangle().getY(), secondDelay); specifiedGuard.setMapControlRenderer(this); // extract list of mark points from the map String listPoints = rectGuard.getProperties().get("markPoints", String.class); String[] tileIndices = listPoints.split(","); for (int i = 0, indexX, indexY; i < tileIndices.length; i += 2) { indexX = Integer.parseInt(tileIndices[i]); indexY = Integer.parseInt(tileIndices[i + 1]); // Gdx.app.log("x: ", "" + indexX); // Gdx.app.log("y: ", "" + indexY); if (!((PatrolGuard) specifiedGuard).addMarkPoint(new Vector2(indexX * 32f, indexY * 32f))) { Gdx.app.log("Cannot add mark point ", "(indeX, indexY)"); } } // Gdx.app.log("Mark point 1: ", ((PatrolGuard) specifiedGuard).listMarkPoints.get(0).toString()); // Gdx.app.log("Mark point 2: ", ((PatrolGuard) specifiedGuard).listMarkPoints.get(1).toString()); // add the corresponding guard to the array guards.add(specifiedGuard); } } }
From source file:com.prisonbreak.game.MapControlRenderer.java
private Array<Item> triggerInteraction() { for (MapObject object : interactionObjects) { // all interaction objects are guaranteed to be rectangle RectangleMapObject rectObject = (RectangleMapObject) object; // Gdx.app.log("object: ", rectObject.getRectangle().toString()); // Gdx.app.log("player: ", player.getSprite().getBoundingRectangle().toString()); // search and find for the object in interaction with Player if (rectObject.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) { String directionCheck = rectObject.getProperties().get("contactDirection", "none", String.class); // Gdx.app.log("Contact direction: ", directionCheck); // Gdx.app.log("Player direction: ", player.getCurrentDirection()); // check if user faces object in correct direction if (directionCheck.equalsIgnoreCase("all") || (!player.getCurrentDirection().equalsIgnoreCase("none") && player.getCurrentDirection().equalsIgnoreCase(directionCheck))) { // retrieve type of interaction String type = rectObject.getProperties().get("type", "", String.class); // if searchable objects if (type.equalsIgnoreCase("search_interaction")) { interactHappen = true; // set the flag for type of interaction typeInteraction = TYPE_INTERACTION.SEARCH_INTERACTION; // extract attributes' values boolean haveItems = rectObject.getProperties().get("haveItems", false, Boolean.class); int listID = rectObject.getProperties().get("listItemID", -1, Integer.class); // if object does contain items // -> return list of those items // otherwise -> return null if (haveItems) { // get the item objectItems ID if (listID == -1) break; else return listItems.get(listID); }/*from ww w . j a v a 2 s . co m*/ } // if door object (open_lock_interaction) else if (type.equalsIgnoreCase("open_lock_interaction")) { // extract attributes' values boolean locked = rectObject.getProperties().get("locked", false, Boolean.class); int keyID = rectObject.getProperties().get("keyID", -1, Integer.class); Array<Item> needKey = new Array<Item>(); Item key = new Item("Needed key", keyID); needKey.add(key); // extract the name of current door in interaction with Player latestObjectName = rectObject.getName(); // set the status of current door in interaction with Player latestDoorLocked = locked; // Gdx.app.log("locked: ", latestDoorLocked + ""); // if the door is not locked // check the position of Player before invoking interaction // -> return the required key to lock it if (!latestDoorLocked) { MapObject o = doorObjects.get(latestObjectName); RectangleMapObject r = (RectangleMapObject) o; if (!r.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) { interactHappen = true; // set the flag for type of interaction typeInteraction = TYPE_INTERACTION.OPEN_LOCK_INTERACTION; return needKey; } } // if the door is locked // -> return the required key to unlock it, or // the key with keyID = -1 ; indicate // that the door CANNOT be opened else { interactHappen = true; // set the flag for type of interaction typeInteraction = TYPE_INTERACTION.OPEN_LOCK_INTERACTION; return needKey; } } // if readable objects else if (type.equalsIgnoreCase("read_interaction")) { interactHappen = true; // set the flag for type of interaction typeInteraction = TYPE_INTERACTION.READ_INTERACTION; // extract attributes' values String message = rectObject.getProperties().get("message", "", String.class); // set the name of the object latestObjectName = rectObject.getProperties().get("name", "Object", String.class); // return a list with one "item" contain the message; id for item = -2 Array<Item> l = new Array<Item>(); Item mess = new Item("Written Message", -2); mess.setDescription(message); l.add(mess); return l; } // if password locking objects else if (type.equalsIgnoreCase("pass_unlock_interaction")) { boolean locked = rectObject.getProperties().get("locked", false, Boolean.class); // if the object has already been unlocked // -> return null; no interaction happens if (!locked) { return null; } // otherwise // -> return a list with first "item" containing the password, // and all the remaining items are ones that are inside // the object (in case of safe locker) else { interactHappen = true; // set the flag indicating the type of interaction typeInteraction = TYPE_INTERACTION.PASS_UNLOCK_INTERACTION; // extract the name of object in interaction latestObjectName = rectObject.getName(); // extract attributes String password = rectObject.getProperties().get("pass", "", String.class); Item passItem = new Item("Password", -3); // item contains password passItem.setDescription(password); // create the list Array<Item> list = new Array<Item>(); list.add(passItem); // if safe locker, add all the contained items into the list int listID = rectObject.getProperties().get("listItemID", -1, Integer.class); if (listID == -1) { Gdx.app.log("Error: ", "listItemID attribute not found"); } else { list.addAll(listItems.get(listID)); } return list; } } // if breakable object (here, break the office door) else if (type.equalsIgnoreCase("break_interaction")) { boolean broken = rectObject.getProperties().get("broken", true, Boolean.class); // if object has been cracked open (broken = true) // -> do nothing, no interaction happens, return null if (broken) { return null; } // otherwise // -> return the required item to break the object (door), which is a crowbar in this game else { interactHappen = true; typeInteraction = TYPE_INTERACTION.BREAK_INTERACTION; // extract the name of object in interaction latestObjectName = rectObject.getName(); int id = rectObject.getProperties().get("breakItemID", Integer.class); Item item = new Item("Required Item", id); Array<Item> l = new Array<Item>(); l.add(item); return l; } } } } } return null; }
From source file:com.prisonbreak.game.MapControlRenderer.java
private void extractBlockedWalls() { // get map objects of ObjectLayer "Collision" MapLayer layer = map.getLayers().get("WallCollision"); MapObjects objects = layer.getObjects(); // fill in blockedWallUnitGrid with position of static blocked map objects // 1 -> blocked 0 -> not blocked blockedWallUnitGrid = new int[100][100]; boolean isBlocked = false; for (int indexX = 0; indexX < 100; ++indexX) { for (int indexY = 0; indexY < 100; ++indexY) { // convert to position in world map Vector2 worldPosition = new Vector2(indexX * 32f + 16f, indexY * 32f + 16f); // consider center // check whether that position is "blocked" or not for (MapObject o : objects) { // retrieve RectangleMapObject objects that are blocked if (o.isVisible() && o instanceof RectangleMapObject && o.getProperties().get("blocked") != null && o.getProperties().get("blocked", Boolean.class)) { RectangleMapObject rectObject = (RectangleMapObject) o; if (rectObject.getRectangle().contains(worldPosition)) { isBlocked = true; break; }/*ww w.jav a 2s . c om*/ } } // fill 1 / 0 into the corrsponding tile index if (isBlocked) { blockedWallUnitGrid[indexX][indexY] = 1; } else { blockedWallUnitGrid[indexX][indexY] = 0; } // reset flag isBlocked = false; } } // Gdx.app.log("Test: ", " " + blockedWallUnitGrid[13][38] + " " + blockedWallUnitGrid[13][39] + // " " + blockedWallUnitGrid[12][38] + " " + blockedWallUnitGrid[12][39]); }
From source file:com.prisonbreak.game.MapControlRenderer.java
private void setPlayerToSpawm() { MapObject spawmPoint = map.getLayers().get("SpecialLocations").getObjects().get("spawmPoint"); RectangleMapObject rectSpawmPoint = (RectangleMapObject) spawmPoint; player.x = rectSpawmPoint.getRectangle().getX(); player.y = rectSpawmPoint.getRectangle().getY(); // player.x = 50 * 32; // player.y = 79 * 32; }
From source file:com.prisonbreak.game.MapControlRenderer.java
private boolean winGame() { RectangleMapObject rectLoc = (RectangleMapObject) winningLocation; return state != STATE.END && rectLoc.getRectangle().contains(player.getSprite().getBoundingRectangle()); }
From source file:com.prisonbreak.game.MapControlRenderer.java
@Override public void render() { if (state == STATE.ONGOING) { player.update();/* w w w. j a v a2s .c om*/ moveCamera(); // check if Player is detected by the Guards for (Guard guard : guards) { if (guard instanceof PatrolGuard) { ((PatrolGuard) guard).update(); } if (guard.detectPlayer()) { // Gdx.app.log("Game over", ""); loseGame(); break; } } // search for the door in contact for (Object o : doorObjects) { RectangleMapObject r = null; if (o instanceof RectangleMapObject) { r = (RectangleMapObject) o; } if (r != null && r.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) { currentDoor = r; break; } } // the door "disappears" when Player steps in // and "showed" again when Player steps out if (currentDoor != null) { int x = currentDoor.getProperties().get("lowerLeftX", Integer.class); int y = currentDoor.getProperties().get("lowerLeftY", Integer.class); String name = currentDoor.getProperties().get("tileLayerName", String.class); TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(name); // if the door has not been hidden, and Player steps in -> hide the door if (!currentDoor.getProperties().get("locked", Boolean.class) && !doorHidden && currentDoor.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) { // extract the tiles tile1 = layer.getCell(x, y).getTile(); // lower left tile2 = layer.getCell(x + 1, y).getTile(); // lower right tile3 = layer.getCell(x, y + 1).getTile(); // upper left tile4 = layer.getCell(x + 1, y + 1).getTile(); // upper right // "hide" the door when Player steps in layer.getCell(x, y).setTile(null); layer.getCell(x + 1, y).setTile(null); layer.getCell(x, y + 1).setTile(null); layer.getCell(x + 1, y + 1).setTile(null); doorHidden = true; // set the flag } // if the door is currently hidden, and Player steps out -> show it if (!currentDoor.getProperties().get("locked", Boolean.class) && doorHidden && !currentDoor.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) { // "show" the door when Player steps out layer.getCell(x, y).setTile(tile1); layer.getCell(x + 1, y).setTile(tile2); layer.getCell(x, y + 1).setTile(tile3); layer.getCell(x + 1, y + 1).setTile(tile4); doorHidden = false; } } // update winning state if (winGame()) state = STATE.WIN; } shapeRenderer.setProjectionMatrix(camera.combined); beginRender(); int currentLayer = 0; for (MapLayer layer : map.getLayers()) { if (layer.isVisible()) { // tile layer if (layer instanceof TiledMapTileLayer) { renderTileLayer((TiledMapTileLayer) layer); ++currentLayer; // layer to draw characters and guards if (currentLayer == drawSpritesAfterLayer) { // draw player player.getSprite().draw(this.getBatch()); // draw all the guards for (Guard guard : guards) { guard.getSprite().draw(this.getBatch()); } } // layer to draw guard's detection area // note: even though detection area is RECTANGLE // , draw a POLYGON instead (POLYGON still inside the RECTANGLE) if (currentLayer == drawDetectionAreaAfterLayer) { for (Guard guard : guards) { endRender(); // first, determine the four vertices float nearLeftX, nearLeftY, nearRightX, nearRightY, // "nearer" points in Guard's POV farLeftX, farLeftY, farRightX, farRightY; // "further" points in Guard's POV if (guard.getCurrentDirection().equalsIgnoreCase("up")) { nearLeftX = guard.getDetectArea().x + guard.getDetectArea().width / 4; nearRightX = guard.getDetectArea().x + guard.getDetectArea().width * 3 / 4; nearLeftY = nearRightY = guard.getDetectArea().y; farLeftX = guard.getDetectArea().x; farRightX = guard.getDetectArea().x + guard.getDetectArea().width; farLeftY = farRightY = guard.getDetectArea().y + guard.getDetectArea().height; } else if (guard.getCurrentDirection().equalsIgnoreCase("down")) { nearLeftX = guard.getDetectArea().x + guard.getDetectArea().width * 3 / 4; nearRightX = guard.getDetectArea().x + guard.getDetectArea().width / 4; nearLeftY = nearRightY = guard.getDetectArea().y + guard.getDetectArea().height; farLeftX = guard.getDetectArea().x + guard.getDetectArea().width; farRightX = guard.getDetectArea().x; farLeftY = farRightY = guard.getDetectArea().y; } else if (guard.getCurrentDirection().equalsIgnoreCase("right")) { nearLeftY = guard.getDetectArea().y + guard.getDetectArea().height * 3 / 4; nearRightY = guard.getDetectArea().y + guard.getDetectArea().height / 4; nearLeftX = nearRightX = guard.getDetectArea().x; farLeftY = guard.getDetectArea().y + guard.getDetectArea().height; farRightY = guard.getDetectArea().y; farLeftX = farRightX = guard.getDetectArea().x + guard.getDetectArea().width; } else if (guard.getCurrentDirection().equalsIgnoreCase("left")) { nearLeftY = guard.getDetectArea().y + guard.getDetectArea().height / 4; nearRightY = guard.getDetectArea().y + guard.getDetectArea().height * 3 / 4; nearLeftX = nearRightX = guard.getDetectArea().x + guard.getDetectArea().width; farLeftY = guard.getDetectArea().y; farRightY = guard.getDetectArea().y + guard.getDetectArea().height; farLeftX = farRightX = guard.getDetectArea().x; } else { nearLeftX = nearLeftY = nearRightX = nearRightY = 0; farLeftX = farLeftY = farRightY = farRightX = 0; } // draw detection area Gdx.gl.glEnable(GL20.GL_BLEND); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); shapeRenderer.setColor(1, 0, 0, 0.5f); if (guard.getCurrentDirection().equalsIgnoreCase("up")) { // the body (rectangle) of the polygon shapeRenderer.rect(nearLeftX, nearLeftY, nearRightX - nearLeftX, farLeftY - nearLeftY); // the left side (triangle) of the polygon shapeRenderer.triangle(nearLeftX, nearLeftY, farLeftX, farLeftY, nearLeftX, farLeftY); // the right side (triangle) of the polygon shapeRenderer.triangle(nearRightX, nearRightY, farRightX, farRightY, nearRightX, farRightY); } else if (guard.getCurrentDirection().equalsIgnoreCase("down")) { // the body (rectangle) of the polygon shapeRenderer.rect(nearRightX, farRightY, nearLeftX - nearRightX, nearRightY - farRightY); // the left side (triangle) of the polygon shapeRenderer.triangle(nearLeftX, nearLeftY, farLeftX, farLeftY, nearLeftX, farLeftY); // the right side (triangle) of the polygon shapeRenderer.triangle(nearRightX, nearRightY, farRightX, farRightY, nearRightX, farRightY); } else if (guard.getCurrentDirection().equalsIgnoreCase("right")) { // the body (rectangle) of the polygon shapeRenderer.rect(nearRightX, nearRightY, farRightX - nearRightX, nearLeftY - nearRightY); // the left side (triangle) of the polygon shapeRenderer.triangle(nearLeftX, nearLeftY, farLeftX, farLeftY, farLeftX, nearLeftY); // the right side (triangle) of the polygon shapeRenderer.triangle(nearRightX, nearRightY, farRightX, farRightY, farRightX, nearRightY); } else if (guard.getCurrentDirection().equalsIgnoreCase("left")) { // the body (rectangle) of the polygon shapeRenderer.rect(farLeftX, nearLeftY, nearLeftX - farLeftX, nearRightY - nearLeftY); // the left side (triangle) of the polygon shapeRenderer.triangle(nearLeftX, nearLeftY, farLeftX, farLeftY, farLeftX, nearLeftY); // the right side (triangle) of the polygon shapeRenderer.triangle(nearRightX, nearRightY, farRightX, farRightY, farRightX, nearRightY); } shapeRenderer.end(); Gdx.gl.glDisable(GL20.GL_BLEND); beginRender(); } } } // object layer else { for (MapObject object : layer.getObjects()) { renderObject(object); } } } } endRender(); stage.act(); stage.draw(); }