I am using a Path in AndEngine that allows a sprite to be moved to a specific location providing the X and Y coordinates.
i have a cloud attached to my scehe, and i want the cloud to move back and forth from side to side but not exceeding the camera, on the X axis(which would be horizontal in landscape mode).
Here is what i have so far:
Sprite cloudSprite = new Sprite(50, 300, (TextureRegion)this.cloud);
final Path path = new Path(10).to(50,300).to(100, 300);
cloudSprite.registerEntityModifier(new LoopEntityModifier(new PathModifier(10, path)));
This doesnt work correctly though, ive tried changing the X, and Y to parameters but to no avail.
Anyone know how i could get this done?
You shouldn't be using a PathModifier for this purpose; Use MoveXModifier instead.
final float minX = 0;
final float maxX = CAMERA_WIDTH - cloudSprite.getWidth();
final float duration = //Duration for the full move across the screen here.
final MoveXModifier rightMoveModifier = new MoveXModifier(minX, maxX, duration);
final MoveXModifier leftMoveModifier = new MoveXModifier(maxX, minX, duration);
cloudSprite.registerEntityModifier(new LoopEntityModifier(new SequenceModifier(rightMoveModifier, leftMoveModifier)));
(Here we assume the cloud is placed in the left of the screen when the game loads)
This should work.
Related
I have two bitmaps that I draw onto the center of a canvas:
One is only a background, it's a spirit level in top view which doesnt move. The second one is a bitmap looking like a "air bubble". When the user tilts the phone, the sensors read the tilt and the air bubble moves according to the sensor values along the x-axis. However, I need to make sure that the air bubble doesnt move too far, e.g out of the background-bitmap.
So I tried to which x coordinate the bubble can travel to,
before I have to set xPos = xPos -1 using trial and error
This works fine on my device.
To clarify: On my phone, the air bubble could move to the coordinate x = 50 from the middle of the screen. This would be the point, where the bitmap is at the very left of the background spirit level.
On a larger phone, the position x = 50 is too far left, and therefore looking like the air bubble travelled out of the water level.
Now I've tried following:
I calculated the area in % in which the air bubble can move. Let's say that
is 70% of the entire width of the bitmap. So I tried to calculate the two x boundary values:
leftBoundary = XmiddlePoint - (backgroundBitmap.getWidth() * 0.35);
rightBoundary = XmiddlePoint + (backgroundBitmap.getWidth() * 0.35);
...which doesnt work when testing with different screen sizes :(
Is it possible to compensate for different screen sizes and densities using absolute coordinates or do I have to rethink my idea?
If you need any information that I forgot about, please let me know. If this question has already been answered, I would appreciate a link :) Thanks in advance!
Edit:
I load my bitmaps like this:
private Bitmap backgroundBitmap;
private static final int BITMAP_WIDTH = 1898;
private static final int BITMAP_HEIGHT = 438;
public class SimulationView extends View implements SensorEventListener{
public SimulationView(Context context){
Bitmap map = BitmapFactory.decodeResource(getResources, R.mipmap.backgroundImage);
backgroundBitmap = Bitmap.createScaledBitmap(map, BITMAP_WIDTH, BITMAP_HEIGHT, true;
}
and draw it like this:
protected void onDraw(Canvas canvas){
canvas.drawBitmap(backgroundBitmap, XmiddlePoint - BITMAP_WIDTH / 2, YmiddlePont - BITMAP_HEIGHT / 2, null);
}
backgroundBitmap.getWidth() and getHeight() prints out the correct sizes.
Calculating like mentioned above would return following boundaries:
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
//which prints out width = 2392
xMiddlePoint = width / 2;
// = 1196
leftBoundary = xMiddlePoint - (BITMAP.getWidth()* 0.35);
// = 531,7
However, when I use trial and error, the right x coordinate seems to be at around 700.
I've come across a great explanation on how to fix my issue here.
As user AgentKnopf explained, you have to scale coordinates or bitmaps like this:
X = (targetScreenWidth / defaultScreenWidth) * defaultXCoordinate
Y = (targetScreenHeight / defaultScreenHeight) * defaultYCoordinate
which, in my case, translates to:
int defaultScreenWidth = 1920;
int defaultXCoordinate = 333;
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
displayWidth = displayMetrics.widthPixels;
leftBoundary = (displayWidth / defaultScreenWidth) * defaultXCoordinates
what would be the best way to change a texture of a unit?
I have this controllable bird, and when you press to the left of it, I want to change texture so that the bird is tilted to the left, the same goes for when pressing to the right. basicly, I want to change the image of the bird.
I have got it working, but can't help to think there is a better way to do it, this is what I have:
Texture birdOriginal;
Texture birdLeft;
Texture batRight;
birdOriginal = new Texture(Gdx.files.internal("textures/birdNew.png"));
birdLeft = new Texture(Gdx.files.internal("textures/birdLeft.png"));
birdRight = new Texture(Gdx.files.internal("textures/birdRight.png"));
//psuedo code
if (birdPosition > touchPosition){
birdImage = birdRight;
}
if (birdPosition < touchPosition){
birdImage = birdRight;
}
if (!Gdx.input.isTouched()){
birdImage = birdOriginal;
}
As I said, this works, but I am asking because I wan't to make the wings go up and down everytime I press the screen, and I don't think I can swap between textures to do that.
thanks for listening.
This can be done by using the same texture instead of multiple ones, declare it as a sprite.
With sprites you can manipulate the image much easier such as rotation and flipping.
You could also keep using texture and use the following
draw(Texture texture, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY)
<code>
Sprite bird = new Sprite(birdTexture);
bird.setFlip(true, false);
bird.rotate(0.45);
</code>
http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html
I am using LibGDX and Box2d to build my first Android game. Yay!
But I am having some serious problems with Box2d.
I have a simple stage with a rectangular Box2d body at the bottom representing the ground, and two other rectangular Box2d bodies both at the left and right representing the walls.
A Screenshot
Another Screenshot
I also have a box. This box can be touched and it moves using applyLinearImpulse, like if it was kicked. It is a DynamicBody.
What happens is that in my draw() code of the Box object, the Box2d body of the Box object is giving me a wrong value for the X axis. The value for the Y axis is fine.
Those blue "dots" on the screenshots are small textures that I printed on the box edges that body.getPosition() give me. Note how in one screenshot the dots are aligned with the actual DebugRenderer rectangle and in the other they are not.
This is what is happening: when the box moves, the alignment is lost in the movement.
The collision between the box, the ground and the walls occur precisely considering the area that the DebugRenderer renders. But body.getPosition() and fixture.testPoint() considers that area inside those blue dots.
So, somehow, Box2d is "maintaining" these two areas for the same body.
I thought that this could be some kind of "loss of precision" between my conversions of pixels and meters (I am scaling by 100 times) but the Y axis uses the same technique and it's fine.
So, I thought that I might be missing something.
Edit 1
I am converting from Box coordinates to World coordinates. If you see the blue debug sprites in the screenshots, they form the box almost perfectly.
public static final float WORLD_TO_BOX = 0.01f;
public static final float BOX_TO_WORLD = 100f;
The box render code:
public void draw(Batch batch, float alpha) {
x = (body.getPosition().x - width/2) * TheBox.BOX_TO_WORLD;
y = (body.getPosition().y - height/2) * TheBox.BOX_TO_WORLD;
float xend = (body.getPosition().x + width/2) * TheBox.BOX_TO_WORLD;
float yend = (body.getPosition().y + height/2) * TheBox.BOX_TO_WORLD;
batch.draw(texture, x, y);
batch.draw(texture, x, yend);
batch.draw(texture, xend, yend);
batch.draw(texture, xend, y);
}
Edit 2
I am starting to suspect the camera. I got the DebugRenderer and a scene2d Stage. Here is the code:
My screen resolution (Nexus 5, and it's portrait):
public static final int SCREEN_WIDTH = 1080;
public static final int SCREEN_HEIGHT = 1920;
At the startup:
// ...
stage = new Stage(SCREEN_WIDTH, SCREEN_HEIGHT, true);
camera = new OrthographicCamera();
camera.setToOrtho(false, SCREEN_WIDTH, SCREEN_HEIGHT);
debugMatrix = camera.combined.cpy();
debugMatrix.scale(BOX_TO_WORLD, BOX_TO_WORLD, 1.0f);
debugRenderer = new Box2DDebugRenderer();
// ...
Now, the render() code:
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
world.step(1/45f, 6, 6);
world.clearForces();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
debugRenderer.render(world, debugMatrix);
}
Looks like the answer to that one was fairly simple:
stage.setCamera(camera);
I was not setting the OrthographicCamera to the stage, so the stage was using some kind of default camera that wasn't aligned with my stuff.
It had nothing to do with Box2d in the end. Box2d was returning healthy values, but theses values were corresponding to wrong places in my screen because of the wrong stage resolution.
Hy, I have started a Game in andengine for android, I want to apply a jump functionality on a sprite which will be like some projectile motion , up and forward as well . I have applied move modifier to gain that functionality. But that is not in projectile motion.
How can i achieve that and while the jump of my sprite by tapping again it cant jump again until it completes it jump.i dont want to use delay function on scene touch .any help .
final Entity playerEntity = move;
final float jumpDuration = 1;
final float startX = playerEntity.getX();
final float jumpHeight = 60;
move.getTextureRegion().setFlippedVertical(true);
final MoveModifier jumpForwardUp = new MoveModifier(jumpDuration/2, startX, startX - jumpHeight, playerEntity.getY(), playerEntity.getY() + 130);
final MoveModifier jumpForwardDown = new MoveModifier(jumpDuration/2, startX - jumpHeight, startX, playerEntity.getY() + 130, playerEntity.getY() + 170);
final SequenceEntityModifier modifier = new SequenceEntityModifier(jumpForwardUp ,jumpForwardDown);
playerEntity.registerEntityModifier(modifier);
Try using JumpModifier and for some real physics work, go for Box2d Extension of AndEngine and go through some of AndEngine examples code.
Edit:
AndEngine have list of modifiers. JumpModifier is one of them. Maintain a class level or project level flag that is true when your object is in jump and is false when object is in normal state.
Every modifier takes an object of IModifierListner set that flag to true in onStart of IModifierListner and set that to false at onEnd of IModifierListner. at every tap check if that flag is true then simple return and do nothing.
I'm developing a simple game by andengine.
I have 10 balls which are moving randomly on screen.i'm importing the balls as picture in sprites.if they move at the same coordinate , they pass though their own insides.but i want: if they move at the same coodirnates ,they should change their directions.so they cannot pass through their insides.how can i do that?
private Runnable mStartCircle = new Runnable() {
public void run() {
int i = circleNumber++;
Scene scene = Level1Activity.this.mEngine.getScene();
float startY = -64.0f;
float startX = randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
float a= randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
circles[i] = new Sprite(startX, startY, textRegCircle[i]);
circles[i].registerEntityModifier(
(IEntityModifier) new SequenceEntityModifier (
new MoveModifier(10.0f, circles[i].getX(), a,
circles[i].getY(),CAMERA_HEIGHT+64.0f)));
}
scene.getLastChild().attachChild(circles[i]);
if (circleNumber < 10){
mHandler.postDelayed(mStartCircle,1000);
}
}
};
Each object(ball) requires a bounding box, or in your case a bounding circle, which is equal to the size of your sprite.
When the game updates and any balls position changes, you have to test for collisions.
Circle to circle collision testing is the simplest type to do.
if distance between (ball1.pos + ball2.pos) is less than (ball1.radius + ball2.radius) = collision.
You then handle the collision by reversing the velocities or calculating new momentums or something. (You also need to move the objects apart so they are no longer colliding)
Just apply a physical connector between balls:
so it will collide and bounce back.
final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f, 0.5f, 0.5f);
final Body ballBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, circles[i],BodyType.DynamicBody, boxFixtureDef);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(circles[i], ballBody, true, true));
this.mScene.attachChild(circles[i]);