I am developing a game in AndEngine and I want to attach a sprite to a parallax background (on my main menu) BUT I don't want the sprite to be repeated (which is what is currently happening).
I have tried this (below) which works but I use the sprites in the game so when I come back to the main menu, the sprites will have moved (I tried resetting the sprites but doesn't seem to be working).
Sprite playerCar = new Sprite(playerX, playerY,
mResourceManager.mPlayerCarTextureRegion,
mVertexBufferObjectManager);
playerCar.setRotation(-15);
attachChild(playerCar);
What I want to do is the following:
Define my sprite as normal:
Sprite playerCar = new Sprite(playerX, playerY,
mResourceManager.mPlayerCarTextureRegion,
mVertexBufferObjectManager);
playerCar.setRotation(-15);
Then attach it to my background:
ParallaxBackground menuParallaxBackground = new ParallaxBackground(0,
0, 0);
menuParallaxBackground.attachParallaxEntity(new ParallaxEntity(0,
new Sprite(0, SCREEN_HEIGHT
- mResourceManager.mParallaxLayerRoad.getHeight(),
mResourceManager.mParallaxLayerRoad,
mVertexBufferObjectManager)));
menuParallaxBackground.attachParallaxEntity(new ParallaxEntity(0,
playerCar));
Which also works but the car keeps on repeating which I do not want.
Any help would be appreciated! Thanks.
Problem was because of the onDraw method on the ParallaxEntity class in the ParallaxBackground class. There was a loop around where the sprites get drawn that keeps going until the sprites fill up the width of the screen. I simply created a custom class and removed the while loop so I could use it for my Main Menu.
ParallaxEntity onDraw code before:
public void onDraw(final GLState pGLState, final Camera pCamera, final float pParallaxValue) {
pGLState.pushModelViewGLMatrix();
{
final float cameraWidth = pCamera.getWidth();
final float shapeWidthScaled = this.mAreaShape.getWidthScaled();
float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled;
while(baseOffset > 0) {
baseOffset -= shapeWidthScaled;
}
pGLState.translateModelViewGLMatrixf(baseOffset, 0, 0);
float currentMaxX = baseOffset;
do {
this.mAreaShape.onDraw(pGLState, pCamera);
pGLState.translateModelViewGLMatrixf(shapeWidthScaled, 0, 0);
currentMaxX += shapeWidthScaled;
} while(currentMaxX < cameraWidth);
}
pGLState.popModelViewGLMatrix();
}
my CustomParallaxEntity onDraw code after (notice the last while loop removed):
public void onDraw(final GLState pGLState, final Camera pCamera,
final float pParallaxValue) {
pGLState.pushModelViewGLMatrix();
{
final float shapeWidthScaled = this.mAreaShape.getWidthScaled();
float baseOffset = (pParallaxValue * this.mParallaxFactor)
% shapeWidthScaled;
while (baseOffset > 0) {
baseOffset -= shapeWidthScaled;
}
pGLState.translateModelViewGLMatrixf(baseOffset, 0, 0);
this.mAreaShape.onDraw(pGLState, pCamera);
pGLState.translateModelViewGLMatrixf(shapeWidthScaled, 0, 0);
}
pGLState.popModelViewGLMatrix();
}
Thanks to the comments on my question for helping me figure out a solution.
Related
Im new on Box2d got a problem and couldnt solve it.
I want to move my player left and right when the user touch my left and right buttons.
I created a fixture I can move body and fixture but not the player sprite
How can I attach my player sprite to my body ?
and How should I control body because I cant stop it.
I want to find a proper way of controlling player in box2d. I couldnt use setLinerVelocity etc.
this is my codes
public World world;
public Body bplayer;
public Box2DDebugRenderer b2dr;
public Matrix4 cameraBox2D;
PlayScreen
buttonimage.addListener(new ClickListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button)
{
bplayer.setLinearVelocity(-5*PPM , 0);
return true;
}
});
world = new World(new Vector2(player.getPosition().x , player.getPosition().y) , false);
b2dr = new Box2DDebugRenderer();
bplayer = createPlayer(player.getPosition().x , player.getPosition().y);
show method
buttonimage.setPosition(160,0);
rightbuttonimage.setPosition(320,0);
pauseimage.setPosition(220,-20);
cameraBox2D = camera.combined.cpy();
Render method
Gdx.gl.glClearColor(0, 0, 2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
sb.setProjectionMatrix(camera.combined);
player.position.y += 500 * Gdx.graphics.getDeltaTime();
sb.begin();
sb.draw(bg, 0, camera.position.y - (camera.viewportHeight/2));
sb.draw(player.sprite, player.getPosition().x , player.getPosition().y);
for (Tube tube : tubes) {
sb.draw(tube.getlefttube(), tube.getposlefttube().x, tube.getposlefttube().y);
sb.draw(tube.getrighttube(), tube.getposrighttube().x, tube.getposrighttube().y);
sb.draw(tube.getLight() , tube.getPoslight().x , tube.getPoslight().y);
}
delta*=speed;
sb.end();
update(delta);
b2dr.render(world , cameraBox2D);
stage.draw();
app.batch.begin();
app.font23.draw(app.batch,"Lights collected :" + dropsGathered , 0, 720);
app.batch.end();
cameraUpdate method
Vector3 position = camera.position;
position.x = player.position.x;
position.y = player.position.y;
camera.position.set(position);
createPlayer method
Body pBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(x * PPM, y * PPM );
def.fixedRotation = true;
pBody = world.createBody(def);
return pBody;
update method
world.step(1 / 60f , 6 , 2);
for(int i = 0; i < tubes.size; i++) {
Tube tube = tubes.get(i);
if (camera.position.y - (camera.viewportWidth/2) > tube.getposlefttube().y + tube.getlefttube().getWidth()) {
tube.reposition(tube.getposlefttube().y + ( TUBE_COUNT) );
}
if (tube.collides(player.getBounds())){
app.setScreen(new GameOver(app));
}
if (tube.gathered(player.getBounds())){
dropsGathered++;
}
if (dropsGathered >= 50){
//app.setScreen(new Stage2(app));
}
}
camera.update();
handleInput();
camera.position.y = player.getPosition().y + 300;
player.update(delta);
camera.update();
cameraUpdate(delta);
stage.act(delta);
Do not use the Sprite class. Use the TextureRegion class instead. Sprite is confusingly subclassed from TextureRegion, so when you call batch.draw(sprite, ...) its position and rotation parameters are ignored because it is being treated as a TextureRegion.
You could use a Sprite by calling sprite.draw(batch) but a Sprite is redundant because your Body already has position and rotation parameters.
Use a TextureRegion directly with the SpriteBatch. You can orient it with rotation parameters passed into the draw method.
Evening Everyone,
I am attempting to get familiar with libdgx and android by going thru the tutorial Here. All seems good except for grabbing the screen coordinates as they get skewed in a Vector3 conversion.
So x input of 101 gets converted to -796, y input of 968 converted to -429 (touching the upper left corner of the screen, same results from emulator as from my phone). When clicking the bottom right corner, the animation fires in the middle of the screen.
It all seems pretty basic so not really sure what I am setting incorrectly to get a skewed conversion. Any help is appreciated!
camera creation:
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(camera.viewportWidth * .5f, camera.viewportHeight * .5f, 0f);
Grabbing touch coord:
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
touchCoordinateX = screenX;
touchCoordinateY = screenY;
stateTime = 0;
explosionHappening = true;
return true;
}
Render loop:
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
batch.begin();
if (!explosionAnimation.isAnimationFinished(stateTime) && explosionHappening) {
Vector3 touchPoint = new Vector3();
touchPoint.set(touchCoordinateX,touchCoordinateY,0);
TextureRegion currentFrame = explosionAnimation.getKeyFrame(stateTime, false); // #16
camera.unproject(touchPoint);
batch.draw(currentFrame, touchPoint.x, touchPoint.y);
}
// batch.draw(img, 0, 0);
batch.end();
if (explosionAnimation.isAnimationFinished(stateTime)){explosionHappening = false;}
}
I think you forgot to set camera projection matrix to your SpriteBatch. Just add
batch.setProjectionMatrix(camera.combined);
before
batch.begin();
OK for sake of argument and simplicity this code here has a rectangle sprite/texture that shoots(cuz it's a gun) upwards. And an enemy rectangle/sprite/texture the spawns downwards. Then the player detects if it hits a enemy. When the player hits an enemy I get an out of bounds exception -1
package com.TheGame.Pack;
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
public class GameScreen implements Screen {
final MasterClass game;
Texture FleetTexture;
Texture PlayerTexture;
Texture ShootingTexture;
OrthographicCamera camera;
Rectangle Player;
Array<Rectangle> Emma;
Array<Rectangle> Shooting;
long EmmaSpawnTime;
long ShootingTime;
public static int EmmaKilled = 0;
public GameScreen(final MasterClass gam) {
this.game = gam;
// load the images for the droplet and the Player, 64x64 pixels each
FleetTexture = new Texture(Gdx.files.internal("cirA.png")); //Enemies
PlayerTexture = new Texture(Gdx.files.internal("BoxA.png"));
ShootingTexture = new Texture(Gdx.files.internal("gun.png"));
// load the drop sound effect and the rain background "music"
// dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
// rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
// rainMusic.setLooping(true);
// create the camera and the SpriteBatch
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
// create a Rectangle to logically represent the Player
Player = new Rectangle();
Player.x = 800 / 2 - 64 / 2; // center the Player horizontally
Player.y = 20; // bottom left corner of the Player is 20 pixels above
// the bottom screen edge
Player.width = 40;
Player.height = 30;
// create the Emma array and spawn the first EmmaInArray
Emma = new Array<Rectangle>();
Shooting = new Array<Rectangle>();
spawnEmma();
}
private void spawnEmma() {
Rectangle EmmaInArray = new Rectangle();
EmmaInArray.x = MathUtils.random(0, 800 - 64);
EmmaInArray.y = 480;
EmmaInArray.width = 40;
EmmaInArray.height = 30;
Emma.add(EmmaInArray);
EmmaSpawnTime = TimeUtils.nanoTime();
}
private void spawnShooting(){
Rectangle ShootingInArray = new Rectangle();
ShootingInArray.x = Player.x;
ShootingInArray.y = Player.y;
ShootingInArray.width = 40;
ShootingInArray.height = 30;
Shooting.add(ShootingInArray);
ShootingTime = TimeUtils.nanoTime();
}
#Override
public void render(float delta) {
// clear the screen with a dark blue color. The
// arguments to glClearColor are the red, green
// blue and alpha component in the range [0,1]
// of the color to be used to clear the screen.
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// tell the camera to update its matrices.
camera.update();
// tell the SpriteBatch to render in the
// coordinate system specified by the camera.
game.batch.setProjectionMatrix(camera.combined);
// begin a new batch and draw the Player and
// all drops
game.batch.begin();
game.font.draw(game.batch, "Drops Collected: " + EmmaKilled, 0, 480);
game.batch.draw(PlayerTexture, Player.x, Player.y, Gdx.graphics.getWidth() / 20,
Gdx.graphics.getHeight()/ 20);
for (Rectangle EmmaInArray : Emma) {
game.batch.draw(FleetTexture, EmmaInArray.x, EmmaInArray.y);
}
for(Rectangle ShootingInArray : Shooting){
game.batch.draw(ShootingTexture, ShootingInArray.x, ShootingInArray.y);
ShootingInArray.y +=10;
}
game.batch.end();
// process user input
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
Player.x = touchPos.x - 64 / 2;
}
if (Gdx.input.isKeyPressed(Keys.LEFT))
Player.x -= 400 * Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Keys.RIGHT))
Player.x += 400 * Gdx.graphics.getDeltaTime();
// make sure the Player stays within the screen bounds
if (Player.x < 0)
Player.x = 0;
if (Player.x > 800 - 64)
Player.x = 800 - 64;
// check if we need to create a new EmmaInArray
if (TimeUtils.nanoTime() - EmmaSpawnTime > 100000000){
spawnEmma();
}
if(TimeUtils.nanoTime() - ShootingTime > 100000000){
spawnShooting();
}
// move the Emma, remove any that are beneath the bottom edge of
// the screen or that hit the Player. In the later case we play back
// a sound effect as well.
Iterator<Rectangle> EmmaIterator = Emma.iterator();
while (EmmaIterator.hasNext()) {
Rectangle EmmaInArray = EmmaIterator.next();
EmmaInArray.y -= 200 * Gdx.graphics.getDeltaTime();
if (EmmaInArray.y + 64 < 0){
EmmaIterator.remove();
}
Iterator<Rectangle> ShootingIterator = Shooting.iterator();
while(ShootingIterator.hasNext()){
Rectangle ShootingInArray = ShootingIterator.next();
// ShootingInArray.y += 200 * Gdx.graphics.getDeltaTime();
if(ShootingInArray.y > 480){
ShootingIterator.remove();
}
if(EmmaInArray.overlaps(ShootingInArray)){
ShootingIterator.remove();
EmmaIterator.remove();
}
if (Player.overlaps(EmmaInArray)) {
EmmaKilled++;
game.setScreen(game.HS);
// dropSound.play();
if I comment out EmmaIterator.remove(); it runs fine with it uncommented it crashes upon hit.
Why does this crash is this not the proper way to do this? Do I need to somehow detect hit's at the same time? How can the array be at negative 1 when clearly there are still enemies on the screen?
EmmaIterator.remove();
}
}
Though this is not the way I will have things setup this code still should run with no issues. I encounter the same problem when instead of detecting the player enemies collisions I have 2 guns checking for collisions. This seems like a big problem to me which is why I'd say I'm just doing it wrong but documentation is light so I come here.
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
// start the playback of the background music
// when the screen is shown
//rainMusic.play();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
FleetTexture.dispose();
PlayerTexture.dispose();
ShootingTexture.dispose();
// dropSound.dispose();
// rainMusic.dispose();
}
}
It's unlikely, unless multithreading is being used, that anything will happen at the same time exactly. You have a number of probable typos in your code, but one will break it:
Rectangle var1_holder = iter.next();
That same reference to iter is in both the first block, which should use it, and the second block, which should use iter1. You should consider using matching variable names, like
Iterator<Rectangle> iter3 = var3.iterator();
if you must have numbers as the only distinguishing feature.
notostraca is right. But to make it more clear i will show u an example with for loops which i use for collisions. it can't make any harm and i hope it will make it more clear for u
int v2 = var2.size();
for (int i = 0; i < v2; i++) {
if (object.getBounds().overlaps(var2.get(i).getBounds())) {
var2.remove(i);
v2--;
//in this line u might use break; if u know that just one object
//from var2 array can hit at a time
}
}
UPDATE Looks like this is a problem because of the static notification bar on tablet because of the lack of hardware buttons. I just didn't think about that. Anyway, in the case of the TF101 it returns a resolution of 1280x752 so about 1.702 (80 : 47) ratio. If I use a suitable unit size, like 33.5 or 11.75 vertically I get the proper scaling and this seems to fix the problem of skewed pixels.
END UPDATE
I've been setting up a game using 16x16 units for my tiled maps. I am using the resolution 1280x800 on both my desktop and android projects, I'm testing this to get a sense of how it will look on my TF101 asus tablet. I currently use a camera with units of 20x12.5 (wxh) and notice no pixel scaling on my desktop project, but when I run the game on my android I get weird scaling, and a green horizontal line. I can also move about quarter cell further along the x-axis on the tablet, shown in the screen shots. The pixels on the android project don't seem uniform at all.
I set the verticalTiles amount to 12.5f, then calculate the horizontalTiles amount as
verticalTiles = 12.5f;
...
horizontalTiles = (float) width / (float) height * verticalTiles;
camera = new OrthographicCamera(horizontalTiles, verticalTiles);
I'm aiming for devices with different aspect ratios to simply see more or less of the map, but can't seem to get working correctly. Any help would be appreciated.
Android Capture - http://imageshack.us/f/7/dsvg.png/ - notice the highlights on the roof edges, they are not uniform at all.
Desktop Capture - http://imageshack.us/f/853/5itv.png/
Current MainGame class
package com.bitknight.bqex;
/* Bunch of imports */
public class MainGame implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch spriteBatch;
private TiledMap map;
private OrthogonalTiledMapRenderer mapRenderer;
private Texture texture;
private Texture clothArmor;
private Sprite sprite;
private BitmapFont font;
private float horizontalTiles = 0;
private float verticalTiles = 12.5f;
private int hoverTileX = 0;
private int hoverTileY = 0;
private TiledMapTileLayer layer;
private Cell cell;
private TiledMapTile canMoveToTile;
private TiledMapTile cannotMoveToTile;
private AnimatedTiledMapTile animatedStopTile;
private AnimatedTiledMapTile animatedGoTile;
private Texture spriteSheet;
private TextureRegion region;
private Player player;
float h, w;
float ppuX, ppuY;
#Override
public void create() {
// Setup the animated tiles
Array<StaticTiledMapTile> tileArray;
// Start position on the sheet
int startX = 192;
int startY = 1568;
spriteSheet = new Texture(Gdx.files.internal("data/maps/tilesheet.png"));
spriteSheet.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
// We are trying to load two strips of 4 frames, 8 total
for( int i = 0; i < 2; ++i ) {
tileArray = new Array<StaticTiledMapTile>(4);
for( int j = 0; j < 4; ++j ) {
region = new TextureRegion(spriteSheet, startX, startY, 16, 16);
tileArray.add(new StaticTiledMapTile(region));
startX += 16;
}
if( i == 0 ) {
animatedStopTile = new AnimatedTiledMapTile(1/10f, tileArray);
} else {
animatedGoTile = new AnimatedTiledMapTile(1/10f, tileArray);
}
}
// Load the map
map = new TmxMapLoader().load("data/maps/base.tmx");
// Setup the two tiles that show movable and not movable sprites
canMoveToTile = map.getTileSets().getTileSet(0).getTile(1959);
canMoveToTile.setBlendMode(BlendMode.ALPHA);
cannotMoveToTile = map.getTileSets().getTileSet(0).getTile(1958);
cannotMoveToTile.setBlendMode(BlendMode.ALPHA);
// Manually create the layer used to show the cursor sprites
layer = new TiledMapTileLayer(100, 100, 16, 16);
layer.setName("display");
cell = new Cell();
cell.setTile(canMoveToTile);
layer.setOpacity(1f);
mapRenderer = new OrthogonalTiledMapRenderer(map, 1/16f);
spriteBatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/consolas.fnt"), false);
font.setScale(0.6f);
texture = new Texture(Gdx.files.internal("data/maps/tilesheet.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
clothArmor = new Texture(Gdx.files.internal("data/img/native/clotharmor.png"));
region = new TextureRegion(clothArmor, 32, 256, 32, 32);
sprite = new Sprite(region);
sprite.setOrigin(0.5f, 0.5f);
sprite.setPosition(0f - 0.5f, 0f);
sprite.setSize(2, 2);
// Setup player and associated animations
Array<TextureRegion> regions = new Array<TextureRegion>();
player = new Player();
}
#Override
public void dispose() {
spriteBatch.dispose();
texture.dispose();
clothArmor.dispose();
spriteSheet.dispose();
}
#Override
public void render() {
player.update(Gdx.graphics.getDeltaTime());
camera.update();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if( Gdx.input.isKeyPressed(Input.Keys.ESCAPE) ) {
Gdx.app.exit();
}
// Clear the last cell
layer.setCell(hoverTileX, hoverTileY, null);
// Convert screen coordinates to world coordinates
Vector3 worldCoordinates = new Vector3(Gdx.input.getX(0), Gdx.input.getY(0), 0);
camera.unproject(worldCoordinates);
hoverTileX = (int)(worldCoordinates.x);
hoverTileY = (int)(worldCoordinates.y);
TiledMapTileLayer layer = (TiledMapTileLayer)map.getLayers().get("collision");
if( Gdx.input.isTouched(0) ) {
//sprite.setPosition(hoverTileX - 0.5f, hoverTileY);
player.pos.x = hoverTileX - 0.5f;
player.pos.y = hoverTileY - 0.25f;
cell.setTile(animatedGoTile);
} else {
if (layer.getCell(hoverTileX, hoverTileY) != null) {
cell.setTile(cannotMoveToTile);
} else {
cell.setTile(canMoveToTile);
}
}
layer.setCell(hoverTileX, hoverTileY, cell);
mapRenderer.setView(camera);
mapRenderer.render();
mapRenderer.getSpriteBatch().begin();
mapRenderer.renderTileLayer(layer);
mapRenderer.getSpriteBatch().end();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
player.render(spriteBatch);
spriteBatch.end();
}
#Override
public void resize(int width, int height) {
horizontalTiles = (float) width / (float) height * verticalTiles;
camera = new OrthographicCamera(horizontalTiles, verticalTiles);
w = width;
h = height;
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Looks like this is a problem because of the static notification bar on tablet because of the lack of hardware buttons. I just didn't think about that. Anyway, in the case of the TF101 it returns a resolution of 1280x752 so about 1.702 (80 : 47) ratio. If I use a suitable unit size, like 33.5 or 11.75 vertically I get the proper scaling and this seems to fix the problem of skewed pixels.
Also, while this is good for the TF101 tablet in my case it's not really a great solution. Here is a Gemserk series that talks about a nice solution.
http://blog.gemserk.com/2013/01/22/our-solution-to-handle-multiple-screen-sizes-in-android-part-one/
I'm new to game development andengine. I want to add ParallaxBackground but I don't know how to change background on player move. I'm using arrow for moving a player. Now my question is where I write the code parallaxBackground.setParallaxValue(5); I was written this line in onAreaTouched method of arrow but it not work. please help me. Thanks.
Code
private Camera mCamera;
private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;
private BitmapTextureAtlas bgTexture;
private ITextureRegion bgTextureRegion;
#Override
protected void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
bgTexture = new BitmapTextureAtlas(getTextureManager(),2160,480,TextureOptions.REPEATING_BILINEAR);
bgTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTexture, this, "background.png", 0, 0);
bgTexture.load();
}
#Override
protected Scene onCreateScene() {
this.getEngine().registerUpdateHandler(new FPSLogger());
Scene scene = new Scene();
scene.setBackground(new Background(Color.BLACK));
final ParallaxBackground parallaxBackground = new ParallaxBackground(0, 0, 0);
final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
parallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.bgTextureRegion.getHeight(), this.bgTextureRegion, vertexBufferObjectManager)));
scene.setBackground(parallaxBackground);
Robot robot = new Robot();
// add Player
final AnimatedSprite animatedRobotSprite = new AnimatedSprite(robot.centerX, robot.centerY, 122, 126, (ITiledTextureRegion) robotTextureRegion, getVertexBufferObjectManager());
scene.attachChild(animatedRobotSprite);
animatedRobotSprite.animate(new long[]{1250,50,50});
// add right arrow button
Sprite rightArrowSprite = new Sprite(0, CAMERA_HEIGHT-70, rightArrowTextureRegion, getVertexBufferObjectManager()){
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) {
switch (pSceneTouchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
moveRight = true;
parallaxBackground.setParallaxValue(5);
break;
case TouchEvent.ACTION_MOVE:
moveRight = true;
break;
case TouchEvent.ACTION_UP:
moveRight = false;
break;
default:
break;
}
return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
}
};
scene.attachChild(rightArrowSprite);
scene.registerTouchArea(rightArrowSprite);
scene.setTouchAreaBindingOnActionDownEnabled(true);
scene.setTouchAreaBindingOnActionMoveEnabled(true);
scene.registerUpdateHandler(new IUpdateHandler() {
#Override
public void reset() {
}
#Override
public void onUpdate(float pSecondsElapsed) {
if ( moveRight ){
animatedRobotSprite.setPosition(animatedRobotSprite.getX()+speedX, animatedRobotSprite.getY());
}
}
});
return scene;
}
I see at least on possible problem: You have only one ParallaxEntity attached. The visual effect of parallax is created by multiple entities moving at different speeds.
But I think what you are seeing is that your background is not scrolling. If you do not use the AutoParallaxBackground class, you have to update the paralax amount on each update.
Inside the autoparallax class, this is what it does onUpdate():
#Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed;
}
Looking at this you can see that the setParallaxValue() is an absolute number, so to make it continually scroll, you will need to feed it a new number on each update. For example, in you main game update loop, you could feed in your player.getX() into parallaxBackground.setParallaxValue() like so:
parallaxBackground.setParallaxValue(rightArrowSprite.getX());
While this may not be the exact effect you want, you should now see the background moving when your character moves.
There are different modifiers foe updating your entity(AnimatedSprite) you can use them for movement like
final Entity playerEntity = ...;//Get player entity here.
final float jumpDuration = 2;
final float x= playerEntity.getX();
final MoveXModifiermoveModifier = new MoveXModifier(jumpDuration / 2, x+ 100, y);
playerEntity.registerEntityModifier(moveModifier );
It's not necessary to have two background moving at different speeds. With one fixed background and one "moving" background you will notice the effect when the player moves. However, I've tried setting an absolute value in
parallaxBackground.setParallaxValue(10f);
And the effect was not continuous. What it worked for me was a recipe found in Android Cookbook which is based on overriding the onUpdate of the background to change only when the camera has moved.
ParallaxBackground background = new ParallaxBackground(0.3f, 0.3f,0.9f) {
/* We'll use these values to calculate the parallax value of the background*/
float cameraPreviousX = 0;
float parallaxValueOffset = 0;
/* onUpdates to the background, we need to calculate new
* parallax values in order to apply movement to the background
* objects (the hills in this case) */
#Override
public void onUpdate(float pSecondsElapsed) {
/* Obtain the camera's current center X value */
final float cameraCurrentX = mCamera.getCenterX();
/* If the camera's position has changed since last update... */
if (cameraPreviousX != cameraCurrentX) {
/* Calculate the new parallax value offset by subtracting the previous update's camera x coordinate from the current update's camera x coordinate */
parallaxValueOffset += cameraCurrentX - cameraPreviousX;
/* Apply the parallax value offset to the background, which will in-turn offset the positions of entities attached to the background */
this.setParallaxValue(parallaxValueOffset);
/* Update the previous camera X since we're finished with this update */
cameraPreviousX = cameraCurrentX;
}
super.onUpdate(pSecondsElapsed);
}
};
background.attachParallaxEntity(new ParallaxEntity(5, hillFurthest));
Note than depending on the camera configuration, the "5" value included in the "attachParallaxEntity" may need to be negative. Otherwise, the background will move in the opposite direction of the player.