List of usage examples for com.badlogic.gdx InputAdapter InputAdapter
InputAdapter
From source file:com.mbrlabs.mundus.Editor.java
License:Apache License
private void setupInput() { // NOTE: order in wich processors are added is important: first added, // first executed! inputManager.addProcessor(shortcutController); inputManager.addProcessor(ui);/*from www .ja v a 2s. c om*/ // when user does not click on a ui element -> unfocus UI inputManager.addProcessor(new InputAdapter() { @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { ui.unfocusAll(); return false; } }); inputManager.addProcessor(toolManager); inputManager.addProcessor(camController); toolManager.setDefaultTool(); }
From source file:com.mygdx.game.Invaders.java
License:Apache License
@Override public void create() { Array<Controller> controllers = Controllers.getControllers(); if (controllers.size > 0) { controller = controllers.first(); }//from w w w .ja va 2 s .c o m Controllers.addListener(controllerListener); // setScreen(new MainMenu(this)); setScreen(new GameLoop(this)); if (audio_enabled == true) { music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal)); music.setLooping(true); music.play(); } Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(int keycode) { if (keycode == Keys.ENTER && Gdx.app.getType() == ApplicationType.WebGL) { Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode()); } return true; } }); fps = new FPSLogger(); }
From source file:com.sbes.game.SBEGame.java
@Override public void create() { //These variables, corresponding to the screen's width and height in cells and a cell's width and height in //pixels, must match the size you specified in the launcher for input to behave. //This is one of the more common places a mistake can happen. //In our desktop launcher, we gave these arguments to the configuration: // config.width = 80 * 8; // config.height = 40 * 18; //Here, config.height refers to the total number of rows to be displayed on the screen. //We're displaying 32 rows of dungeon, then 8 more rows of text generation to show some tricks with language. //gridHeight is 32 because that variable will be used for generating the dungeon and handling movement within //the upper 32 rows. Anything that refers to the full height, which happens rarely and usually for things like //screen resizes, just uses gridHeight + 8. Next to it is gridWidth, which is 80 because we want 80 grid spaces //across the whole screen. cellWidth and cellHeight are 8 and 18, and match the multipliers for config.width and //config.height, but in this case don't strictly need to because we soon use a "Stretchable" font. While //gridWidth and gridHeight are measured in spaces on the grid, cellWidth and cellHeight are the pixel dimensions //of an individual cell. The font will look more crisp if the cell dimensions match the config multipliers //exactly, and the stretchable fonts (technically, distance field fonts) can resize to non-square sizes and //still retain most of that crispness. gridWidth = 80;//ww w . j a v a 2 s . com gridHeight = 32; cellWidth = 8; cellHeight = 18; // gotta have a random number generator. We can seed an RNG with any long we want, or even a String. rng = new RNG("SquidLib!"); //Some classes in SquidLib need access to a batch to render certain things, so it's a good idea to have one. batch = new SpriteBatch(); //Here we make sure our Stage, which holds any text-based grids we make, uses our Batch. stage = new Stage(new StretchViewport(gridWidth * cellWidth, (gridHeight + 8) * cellHeight), batch); // the font will try to load Inconsolata-LGC-Custom as an embedded bitmap font with a distance field effect. // this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used. display = new SquidLayers(gridWidth, gridHeight + 8, cellWidth, cellHeight, DefaultResources.getStretchableFont()); // a bit of a hack to increase the text height slightly without changing the size of the cells they're in. // this causes a tiny bit of overlap between cells, which gets rid of an annoying gap between vertical lines. // if you use '#' for walls instead of box drawing chars, you don't need this. display.getTextFactory().height(cellHeight + 1).initBySize(); // this makes animations very fast, which is good for multi-cell movement but bad for attack animations. display.setAnimationDuration(0.03f); //These need to have their positions set before adding any entities if there is an offset involved. //There is no offset used here, but it's still a good practice here to set positions early on. display.setPosition(0, 0); //This uses the seeded RNG we made earlier to build a procedural dungeon using a method that takes rectangular //sections of pre-drawn dungeon and drops them into place in a tiling pattern. It makes good "ruined" dungeons. dungeonGen = new DungeonGenerator(gridWidth, gridHeight, rng); //uncomment this next line to randomly add water to the dungeon in pools. //dungeonGen.addWater(15); //decoDungeon is given the dungeon with any decorations we specified. (Here, we didn't, unless you chose to add //water to the dungeon. In that case, decoDungeon will have different contents than bareDungeon, next.) decoDungeon = dungeonGen.generate(); //getBareDungeon provides the simplest representation of the generated dungeon -- '#' for walls, '.' for floors. bareDungeon = dungeonGen.getBareDungeon(); //When we draw, we may want to use a nicer representation of walls. DungeonUtility has lots of useful methods //for modifying char[][] dungeon grids, and this one takes each '#' and replaces it with a box-drawing character. lineDungeon = DungeonUtility.hashesToLines(decoDungeon); // it's more efficient to get random floors from a packed set containing only (compressed) floor positions. short[] placement = CoordPacker.pack(bareDungeon, '.'); //Coord is the type we use as a general 2D point, usually in a dungeon. //Because we know dungeons won't be incredibly huge, Coord performs best for x and y values less than 256. cursor = Coord.get(-1, -1); //player is, here, just a Coord that stores his position. In a real game, you would probably have a class for //creatures, and possibly a subclass for the player. player = dungeonGen.utility.randomCell(placement); //This is used to allow clicks or taps to take the player to the desired area. toCursor = new ArrayList<Coord>(100); awaitedMoves = new ArrayList<Coord>(100); //DijkstraMap is the pathfinding swiss-army knife we use here to find a path to the latest cursor position. playerToCursor = new DijkstraMap(decoDungeon, DijkstraMap.Measurement.MANHATTAN); bgColor = SColor.DARK_SLATE_GRAY; colorIndices = DungeonUtility.generatePaletteIndices(decoDungeon); bgColorIndices = DungeonUtility.generateBGPaletteIndices(decoDungeon); // these were generated by the FakeLanguageGen class, which is compatible with most platforms SquidLib runs on, // but not HTML. So they are simply pre-generated chunks of text to show the glyph support in SquidLib. lang = new String[] { "Ned jation, quariok sied pebation gnadism erbiss!", "Tezen kisaiba konnouda, bubotan, ne rijonnozouna?", "M le roe leth glang ioui?", "Potron oxa kthoi opleipotron ola aisaisp kthou.", " ? ? ? ?.", "Tuskierovich topliegrachigary khodynamyv, toskiafi!", "?, ? ? !", "Hmaagrai eindian, ase agluxi-ugg?", "Gu, auna sazeun nonanen kunnenou ro.", "Esibnt srm tsed spoupot l dely?y go, sneiec bism ?lsi?", "aaire v?a? c? ; r, ??ggr n!", "Gatyriam reta - venn dn on? kazhy s, tsibiinki.", }; // this is a big one. // SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse // (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both. // keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish // between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The // implementation here handles hjkl keys (also called vi-keys), numpad, arrow keys, and wasd for 4-way movement. // Shifted letter keys produce capitalized chars when passed to KeyHandler.handle(), but we don't care about // that so we just use two case statements with the same body, i.e. one for 'A' and one for 'a'. // You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the // path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger // the event when someone clicks. input = new SquidInput(new SquidInput.KeyHandler() { @Override public void handle(char key, boolean alt, boolean ctrl, boolean shift) { switch (key) { case SquidInput.UP_ARROW: case 'k': case 'w': case 'K': case 'W': { //-1 is up on the screen move(0, -1); break; } case SquidInput.DOWN_ARROW: case 'j': case 's': case 'J': case 'S': { //+1 is down on the screen move(0, 1); break; } case SquidInput.LEFT_ARROW: case 'h': case 'a': case 'H': case 'A': { move(-1, 0); break; } case SquidInput.RIGHT_ARROW: case 'l': case 'd': case 'L': case 'D': { move(1, 0); break; } case 'Q': case 'q': case SquidInput.ESCAPE: { Gdx.app.exit(); break; } } } }, //The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen //input and converts it to grid coordinates (here, a cell is 12 wide and 24 tall, so clicking at the // pixel position 15,51 will pass screenX as 1 (since if you divide 15 by 12 and round down you get 1), // and screenY as 2 (since 51 divided by 24 rounded down is 2)). new SquidMouse(cellWidth, cellHeight, gridWidth, gridHeight, 0, 0, new InputAdapter() { // if the user clicks and there are no awaitedMoves queued up, generate toCursor if it // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (awaitedMoves.isEmpty()) { if (toCursor.isEmpty()) { cursor = Coord.get(screenX, screenY); //This uses DijkstraMap.findPath to get a possibly long path from the current player position //to the position the user clicked on. toCursor = playerToCursor.findPath(100, null, null, player, cursor); } awaitedMoves = new ArrayList<>(toCursor); } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of points that // receive highlighting). Uses DijkstraMap.findPath() to find the path, which is surprisingly fast. @Override public boolean mouseMoved(int screenX, int screenY) { if (!awaitedMoves.isEmpty()) return false; if (cursor.x == screenX && cursor.y == screenY) { return false; } cursor = Coord.get(screenX, screenY); toCursor = playerToCursor.findPath(100, null, null, player, cursor); return false; } })); //Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT Gdx.input.setInputProcessor(new InputMultiplexer(stage, input)); //You might be able to get by with the next line instead of the above line, but the former is preferred. //Gdx.input.setInputProcessor(input); // and then add display, our one visual component, to the list of things that act in Stage. stage.addActor(display); }
From source file:com.shiz.shzrgl.ShzRgl.java
private SquidInput getSquidInput() { return new SquidInput(new SquidInput.KeyHandler() { @Override//from w ww . j a v a 2s. c o m public void handle(char key, boolean alt, boolean ctrl, boolean shift) { } }, //The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen //input and converts it to grid coordinates (here, a cell is 12 wide and 24 tall, so clicking at the // pixel position 15,51 will pass screenX as 1 (since if you divide 15 by 12 and round down you get 1), // and screenY as 2 (since 51 divided by 24 rounded down is 2)). new SquidMouse(cellWidth, cellHeight, gridWidth, gridHeight, 0, 0, new InputAdapter() { // if the user clicks and there are no awaitedMoves queued up, generate toCursor if it // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (awaitedMoves.isEmpty()) { if (toCursor.isEmpty()) { cursor = Coord.get(screenX, screenY); //This uses DijkstraMap.findPath to get a possibly long path from the current player position //to the position the user clicked on. toCursor = playerToCursor.findPath(100, null, null, player, cursor); } awaitedMoves = new ArrayList<>(toCursor); } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of points that // receive highlighting). Uses DijkstraMap.findPath() to find the path, which is surprisingly fast. @Override public boolean mouseMoved(int screenX, int screenY) { if (!awaitedMoves.isEmpty()) return false; if (cursor.x == screenX && cursor.y == screenY) { return false; } cursor = Coord.get(screenX, screenY); toCursor = playerToCursor.findPath(100, null, null, player, cursor); return false; } })); }
From source file:com.squidpony.basic.demo.BasicGame.java
@Override public void create() { //These variables, corresponding to the screen's width and height in cells and a cell's width and height in //pixels, must match the size you specified in the launcher for input to behave. //This is one of the more common places a mistake can happen. //In our desktop launcher, we gave this arguments to the configuration: // config.width = 80 * 12; // config.height = 25 * 24; //Most games that do not use multiple Panels should probably use the same approach. width = 80;/*from w w w . j a v a2 s .com*/ height = 25; cellWidth = 12; cellHeight = 24; // gotta have a random number generator. We seed a LightRNG with any long we want, then pass that to an RNG. rng = new RNG(new LightRNG(0xd00d)); //Some classes in SquidLib need access to a batch to render certain things, so it's a good idea to have one. batch = new SpriteBatch(); //Here we make sure our Stage, which holds any text-based grids we make, uses our Batch. stage = new Stage(new ScreenViewport(), batch); // the font will try to load Inconsolata-LGC as a bitmap font from resources. // this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used. display = new SquidLayers(width, height, cellWidth, cellHeight, DefaultResources.smoothNameLarge); display.setAnimationDuration(0.03f); //These need to have their positions set before adding any entities if there is an offset involved. //There is no offset used here, but it's still a good practice here to set positions early on. display.setPosition(0, 0); //This uses the seeded RNG we made earlier to build a procedural dungeon using a method that takes rectangular //sections of pre-drawn dungeon and drops them into place in a tiling pattern. It makes good "ruined" dungeons. dungeonGen = new DungeonGenerator(width, height, rng); //uncomment this next line to randomly add water to the dungeon in pools. //dungeonGen.addWater(15); //decoDungeon is given the dungeon with any decorations we specified. (Here, we didn't, unless you chose to add //water to the dungeon. In that case, decoDungeon will have different contents than bareDungeon, next.) decoDungeon = dungeonGen.generate(); //getBareDungeon provides the simplest representation of the generated dungeon -- '#' for walls, '.' for floors. bareDungeon = dungeonGen.getBareDungeon(); //When we draw, we may want to use a nicer representation of walls. DungeonUtility has lots of useful methods //for modifying char[][] dungeon grids, and this one takes each '#' and replaces it with a box-drawing character. lineDungeon = DungeonUtility.hashesToLines(decoDungeon); // it's more efficient to get random floors from a packed set containing only (compressed) floor positions. short[] placement = CoordPacker.pack(bareDungeon, '.'); //Coord is the type we use as a general 2D point, usually in a dungeon. //Because we know dungeons won't be incredibly huge, Coord performs best for x and y values less than 256. cursor = Coord.get(-1, -1); //player is, here, just a Coord that stores his position. In a real game, you would probably have a class for //creatures, and possibly a subclass for the player. player = dungeonGen.utility.randomCell(placement); //This is used to allow clicks or taps to take the player to the desired area. toCursor = new ArrayList<Coord>(100); awaitedMoves = new ArrayList<Coord>(100); //DijkstraMap is the pathfinding swiss-army knife we use here to find a path to the latest cursor position. playerToCursor = new DijkstraMap(decoDungeon, DijkstraMap.Measurement.MANHATTAN); bgColor = SColor.DARK_SLATE_GRAY; colorIndices = DungeonUtility.generatePaletteIndices(decoDungeon); bgColorIndices = DungeonUtility.generateBGPaletteIndices(decoDungeon); // this is a big one. // SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse // (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both. // keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish // between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The // implementation here handles hjkl keys (also called vi-keys), numpad, arrow keys, and wasd for 4-way movement. // Shifted letter keys produce capitalized chars when passed to KeyHandler.handle(), but we don't care about // that so we just use two case statements with the same body, i.e. one for 'A' and one for 'a'. // You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the // path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger // the event when someone clicks. input = new SquidInput(new SquidInput.KeyHandler() { @Override public void handle(char key, boolean alt, boolean ctrl, boolean shift) { switch (key) { case SquidInput.UP_ARROW: case 'k': case 'w': case 'K': case 'W': { //-1 is up on the screen move(0, -1); break; } case SquidInput.DOWN_ARROW: case 'j': case 's': case 'J': case 'S': { //+1 is down on the screen move(0, 1); break; } case SquidInput.LEFT_ARROW: case 'h': case 'a': case 'H': case 'A': { move(-1, 0); break; } case SquidInput.RIGHT_ARROW: case 'l': case 'd': case 'L': case 'D': { move(1, 0); break; } case 'Q': case 'q': case SquidInput.ESCAPE: { Gdx.app.exit(); break; } } } }, //The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen //input and converts it to grid coordinates (here, a cell is 12 wide and 24 tall, so clicking at the // pixel position 15,51 will pass screenX as 1 (since if you divide 15 by 12 and round down you get 1), // and screenY as 2 (since 51 divided by 24 rounded down is 2)). new SquidMouse(cellWidth, cellHeight, width, height, 0, 0, new InputAdapter() { // if the user clicks and there are no awaitedMoves queued up, generate toCursor if it // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (awaitedMoves.isEmpty()) { if (toCursor.isEmpty()) { cursor = Coord.get(screenX, screenY); //This uses DijkstraMap.findPath to get a possibly long path from the current player position //to the position the user clicked on. toCursor = playerToCursor.findPath(100, null, null, player, cursor); } awaitedMoves = new ArrayList<>(toCursor); } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of points that // receive highlighting). Uses DijkstraMap.findPath() to find the path, which is surprisingly fast. @Override public boolean mouseMoved(int screenX, int screenY) { if (!awaitedMoves.isEmpty()) return false; if (cursor.x == screenX && cursor.y == screenY) { return false; } cursor = Coord.get(screenX, screenY); toCursor = playerToCursor.findPath(100, null, null, player, cursor); return false; } })); //Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT Gdx.input.setInputProcessor(new InputMultiplexer(stage, input)); //You might be able to get by with the next line instead of the above line, but the former is preferred. //Gdx.input.setInputProcessor(input); // and then add display, our one visual component, to the list of things that act in Stage. stage.addActor(display); }
From source file:com.squidpony.pandora.PandoraGame.java
@Override public void create() { // gotta have a random number generator. We seed a LightRNG with any long we want, then pass that to an RNG. lrng = new LightRNG(0xBADBEEFB0BBL); rng = new RNG(lrng); // SaturationFilter here is used to de-saturate the background and over-saturate the foreground. fgCenter = new SquidColorCenter(new Filters.SaturationFilter(1.15f)); bgCenter = new SquidColorCenter(new Filters.SaturationFilter(0.85f)); batch = new SpriteBatch(); width = 35;// w ww . jav a 2 s . c om height = 35; depth = 12; cellWidth = 8; cellHeight = 18; currentDepth = 0; decoDungeons = new char[depth][][]; bareDungeons = new char[depth][][]; lineDungeons = new char[depth][][]; // the font will try to load Inconsolata-LGC as a bitmap font from resources. // this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used. display = new SquidLayers(width * 2, height + 1, cellWidth, cellHeight, DefaultResources.smoothName, bgCenter, fgCenter); display.setAnimationDuration(0.04f); messages = new SquidMessageBox(width * 2, 4, new TextCellFactory().font(DefaultResources.smoothName) .width(cellWidth).height(cellHeight).initBySize()); stage = new Stage(new ScreenViewport(), batch); //These need to have their positions set before adding any entities if there is an offset involved. messages.setPosition(0, 0); display.setPosition(0, messages.getHeight()); messages.appendMessage("Pandora opened The Box of All Evil... to beat up All Evil."); messages.appendWrappingMessage("Use numpad or vi-keys to move, bump=attack. ? for help, q to quit."); counter = 0; dungeonGen = new DungeonGenerator(width, height, rng); dungeonGen.addWater(12); dungeonGen.addGrass(10); dungeonGen.addBoulders(15); dungeonGen.addDoors(8, false); SerpentDeepMapGenerator serpent = new SerpentDeepMapGenerator(width, height, depth, rng, 0.1); serpent.putCaveCarvers(3); serpent.putBoxRoomCarvers(1); serpent.putRoundRoomCarvers(1); char[][][] sg = serpent.generate(); for (int i = 0; i < depth; i++) { decoDungeons[i] = dungeonGen.generateRespectingStairs(sg[i]); // change the TilesetType to lots of different choices to see what dungeon works best. //bareDungeons = dungeonGen.generate(TilesetType.DEFAULT_DUNGEON); bareDungeons[i] = dungeonGen.getBareDungeon(); lineDungeons[i] = DungeonUtility .hashesToLines(DungeonUtility.doubleWidth(DungeonUtility.closeDoors(decoDungeons[i])), true); } // it's more efficient to get random floors from a packed set containing only (compressed) floor positions. short[] placement = CoordPacker.pack(bareDungeons[currentDepth], '.'); Coord pl = dungeonGen.utility.randomCell(placement); placement = CoordPacker.removePacked(placement, pl.x, pl.y); int numMonsters = 10; monsters = new HashMap<AnimatedEntity, Integer>(numMonsters); for (int i = 0; i < numMonsters; i++) { Coord monPos = dungeonGen.utility.randomCell(placement); placement = CoordPacker.removePacked(placement, monPos.x, monPos.y); monsters.put(display.animateActor(monPos.x, monPos.y, (FakeLanguageGen.GREEK_AUTHENTIC.word(rng, true) + "??").substring(0, 2), fgCenter.filter(display.getPalette().get(11)), true), 0); } // your choice of FOV matters here. fov = new FOV(FOV.RIPPLE_TIGHT); getToPlayer = new DijkstraMap(decoDungeons[currentDepth], DijkstraMap.Measurement.CHEBYSHEV); getToPlayer.rng = rng; getToPlayer.setGoal(pl); pathMap = getToPlayer.scan(null); res = DungeonUtility.generateResistances(decoDungeons[currentDepth]); fovmap = fov.calculateFOV(res, pl.x, pl.y, 8, Radius.SQUARE); player = display.animateActor(pl.x, pl.y, "@@", fgCenter.filter(display.getPalette().get(30)), true); cursor = Coord.get(-1, -1); toCursor = new ArrayList<Coord>(10); awaitedMoves = new ArrayList<Coord>(10); playerToCursor = new DijkstraMap(decoDungeons[currentDepth], DijkstraMap.Measurement.EUCLIDEAN); colors = DungeonUtility.generatePaletteIndices(decoDungeons[currentDepth]); bgColors = DungeonUtility.generateBGPaletteIndices(decoDungeons[currentDepth]); bgColor = SColor.DARK_SLATE_GRAY; lights = DungeonUtility.generateLightnessModifiers(decoDungeons[currentDepth], counter); seen = new boolean[depth][width][height]; lang = FakeLanguageGen.GREEK_AUTHENTIC.sentence(rng, 4, 5, new String[] { ",", ",", ";" }, new String[] { "...", "...", "...", "!", "." }, 0.1); // this is a big one. // SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse // (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both. // keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish // between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The // implementation here handles hjklyubn keys for 8-way movement, numpad for 8-way movement, arrow keys for // 4-way movement, and wasd for 4-way movement. Shifted letter keys produce capitalized chars when passed to // KeyHandler.handle(), but we don't care about that so we just use two case statements with the same body, // one for the lower case letter and one for the upper case letter. // You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the // path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger // the event when someone clicks. input = new SquidInput(new SquidInput.KeyHandler() { @Override public void handle(char key, boolean alt, boolean ctrl, boolean shift) { switch (key) { case SquidInput.UP_ARROW: case 'k': case 'w': case 'K': case 'W': { move(0, -1); break; } case SquidInput.DOWN_ARROW: case 'j': case 's': case 'J': case 'S': { move(0, 1); break; } case SquidInput.LEFT_ARROW: case 'h': case 'a': case 'H': case 'A': { move(-1, 0); break; } case SquidInput.RIGHT_ARROW: case 'l': case 'd': case 'L': case 'D': { move(1, 0); break; } case SquidInput.UP_LEFT_ARROW: case 'y': case 'Y': { move(-1, -1); break; } case SquidInput.UP_RIGHT_ARROW: case 'u': case 'U': { move(1, -1); break; } case SquidInput.DOWN_RIGHT_ARROW: case 'n': case 'N': { move(1, 1); break; } case SquidInput.DOWN_LEFT_ARROW: case 'b': case 'B': { move(-1, 1); break; } case '?': { toggleHelp(); break; } case 'Q': case 'q': case SquidInput.ESCAPE: { Gdx.app.exit(); break; } } } }, new SquidMouse(cellWidth, cellHeight, width, height, 0, 0, new InputAdapter() { // if the user clicks within FOV range and there are no awaitedMoves queued up, generate toCursor if it // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (fovmap[screenX / 2][screenY] > 0.0 && awaitedMoves.isEmpty()) { if (toCursor.isEmpty()) { cursor = Coord.get(screenX / 2, screenY); //Uses DijkstraMap to get a path. from the player's position to the cursor toCursor = playerToCursor.findPath(30, null, null, Coord.get(player.gridX, player.gridY), cursor); } awaitedMoves = new ArrayList<Coord>(toCursor); } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of points that // receive highlighting). Uses DijkstraMap.findPath() to find the path, which is surprisingly fast. @Override public boolean mouseMoved(int screenX, int screenY) { if (!awaitedMoves.isEmpty()) return false; if (cursor.x == screenX / 2 && cursor.y == screenY) { return false; } if (fovmap[screenX / 2][screenY] > 0.0) { cursor = Coord.get(screenX / 2, screenY); //Uses DijkstraMap to get a path. from the player's position to the cursor toCursor = playerToCursor.findPath(30, null, null, Coord.get(player.gridX, player.gridY), cursor); } return false; } })); // ABSOLUTELY NEEDED TO HANDLE INPUT Gdx.input.setInputProcessor(new InputMultiplexer(stage, input)); // and then add display and messages, our two visual components, to the list of things that act in Stage. stage.addActor(display); stage.addActor(messages); }
From source file:com.tnf.ptm.screens.main.InputMapControllerScreen.java
License:Apache License
@Override public void setEnterNewKey(boolean newKey) { isEnterNewKey = newKey;/*from ww w.jav a 2 s . c o m*/ // Cancel the key input if (!isEnterNewKey) { Gdx.input.setInputProcessor(null); Controllers.clearListeners(); } else { // Capture the new key input // Keyboard items Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(int keycode) { // Don't capture the escape key if (keycode == Input.Keys.ESCAPE) { return true; } if (selectedIndex >= controllerItems) { removeDuplicateKeys(keycode); InputConfigItem item = itemsList.get(selectedIndex); item.setInputKey(Input.Keys.toString(keycode)); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; return true; // return true to indicate the event was handled } }); // Controller items // setup the listener that prints events to the console Controllers.addListener(new ControllerListener() { public int indexOf(Controller controller) { return Controllers.getControllers().indexOf(controller, true); } @Override public void connected(Controller controller) { } @Override public void disconnected(Controller controller) { } @Override public boolean buttonDown(Controller controller, int buttonIndex) { // Do nothing on button down - register the button up event return true; } @Override public boolean buttonUp(Controller controller, int buttonIndex) { logger.printDebug(String.format("#{}, button {} up", indexOf(controller), buttonIndex)); if (selectedIndex < controllerItems) { removeDuplicateButtons(buttonIndex); InputConfigItem item = itemsList.get(selectedIndex); item.setIsAxis(false); item.setControllerInput(buttonIndex); item.setInputKey("Button: " + buttonIndex); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; return true; // return true to indicate the event was handled } @Override public boolean axisMoved(Controller controller, int axisIndex, float value) { logger.printDebug(String.format("#{}, axis {}: {}", indexOf(controller), axisIndex, value)); if (value > 0.5f || value < -0.5f) { if (selectedIndex < controllerItems) { InputConfigItem item = itemsList.get(selectedIndex); item.setIsAxis(true); item.setControllerInput(axisIndex); item.setInputKey("Axis: " + axisIndex); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; } return true; } @Override public boolean povMoved(Controller controller, int povIndex, PovDirection value) { return false; } @Override public boolean xSliderMoved(Controller controller, int sliderIndex, boolean value) { return false; } @Override public boolean ySliderMoved(Controller controller, int sliderIndex, boolean value) { return false; } @Override public boolean accelerometerMoved(Controller controller, int accelerometerIndex, Vector3 value) { return false; } }); } }
From source file:com.tnf.ptm.screens.main.InputMapKeyboardScreen.java
License:Apache License
@Override public void setEnterNewKey(boolean newKey) { isEnterNewKey = newKey;/*from w w w .j av a 2 s .c o m*/ // Cancel the key input if (!isEnterNewKey) { Gdx.input.setInputProcessor(null); } else { // Capture the new key input Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(int keycode) { // Don't capture the escape key if (keycode == Input.Keys.ESCAPE) { return true; } removeDuplicateKeys(keycode); InputConfigItem item = itemsList.get(selectedIndex); item.setInputKey(Input.Keys.toString(keycode)); itemsList.set(selectedIndex, item); Gdx.input.setInputProcessor(null); isEnterNewKey = false; return true; // return true to indicate the event was handled } }); } }
From source file:de.cwclan.gdxtest.core.games.CarGame.java
@Override public void show() { world = new World(new Vector2(0, -9.8f), true); debugRenderer = new Box2DDebugRenderer(); batch = new SpriteBatch(); camera = new OrthographicCamera(Gdx.graphics.getWidth() / 25, Gdx.graphics.getHeight() / 25); BodyDef bodyDef = new BodyDef(); FixtureDef fixtureDef = new FixtureDef(); FixtureDef wheelFixtureDef = new FixtureDef(); //car/*w w w .j av a2 s . c o m*/ fixtureDef.density = 5; fixtureDef.friction = .4f; fixtureDef.restitution = .3f; wheelFixtureDef.density = fixtureDef.density * 1.5f; wheelFixtureDef.friction = 50; wheelFixtureDef.restitution = .4f; car = new Car(world, fixtureDef, wheelFixtureDef, 0, 3, 3, 1.5f); Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter() { @Override public boolean keyDown(int keycode) { switch (keycode) { case Keys.ESCAPE: ((com.badlogic.gdx.Game) Gdx.app.getApplicationListener()).setScreen(new LevelMenu()); break; } return false; } @Override public boolean scrolled(int amount) { camera.zoom += amount / 25f; return true; } }, car)); /* * the ground */ ChainShape groundShape = new ChainShape(); groundShape.createChain(new Vector2[] { new Vector2(-50, 10), new Vector2(-49, 0), new Vector2(-40, 0), new Vector2(-30, -1), new Vector2(-20, 0), new Vector2(-10, -1), new Vector2(0, 1), new Vector2(10, 2), new Vector2(20, 0), new Vector2(30, -1), new Vector2(40, -2), new Vector2(50, 0) }); bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(0, 0); fixtureDef.friction = .5f; fixtureDef.restitution = 0; fixtureDef.shape = groundShape; world.createBody(bodyDef).createFixture(fixtureDef); groundShape.dispose(); /* * another ground */ groundShape = new ChainShape(); groundShape.createChain( new Vector2[] { new Vector2(40, -5), new Vector2(50, -3), new Vector2(60, 0), new Vector2(70, -1), new Vector2(80, 3), new Vector2(90, -1), new Vector2(100, 1), new Vector2(110, 2), new Vector2(120, 0), new Vector2(130, -1), new Vector2(140, -2), new Vector2(150, 0) }); world.createBody(bodyDef).createFixture(fixtureDef); groundShape.dispose(); }
From source file:de.cwclan.gdxtest.core.games.JumperGame.java
@Override public void show() { if (Gdx.app.getType() == Application.ApplicationType.Desktop) { Gdx.graphics.setDisplayMode((int) (Gdx.graphics.getHeight() / 1.5), Gdx.graphics.getHeight(), false); }//w w w . j av a2 s . co m world = new World(new Vector2(0, -9.8f), true); debugRenderer = new Box2DDebugRenderer(); batch = new SpriteBatch(); camera = new OrthographicCamera(Gdx.graphics.getWidth() / 25, Gdx.graphics.getHeight() / 25); BodyDef bodyDef = new BodyDef(); FixtureDef fixtureDef = new FixtureDef(); FixtureDef wheelFixtureDef = new FixtureDef(); //car fixtureDef.density = 5; fixtureDef.friction = .4f; fixtureDef.restitution = .3f; wheelFixtureDef.density = fixtureDef.density * 1.5f; wheelFixtureDef.friction = 50; wheelFixtureDef.restitution = .4f; player = new Player(world, 0, 1, 1); world.setContactFilter(player); world.setContactListener(player); Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter() { @Override public boolean keyDown(int keycode) { switch (keycode) { case Keys.ESCAPE: ((com.badlogic.gdx.Game) Gdx.app.getApplicationListener()).setScreen(new LevelMenu()); break; } return false; } @Override public boolean scrolled(int amount) { camera.zoom += amount / 25f; return true; } }, player)); /* * the ground */ ChainShape groundShape = new ChainShape(); buttomLeft = new Vector3(0, Gdx.graphics.getHeight(), 0); buttomRight = new Vector3(Gdx.graphics.getWidth(), buttomLeft.y, 0); camera.unproject(buttomLeft); camera.unproject(buttomRight); groundShape.createChain(new float[] { buttomLeft.x, buttomLeft.y, buttomRight.x, buttomRight.y }); bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(0, 0); fixtureDef.friction = .5f; fixtureDef.restitution = 0; fixtureDef.shape = groundShape; Body ground = world.createBody(bodyDef); ground.createFixture(fixtureDef); groundShape.dispose(); // //a test platform // groundShape = new ChainShape(); // groundShape.createChain(new float[]{buttomRight.x / 10, 3, buttomRight.x / 4, 3}); // world.createBody(bodyDef).createFixture(fixtureDef); // levelGenerator = new LevelGenerator(ground, buttomLeft.x, buttomRight.x, player.HEIGHT / 2, player.HEIGHT * 3, player.WIDTH * 1.5f, player.WIDTH * 4f, player.WIDTH / 3, 0);//10*MathUtils.degRad); }