Libgdx Creating On Screen Controls - android

I am using the libgdx framework to create a game. I'm trying create onscreen buttons/controls.
Currently, I have a
class LevelOne that implements Screen.
This class has a private variable world (From Box2d)
I want to add a
Table with Textbuttons or a Libgdx Touchpad to the Box2d world.
However, I'm not sure how to do this.
Next, I know I can add a table or a touchpad to a Libgdx Stage. Is there anyway to get the Libgdx stage and Box2d world to work together so, I can add a Touchpad or Table to the Box2d world.

For onscreen controls, you can do it like this:
Make a new cam which will be fixed for the controls:
OrthographicCamera guicam = new OrthographicCamera(480, 320);
guicam.position.set(480/2F, 320/2F, 0);
Make a (libgdx) Rectangle for each control:
Rectangle wleftBounds = new Rectangle(0, 0, 80, 80);
Rectangle wrightBounds = new Rectangle(80, 0, 80, 80);
Create a new Vector3 to hold your unprojected touch coordinates:
Vector3 touchPoint = new Vector3();
Then you can poll the Input to see if the user is touching these rectangles:
//in render method
for (int i=0; i<5; i++){
if (!Gdx.input.isTouched(i)) continue;
guicam.unproject(touchPoint.set(Gdx.input.getX(i), Gdx.input.getY(i), 0));
if (wleftBounds.contains(touchPoint.x, touchPoint.y)){
//Move your player to the left!
}else if (wrightBounds.contains(touchPoint.x, touchPoint.y)){
//Move your player to the right!
}
}
Notice I'm checking the first 5 touch indexes, thats because you will surely want to have controls that are being used at the same time (i.e. Jumping while Moving Right).
Last but not least, you will want to draw some nice graphics over the controls:
batch.draw(leftRegion, wleftBounds.x, wleftBounds.y, wleftBounds.width, wleftBounds.height);
batch.draw(rightRegion, wrightBounds.x, wrightBounds.y, wrightBounds.width, wrightBounds.height);

If you want to include a HUD stage
Create HUD matrix (import com.badlogic.gdx.math.Matrix4):
HUDMatrix = camera.combined.cpy();
HUDMatrix.setToOrtho2D(0, 0, wwidth, wheight);
Then draw it HUD
batch.setProjectionMatrix(HUDMatrix);
batch.begin();
stage.draw(batch)
batch.end();

Related

Continuous scrolling of background sprite synchronising with a moving sprite in andEngine

I am new in andengine game Development. I am trying to make a game where a playerSprite moves forward and backward through X- axis. How can I continuously move the background along with the playerSprite ? If the player goes forward , the background will go forward and will repeat itself continuously . Same for moving the playerSprite to backward. How can I do this ?
What you are looking for is ParalaxBackground. Here is simple example:
private void createBackground()
{
ParallaxBackground background = new ParallaxBackground(0, 0, 0);
background.attachParallaxEntity(new ParallaxEntity(0, new Sprite(0, 0, background_region, vbo)));
scene.setBackground(background);
}
It is from Matim-Dev andEngine Tutorial: Matim-Dev tutorial
You might also look into sample code for AutoParalaxBackground: AutoParalaxBackground

why detected object jumps using OpenCV

Ok I have a strange problem. I'll try to describe it as best as I can.
I've learned my app to detect a car when looking on it from the side
Imgproc.cvtColor(aInputFrame, grayscaleImage, Imgproc.COLOR_RGBA2RGB);
MatOfRect objects = new MatOfRect();
// Use the classifier to detect cars
if (cascadeClassifier != null) {
cascadeClassifier.detectMultiScale(grayscaleImage, objects, 1.1, 1,
2, new Size(absoluteObjectSize, absoluteObjectSize),
new Size());
}
for (int i = 0; i < dataArray.length; i++) {
Core.rectangle(aInputFrame, dataArray[i].tl(), dataArray[i].br(),
new Scalar(0, 255, 0, 255), 3);
mRenderer.setCameraPosition(-5, 5, 60f);
}
Now, this code works nice. I mean that i detects cars and it marks them with green rectangle. The problem is that the marked rectangle jumps like hell. I mean even when the phone is hold still the rectangle jumps from left to right to middle. There is never one still rectangle. I hope I've described the problem properly. I would like to stabilizy the marking cause I want to draw an overlay based on it and I can't make it to jump like this
See(1) the parameters for detectMultiScale and it expects
image of type CV_8U. You will need to convert to gray scale image
with COLOR_RGBA2GRAY instead of COLOR_RGBA2RGB
In detectMultiScale, increase the number of neighbours parameter to avoid false positives.
Suggestion: If input is a video stream, don't run
detectMultiScale on every frame. It is slow even if you use LBP
cascades. Try detection in one frame, followed by tracking techniques.

Sprites attached to scene without intention

I have three TextureRegions that are created like this:
mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuTextureAtlas, pActivity, "menu_background.png", 0, 0);
mPlayBtnTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuTextureAtlas, pActivity, "play_btn.png", 50, 100);
mExitBtnTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuTextureAtlas, pActivity, "exit_btn.png", 50, 200);
I also have corresponding sprites for each TextureRegion which are created like this:
mBackgroundSprite = new Sprite(0, 0, mBackgroundTextureRegion, mBufferObjectManager);
mPlayBtnSprite = new Sprite(0, 0, mPlayBtnTextureRegion, mBufferObjectManager);
mExitBtnSprite = new Sprite(0, 0, mExitBtnTextureRegion, mBufferObjectManager);
When I attach mBackgroundSprite to a scene like this:
mScene.attachChild(mBackgroundSprite);
I would expect only mBackgroundTextureRegion to appear on the scene (i.e. "menu_background.png") but in reality all three TextureRegions appear (i.e. mPlayBtnTextureRegion and mExitBtnTextureRegion appear too in their location as well, (50,100) and (50,200) respectively).
My questions are:
A. Why does this happen? (does it have something to do with using the same Texture for all TextureRegions?)
B. What is the correct way to make only one TextureRegion appear on a scene?
No this has nothing to do with the texture atlas. This is the correct way of doing it more or less. Nothing should be shown on the screen unless they are attached as a child to something (scene or engine). If you need more straightforward help please upload the part of your code that you are loading the sprite.

LibGdx: Mismatch between mouse position and selected tile(world position)

I've created a hex tile map and I a problem in combining two features:
1) scrolling the map by dragging with the mouse/finger
2) highlighting a tile on mouse over position
My world contains a map, which consists of custom Tile() objects. Each Tile has an x and y coordinate saved. In my game class I use an OrthographicCamera and a TileSelector, a class that gets the current mouse position and highlights the appropriate tile underneath those coordinates.
Further more, my render() method checks whether the mouse/finger is down and if so, each tile's position is updated by the distance moved while finger/mouse button down.
The following code shows the relevant parts. As long as I don't move the map, the highlighting works. But as soon as I do move the tiles, the highlighting starts to be off (by the amount of the distance moved).
//initialiting orthographic camera
camera = new OrthographicCamera(800, 480);
camera.setToOrtho(false, 800, 480);
//draw screen black
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
//drawing to batch
game.batch.begin();
//drawing the tiles, simply getting x,y coords and putting on screen
world.render(game.batch);
//highlighting tile under the current mouse/finger coords and drawing highlight on screen
selector.select(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY(), game.batch, world);
game.batch.end();
//scrolling routine
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
deltaX = (float)Gdx.input.getDeltaX();
deltaY = (float)Gdx.input.getDeltaY();
//moving each tile by the distance moved
for(int i = 0; i< world.getMap().getWidth(); i++){
for(int j = 0; j< world.getMap().getHeight(); j++){
tile = world.getMap().getTile(i, j);
tile.x += deltaX;
tile.y -= deltaY;
world.getMap().setTile(tile, i, j);
}
}
}
See screenshots for visualization:
1)Map not moved, mouse(red arrow) over tile and it is highlighted
http://i.stack.imgur.com/3d7At.png
2)Map moved but mouse on old position, no tile should be highlighted, but the tile is highlighted as if the map has not moved
http://i.stack.imgur.com/dSibc.png
Now I understand that the problem seems to arise from not mapping/updating screen and world coordinates correctly. But due to my lack of knowledge about LibGdx/OpenGL/projecting/translating I can't pinpoint my mistake.
So can this rendering algorithm be fixed as it is? Or should I switch from moving my tiles to moving my camera(how)? Please let me know, if you need more of the code, thank you.
Alright, I was able to find a solution on my own, since the problem was rather in the logic and not in the LibGdx API. In case somebody else has the same issue in the future, I'll provide the solution here.
At first I followed Angel-Angel's tip and started to move the camera instead of the map/world. Second, the main problem was the fact, that I used the screen coordinates of my mouse/finger for the tile highlighting, instead of the world coordinates.
The new code:
//scrolling routine
if (Gdx.input.isTouched()) {
//get mouse/finger position in screen coordinates and save in a Vector3
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
//get the distance moved by mouse/finger since last frame and translate camera to that position
//(I have no idea yet why the x-axis is flipped)
deltaX = (float)Gdx.input.getDeltaX();
deltaY = (float)Gdx.input.getDeltaY();
camera.translate(-deltaX, deltaY, 0);
//this is the solution, the coordinates that you use for tile highlighting
//are translated to world coordinates
touchPos = camera.unproject(touchPos);
}
//update the camera position and the math that is involved
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
world.render(game.batch);
//now the highlighting routine is working with world coordinates
selector.select(touchPos.x, touchPos.y, game.batch, world);
game.batch.end();
I hope this will help out in the future. If anyone is interested how I get the right tile for highlighting, I use the method described in the highest rated answer in this thread:
Hexagonal Grids, how do you find which hexagon a point is in?
Good luck and have fun!

Attach Sprite on another Sprite ANDENGINE

I am working on andengine and i have two sprite one is plate and the other is an apple . My plate sprite move form point 1 to point 2 and my apple sprite is jumping up and down.
Now i want to make apple jump on plate. I tried it with attched child apple with plate but the apple not place on the plate. Apple place below the plate i used zindex but its not working.
Actually problem is to move apple and plate at the same time. Any help would be appriciated. I am stuck with that that why this is happening and what will be solution .Here is my code:
plateDisplay = new Sprite( 250, 300, this.plate, this.getVertexBufferObjectManager());
appleDisplay = new Sprite( 250, 140, this.apple, this.getVertexBufferObjectManager());
plateDisplay.registerEntityModifier(new LoopEntityModifier(new PathModifier(20, path, EaseLinear.getInstance())));
appleDisplay.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier(new MoveYModifier(1, appleDisplay.getY(),
(appleDisplay.getY()+70), EaseBounceInOut.getInstance()))));
this.appleDisplay.setZIndex(1);
plateDisplay.setZIndex(0);
plateDisplay.attachChild(this.appleDisplay);
scene.attachChild(plateDisplay);
The issue you are having is that there are different coordinate systems for each object. The Plate sprite has its own X and Y in the scene coordinates. But when you add the apple to the plate object you are now using the plates local coordinates. So if the apple was on the scene's 50,50, when you add it to the plate, it will now be 50,50 as measured from the transform center point of the plate.
There are LocaltoScene and ScenetoLocal coordinate utilities in andengine to help you make this conversion. But underneath they are not super complex - they just add the transforms of all the nested sprites. Both utilites are part of the Sprite class, so you call them from the sprite in question. In your case probably
// Get the scene coordinates of the apple as an array.
float[] coodinates = [appleDisplay.getX(), appleDisplay.getY()];
// Convert the the scene coordinates of the apple to the local corrdinates of the plate.
float[] localCoordinates = plateDisplay.convertSceneToLocalCoordinates(coordinates);
// Attach and set position of apple
appleDisplay.setPosition(localCoordinates[0], localCoordintates[1]);
plateDisplay.attachChild(appleDisplay);

Categories

Resources