Move background on button click andengine - andengine

I am new in android game development,I have two buttons on screen , one for forward and one for reverse, also one player sprite.I want to move large background on buttons click.
I have idea about auto-parallax background,but how can i move background on buttons click?
please help
I am doing some thing like this, but it is not smooth and also i think this is not a good approach
public class MainActivity extends SimpleBaseGameActivity implements IOnSceneTouchListener {
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
BitmapTextureAtlas ForwardAtlas,backgroundAtlas,backAtlas,mFontTexture;
ITextureRegion ForwardAtlasRegion,backgroundAtlasRegion,backAtlasRegion;
Sprite ForwardSprite,backgroundSprite,backSprite;
AnimatedSprite player;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mPlayerTextureRegion;
SequenceEntityModifier modifier;
AutoParallaxBackground autoParallaxBackground;
boolean flag=true;
Scene scene;
private Font mFont;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,new FillResolutionPolicy(),camera);
return eo;
}
#Override
protected void onCreateResources() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR);
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4);
this.mBitmapTextureAtlas.load(this.getTextureManager());
ForwardAtlas = new BitmapTextureAtlas(60,60);
ForwardAtlas.load(getTextureManager());
ForwardAtlasRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(ForwardAtlas, getApplicationContext(), "forward.png",0,0);
backAtlas = new BitmapTextureAtlas(60,60);
backAtlas.load(getTextureManager());
backAtlasRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(backAtlas, getApplicationContext(), "Back.png",0,0);
backgroundAtlas = new BitmapTextureAtlas(1000,480);
backgroundAtlas.load(getTextureManager());
backgroundAtlasRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(backgroundAtlas, getApplicationContext(), "background-2.png",0,0);
this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.BLACK);
this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
this.getFontManager().loadFont(this.mFont);
}
#Override
protected Scene onCreateScene() {
// TODO Auto-generated method stub
this.mEngine.registerUpdateHandler(new FPSLogger());
scene = new Scene();
final int playerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getWidth()) / 2;
final int playerY = CAMERA_HEIGHT - this.mPlayerTextureRegion.getHeight() - 5;
//final Text x = new Text(100, 60, this.mFont,Integer.toString(playerX) , HorizontalAlign.CENTER);
//final Text y = new Text(120, 90, this.mFont,Integer.toString(playerY) , HorizontalAlign.CENTER);
player = new AnimatedSprite(playerX, playerY, this.mPlayerTextureRegion);
player.setScaleCenterY(this.mPlayerTextureRegion.getHeight());
player.setScale(2);
player.animate(new long[]{200, 200, 200}, 6, 8, true);
ForwardSprite = new Sprite(390,250, ForwardAtlasRegion);
backSprite = new Sprite(40,250, backAtlasRegion);
backgroundSprite = new Sprite(0,0,backgroundAtlasRegion);
autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.backgroundAtlasRegion.getHeight(), this.backgroundAtlasRegion)));
scene.setBackground(autoParallaxBackground);
scene.attachChild(player);
scene.attachChild(ForwardSprite);
scene.registerTouchArea(ForwardSprite);
scene.attachChild(backSprite);
scene.registerTouchArea(backSprite);
scene.setOnAreaTouchListener(new IOnAreaTouchListener() {
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
ITouchArea pTouchArea, float pTouchAreaLocalX,
float pTouchAreaLocalY)
{
if(pSceneTouchEvent.isActionUp())
{
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - backgroundAtlasRegion.getHeight(), backgroundAtlasRegion)));
if(pTouchArea == ForwardSprite)
if(pTouchArea == backSprite)
return true;
}
if(pSceneTouchEvent.isActionMove()) {
if(pTouchArea == ForwardSprite)
{
player.animate(new long[]{200, 200, 200}, 3, 5, true);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - backgroundAtlasRegion.getHeight(), backgroundAtlasRegion)));
//backgroundSprite.setPosition(backgroundSprite.getX()-5, backgroundSprite.getY());
}
if(pTouchArea == backSprite)
{
player.animate(new long[]{200, 200, 200}, 9, 11, true);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(10.0f, new Sprite(0, CAMERA_HEIGHT - backgroundAtlasRegion.getHeight(), backgroundAtlasRegion)));
//backgroundSprite.setPosition(backgroundSprite.getX()+5, backgroundSprite.getY());
}
return true;
}
return false;
}
});
//scene.setOnSceneTouchListener(this);
return scene;
}

I've just answered similiar question. Please take a look at stop and start auto parallaxbackground in andengine
There isn't such function provided in andengine so you will need extend or add some features in AutoParallaxBacground class of AndEngine library.
package org.andengine.entity.scene.background;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* #author Nicolas Gramlich
* #since 19:44:31 - 19.07.2010
*/
public class AutoParallaxBackground extends ParallaxBackground {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mParallaxChangePerSecond;
private boolean movingForward;
private boolean movingBackward;
// ===========================================================
// Constructors
// ===========================================================
public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) {
super(pRed, pGreen, pBlue);
this.mParallaxChangePerSecond = pParallaxChangePerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setParallaxChangePerSecond(final float pParallaxChangePerSecond) {
this.mParallaxChangePerSecond = pParallaxChangePerSecond;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
if(movingForward)
this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed;
else if (moving Backward)
this.mParallaxValue -= this.mParallaxChangePerSecond * pSecondsElapsed;
}
// ===========================================================
// Methods
// ===========================================================
public void startForward(){
this.movingBackward = false;
this.movingForward = true;
}
public void startBackward(){
this.movingForward = false;
this.movingBackward = true;
}
public void stop(){
this.movingBackward = false;
this.movingForward = false;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
I haven't tested that solution but it should work as expected. The only thing I am not sure right now is changing incrementation to decrementation enough.

Related

Start Android Wear Watchface from Activity

I am wondering if it's possible to start the Watchface Service from an activity?
I tried to start the service in the onCreate method of my activity but it does not show the Watchface:
Intent serviceIntent = new Intent(this, CustomWatchFaceService);
startService(serviceIntent);
update
Here is the code for the WatchfaceService
public class CustomWatchFaceService extends CanvasWatchFaceService {
private static final String TAG = "DigitalWatchFaceService";
private static final Typeface BOLD_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
private static final Typeface NORMAL_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
private static final long NORMAL_UPDATE_RATE_MS = 500;
private static final long MUTE_UPDATE_RATE_MS = TimeUnit.MINUTES.toMillis(1);
#Override
public Engine onCreateEngine() {
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine {
static final String COLON_STRING = ":";
static final int MUTE_ALPHA = 100;
static final int NORMAL_ALPHA = 255;
static final int MSG_UPDATE_TIME = 0;
long mInteractiveUpdateRateMs = NORMAL_UPDATE_RATE_MS;
final Handler mUpdateTimeHandler = new Handler() {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_UPDATE_TIME:
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "updating time");
}
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs =
mInteractiveUpdateRateMs - (timeMs % mInteractiveUpdateRateMs);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
break;
}
}
};
Paint mBackgroundPaint;
Bitmap mBackgroundBitmap;
Bitmap wifiIconOn;
Bitmap wifiIconOff;
Paint mDatePaint;
Paint mNotificationPaint;
Paint mNotificationMax;
Paint mNotificationHigh;
Paint mHourPaint;
Paint mMinutePaint;
Paint mSecondPaint;
Paint mAmPmPaint;
Paint mColonPaint;
float mColonWidth;
boolean mMute;
Calendar mCalendar;
Date mDate;
SimpleDateFormat mDayOfWeekFormat;
java.text.DateFormat mDateFormat;
boolean mShouldDrawColons;
float mXOffset;
float mYOffset;
float mLineHeight;
int mInteractiveBackgroundColor =
R.color.interactive_bg;
int mInteractiveNotificationMax =
R.color.notification_max;
int mInteractiveNotificationHigh =
R.color.notification_high;
int mInteractiveNotificationColor =
R.color.notification;
int mInteractiveHourDigitsColor =
R.color.interactive_time;
int mInteractiveMinuteDigitsColor =
R.color.interactive_time;
int mInteractiveSecondDigitsColor =
R.color.interactive_time;
boolean mLowBitAmbient;
#Override
public void onCreate(SurfaceHolder holder) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onCreate");
}
super.onCreate(holder);
Locale locale = new Locale("de");
Locale.setDefault(locale);
Configuration config = getResources().getConfiguration();
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
setWatchFaceStyle(new WatchFaceStyle.Builder(CustomWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
Resources resources = CustomWatchFaceService.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mLineHeight = resources.getDimension(R.dimen.digital_line_height);
setInteractiveColors();
// Not sure why the text color needs to be set here again ... it should be set in setDefaultColors()!
mDatePaint.setColor(getColor(R.color.digital_date));
mNotificationPaint.setColor(getColor(R.color.notification));
mNotificationMax.setColor(getColor(R.color.notification_max));
mNotificationHigh.setColor(getColor(R.color.notification_high));
mHourPaint.setColor(getColor(R.color.interactive_time));
mMinutePaint.setColor(getColor(R.color.interactive_time));
mSecondPaint.setColor(getColor(R.color.interactive_time));
mColonPaint.setColor(getColor(R.color.interactive_time));
//Images should be loaded here so they can be called during the Draw Method
wifiIconOn = BitmapFactory.decodeResource(CustomWatchFaceService.this.getResources(), R.drawable.wifi_on_small);
wifiIconOff = BitmapFactory.decodeResource(CustomWatchFaceService.this.getResources(), R.drawable.wifi_off_small);
mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.customcart_logo_240_alpha);
mCalendar = Calendar.getInstance();
mDate = new Date();
initFormats();
}
public void setInteractiveColors() {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(mInteractiveBackgroundColor));
mNotificationPaint = createTextPaint(mInteractiveNotificationColor);
mNotificationMax = createTextPaint(mInteractiveNotificationMax);
mNotificationHigh = createTextPaint(mInteractiveNotificationHigh);
mDatePaint = createTextPaint(R.color.digital_date);
mHourPaint = createTextPaint(mInteractiveHourDigitsColor, BOLD_TYPEFACE);
mMinutePaint = createTextPaint(mInteractiveMinuteDigitsColor);
mSecondPaint = createTextPaint(mInteractiveSecondDigitsColor);
mColonPaint = createTextPaint(R.color.digital_colons);
}
#Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
private Paint createTextPaint(int defaultInteractiveColor) {
return createTextPaint(defaultInteractiveColor, NORMAL_TYPEFACE);
}
private Paint createTextPaint(int defaultInteractiveColor, Typeface typeface) {
Paint paint = new Paint();
paint.setColor(defaultInteractiveColor);
paint.setTypeface(typeface);
paint.setAntiAlias(true);
return paint;
}
#Override
public void onVisibilityChanged(boolean visible) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onVisibilityChanged: " + visible);
}
super.onVisibilityChanged(visible);
updateTimer();
}
private void initFormats() {
mDayOfWeekFormat = new SimpleDateFormat("EEEE", Locale.getDefault());
mDayOfWeekFormat.setCalendar(mCalendar);
mDateFormat = DateFormat.getDateFormat(CustomWatchFaceService.this);
mDateFormat.setCalendar(mCalendar);
}
#Override
public void onApplyWindowInsets(WindowInsets insets) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onApplyWindowInsets: " + (insets.isRound() ? "round" : "square"));
}
super.onApplyWindowInsets(insets);
// Load resources that have alternate values for round watches.
Resources resources = CustomWatchFaceService.this.getResources();
boolean isRound = insets.isRound();
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
float textSize = resources.getDimension(isRound
? R.dimen.digital_text_size_round : R.dimen.digital_text_size);
float notificationTextSize = resources.getDimension(isRound
? R.dimen.notification_text_size : R.dimen.notification_text_size);
mDatePaint.setTextSize(resources.getDimension(R.dimen.digital_date_text_size));
mHourPaint.setTextSize(textSize);
mMinutePaint.setTextSize(textSize);
mSecondPaint.setTextSize(textSize);
mColonPaint.setTextSize(textSize);
mNotificationPaint.setTextSize(notificationTextSize);
mColonWidth = mColonPaint.measureText(COLON_STRING);
}
#Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
boolean burnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false);
mHourPaint.setTypeface(burnInProtection ? NORMAL_TYPEFACE : BOLD_TYPEFACE);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onPropertiesChanged: burn-in protection = " + burnInProtection
+ ", low-bit ambient = " + mLowBitAmbient);
}
}
#Override
public void onTimeTick() {
super.onTimeTick();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onTimeTick: ambient = " + isInAmbientMode());
}
invalidate();
}
#Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (!isInAmbientMode()) {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(R.color.interactive_bg));
mDatePaint.setColor(getColor(R.color.digital_date));
mHourPaint.setColor(getColor(R.color.interactive_time));
mMinutePaint.setColor(getColor(R.color.interactive_time));
mSecondPaint.setColor(getColor(R.color.interactive_time));
mColonPaint.setColor(getColor(R.color.interactive_time));
}
else {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(R.color.ambient_bg));
mDatePaint.setColor(getColor(R.color.digital_date));
mHourPaint.setColor(getColor(R.color.ambient_time));
mMinutePaint.setColor(getColor(R.color.ambient_time));
mSecondPaint.setColor(getColor(R.color.ambient_time));
mColonPaint.setColor(getColor(R.color.ambient_time));
}
//Log.d("XXX", "onAmbientModeChanged: " + inAmbientMode);
if (mLowBitAmbient) {
boolean antiAlias = !inAmbientMode;
mDatePaint.setAntiAlias(antiAlias);
mHourPaint.setAntiAlias(antiAlias);
mMinutePaint.setAntiAlias(antiAlias);
mSecondPaint.setAntiAlias(antiAlias);
mAmPmPaint.setAntiAlias(antiAlias);
mColonPaint.setAntiAlias(antiAlias);
}
invalidate();
// Whether the timer should be running depends on whether we're in ambient mode (as well
// as whether we're visible), so we may need to start or stop the timer.
updateTimer();
}
#Override
public void onInterruptionFilterChanged(int interruptionFilter) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onInterruptionFilterChanged: " + interruptionFilter);
}
super.onInterruptionFilterChanged(interruptionFilter);
boolean inMuteMode = interruptionFilter == WatchFaceService.INTERRUPTION_FILTER_NONE;
// We only need to update once a minute in mute mode.
setInteractiveUpdateRateMs(inMuteMode ? MUTE_UPDATE_RATE_MS : NORMAL_UPDATE_RATE_MS);
if (mMute != inMuteMode) {
mMute = inMuteMode;
int alpha = inMuteMode ? MUTE_ALPHA : NORMAL_ALPHA;
mDatePaint.setAlpha(alpha);
mHourPaint.setAlpha(alpha);
mMinutePaint.setAlpha(alpha);
mColonPaint.setAlpha(alpha);
mAmPmPaint.setAlpha(alpha);
invalidate();
}
}
public void setInteractiveUpdateRateMs(long updateRateMs) {
if (updateRateMs == mInteractiveUpdateRateMs) {
return;
}
mInteractiveUpdateRateMs = updateRateMs;
// Stop and restart the timer so the new update rate takes effect immediately.
if (shouldTimerBeRunning()) {
updateTimer();
}
}
private String formatTwoDigitNumber(int hour) {
return String.format("%02d", hour);
}
#Override
public void onDraw(Canvas canvas, Rect bounds) {
long now = System.currentTimeMillis();
int width = bounds.width();
int height = bounds.height();
mCalendar.setTimeInMillis(now);
mDate.setTime(now);
boolean is24Hour = DateFormat.is24HourFormat(CustomWatchFaceService.this);
// Draw the background.
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint);
//Draw the background Image
if (mBackgroundBitmap == null
|| mBackgroundBitmap.getWidth() != width
|| mBackgroundBitmap.getHeight() != height) {
mBackgroundBitmap = Bitmap.createScaledBitmap(mBackgroundBitmap,
width, height, true /* filter */);
}
//Log.d("XXX", "Width: "+ mBackgroundBitmap.getWidth() + "Height: "+mBackgroundBitmap.getHeight() );
if (isInAmbientMode() && (mLowBitAmbient)) {
canvas.drawColor(Color.BLACK);
} else if (isInAmbientMode()) {
canvas.drawColor(Color.BLACK);
} else {
canvas.drawBitmap(mBackgroundBitmap, 0, 0, mBackgroundPaint);
}
// Show colons for the first half of each second so the colons blink on when the time updates.
mShouldDrawColons = (System.currentTimeMillis() % 1000) < 500;
// Draw the hours.
float x = mXOffset;
String hourString;
if (is24Hour) {
hourString = formatTwoDigitNumber(mCalendar.get(Calendar.HOUR_OF_DAY));
} else {
int hour = mCalendar.get(Calendar.HOUR);
if (hour == 0) {
hour = 12;
}
hourString = String.valueOf(hour);
}
canvas.drawText(hourString, x, mYOffset, mHourPaint);
x += mHourPaint.measureText(hourString);
// In ambient and mute modes, always draw the first colon. Otherwise, draw the
// first colon for the first half of each second.
if (isInAmbientMode() || mMute || mShouldDrawColons) {
canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint);
}
x += mColonWidth;
// Draw the minutes.
String minuteString = formatTwoDigitNumber(mCalendar.get(Calendar.MINUTE));
canvas.drawText(minuteString, x, mYOffset, mMinutePaint);
x += mMinutePaint.measureText(minuteString);
// In unmuted interactive mode, draw a second blinking colon followed by the seconds.
// Otherwise, if we're in 12-hour mode, draw AM/PM
if (!isInAmbientMode() && !mMute) {
if (mShouldDrawColons) {
canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint);
}
x += mColonWidth;
canvas.drawText(formatTwoDigitNumber(
mCalendar.get(Calendar.SECOND)), x, mYOffset, mSecondPaint);
} else if (!is24Hour) {
x += mColonWidth;
}
// Only render the day of week and date if there is no peek card, so they do not bleed
// into each other in ambient mode.
if (getPeekCardPosition().isEmpty()) {
// Day of week
canvas.drawText(
mDayOfWeekFormat.format(mDate),
mXOffset, mYOffset + mLineHeight, mDatePaint);
// Date
canvas.drawText(
mDateFormat.format(mDate),
mXOffset, mYOffset + mLineHeight * 2, mDatePaint);
}
}
/**
* Starts the {#link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "updateTimer");
}
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {#link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
}
}

AndEngine : Showing All sprites images same

enter image description hereI have 4 sprites. I am placing all 4 sprites in different place on the mobile screen. But it is taking the last added sprite image that is (sprite4.png) all the sprites images(sprite1.png, sprite2.png, sprite3.png and sprite4.png).
In short its displaying all the sprite images same.
The code is given below, please share your experience
// the below code is running without error but displaying same images in all the sprites
package com.example.test1;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
/*;
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* #author Nicolas Gramlich
* #since 15:13:46 - 15.06.2010
*/
public class Puzzle extends GameActivity {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
final Scene scene = new Scene();
// ===========================================================
// Fields
// ===========================================================
private BitmapTextureAtlas mBitmapTextureAtlas;
private ITextureRegion spriteTextureRegion1;
private ITextureRegion spriteTextureRegion2;
private ITextureRegion spriteTextureRegion3;
private ITextureRegion spriteTextureRegion4;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public EngineOptions onCreateEngineOptions() {
// Toast.makeText(this, "Touch & Drag the face!", Toast.LENGTH_LONG).show();
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}
#Override
public void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 96, 96, TextureOptions.BILINEAR);
this.spriteTextureRegion1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite1.png", 0, 0);
this.spriteTextureRegion2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite2.png", 0, 0);
this.spriteTextureRegion3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite3.png", 0, 0);
this.spriteTextureRegion4= BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite4.png", 0, 0);
// scene.attachChild(sprite1);
this.mBitmapTextureAtlas.load();
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));
/* set sprite1 positions on screen */
final float sprite1_posX = (40);
final float sprite1_posY = (40);
final Sprite sprite1 = new Sprite(sprite1_posX, sprite1_posY, this.spriteTextureRegion1, this.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
return true;
}
};
//sprite1.setScale(3);
scene.attachChild(sprite1);
scene.registerTouchArea(sprite1);
scene.setTouchAreaBindingOnActionDownEnabled(true);
/* set sprite2 positions on screen */
final Sprite sprite2 = new Sprite(sprite1_posX, sprite1_posY + (sprite1.getHeight()*3 + 10), this.spriteTextureRegion2, this.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
return true;
}
};
//sprite2.setScale(3);
scene.attachChild(sprite2);
scene.registerTouchArea(sprite2);
scene.setTouchAreaBindingOnActionDownEnabled(true);
/* set sprite3 positions on screen */
final Sprite sprite3 = new Sprite(sprite1_posX, sprite1_posY + (sprite1.getHeight() + 20), this.spriteTextureRegion3, this.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
return true;
}
};
// sprite3.setScale(3);
scene.attachChild(sprite3);
scene.registerTouchArea(sprite3);
scene.setTouchAreaBindingOnActionDownEnabled(true);
/* set sprite3 positions on screen */
final Sprite sprite4 = new Sprite(sprite1_posX, sprite1_posY + (sprite1.getHeight() + 30), this.spriteTextureRegion4, this.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
return true;
}
};
// sprite4.setScale(3);
scene.attachChild(sprite4);
scene.registerTouchArea(sprite4);
scene.setTouchAreaBindingOnActionDownEnabled(true);
return scene;
}
}
Oh sorry I know what is the problem:
this.spriteTextureRegion1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite1.png", 0, 0);
this.spriteTextureRegion2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite2.png", 0, 0);
this.spriteTextureRegion3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite3.png", 0, 0);
this.spriteTextureRegion4= BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite4.png", 0, 0);
At the end, where you put 0, 0 - you declare where your region should be located on the Texture atlas. Imagine stickers you put on the sheet of paper. You put one, then on this you put another, and third and fourth. This way you can see only the one that is on top. So you have to put your regions in different places of the texture atlas. If all your images are 40x40 it should look like this (also your atlas might be bigger (512x512):
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 512, 512, TextureOptions.BILINEAR);
this.spriteTextureRegion1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite1.png", 0, 0);
this.spriteTextureRegion2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite2.png", 50, 0);
this.spriteTextureRegion3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite3.png", 0, 50);
this.spriteTextureRegion4= BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "sprite4.png", 50, 50);

What is wrong with this ANDEngine HUD?

I am trying to make a HUD at AndEngine, but when I write this code below and run the emulator, only thing appears on Emulator is a black screen with crashed HUD image.
This is what I want to display,
and This is how my code show.
This is my code -
package com.example.andenginetester;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
public class SpriteTester extends SimpleBaseGameActivity {
public static final int CAMERA_WIDTH = 720;
public static final int CAMERA_HEIGHT = 480;
private HUD myHUD;
private Sprite myHUDSprite;
private BitmapTextureAtlas myAtlas;
private TextureRegion myHUDImage;
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
#Override
public EngineOptions onCreateEngineOptions() {
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}
#Override
protected void onCreateResources() {
myAtlas = new BitmapTextureAtlas(this.getTextureManager(), 1024, 1024);
myHUDImage = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.myAtlas, this, "gfx/HUD.png", 0, 0);
mEngine.getTextureManager().loadTexture(myAtlas);
}
#Override
protected Scene onCreateScene() {
final Scene scene = new Scene();
scene.setBackground(new Background(0, 0, 0));
myHUDSprite = new Sprite(0, 0, myHUDImage, this.getVertexBufferObjectManager());
myHUD.attachChild(myHUDSprite);
camera.setHUD(myHUD);
return scene;
}
}
How I should fix it?
Well, I managed to get the correct result , let me know if it works for you:
a) I updated the AndroidManifest.xml
Added in the <activity ... >:
1) android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"
2) android:screenOrientation="landscape"
b) The updated activity:
public class MainActivity extends SimpleBaseGameActivity {
public static final int CAMERA_WIDTH = 720;
public static final int CAMERA_HEIGHT = 480;
private HUD myHUD = new HUD();
private Sprite myHUDSprite;
private BitmapTextureAtlas myAtlas;
private TextureRegion myHUDImage;
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
#Override
public EngineOptions onCreateEngineOptions() {
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}
#Override
protected void onCreateResources() {
myAtlas = new BitmapTextureAtlas(this.getTextureManager(), 1024, 1024);
myHUDImage = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
this.myAtlas, this, "gfx/HUD.png", 0, 0);
mEngine.getTextureManager().loadTexture(myAtlas);
}
#Override
protected Scene onCreateScene() {
final Scene scene = new Scene();
scene.setBackground(new Background(0, 0, 0));
myHUDSprite = new Sprite(0, 0, myHUDImage,
this.getVertexBufferObjectManager());
myHUD.attachChild(myHUDSprite);
myHUD.setPosition(CAMERA_WIDTH/2,CAMERA_HEIGHT/2);
camera.setHUD(myHUD);
return scene;
}
}

Move a ball with the accelerometer andengine

I had written a code to move a ball with the help of accelerometer andengine, but i get force close.
My problem is the use of PhysicsWorld.
My library is:
andengine.jar
andenginephysicsbox2dextension.jar
my code is:
public class SnakeGameActivity extends BaseGameActivity implements IAccelerometerListener
{
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
private float mGravityX;
private float mGravityY;
private Sprite splash ;
private final Vector2 mTempVector = new Vector2();
protected PhysicsWorld mPhysicsWorld;
private Camera mCamera;
private Texture mTexture;
private TextureRegion mSplashTextureRegion;
#Override
public Engine onLoadEngine() {
// TODO Auto-generated method stub
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
#Override
public void onLoadResources() {
// TODO Auto-generated method stub
this.mTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.enableAccelerometerSensor(this);
this.mSplashTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "ball_enemy.png", 0, 0);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mEngine.getTextureManager().loadTexture(this.mTexture);
}
#Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
Scene scene = new Scene(1);
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
final int centerX = (CAMERA_WIDTH - this.mSplashTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mSplashTextureRegion.getHeight()) / 2;
splash = new Sprite(centerX, centerY, this.mSplashTextureRegion);
scene.getLastChild().attachChild(splash);
scene.registerUpdateHandler(this.mPhysicsWorld);
return scene;
}
#Override
public void onLoadComplete() {
// TODO Auto-generated method stub
}
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY());
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
}
my log error:
02-25 21:08:22.334: E/ActivityManager(69): Start proc com.android.deskclock for
broadcast com.android.deskclock/.AlarmInitReceiver: pid=255 uid=10019 gids={}
CPU usage from 16953ms to 19171ms later:
Thank you very much for your help

add visual below finger swipe, Triangle strip like fruit ninja Andengine

I want to show a triangle strip when user swap finger on screen. I am not sure how to do it with AndEngine, using particle system or using sprites or using Triangle Strip algo...
I haven't wrote any code because I am struck that what to do. I am uploading an image please share your ideas.
Update
someone has done this in Iphone but unfortunately I am unfamiliar with language syntax please help me in understanding algo of this code https://github.com/hiepnd/CCBlade
**Effect I want **
Complete Android Project Download
http://www.andengine.org/forums/resources/complete-runnable-project/1301
I have done this code but could not get the desired effect...
package org.az.algo.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.RectangleParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AlphaInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.GravityInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ColorModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Toast;
public class ParticleSystemSimpleExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mParticleTextureRegion;
private BitmapTextureAtlas mBitmapTextureAtlasStreak;
private TextureRegion mStreadTextureRegion;
private Sprite[] mSprite = new Sprite[20];
private int mIndex = 0;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
#Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/particle_point.png", 0, 0);
this.mBitmapTextureAtlasStreak = new BitmapTextureAtlas(128, 16, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mStreadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasStreak, this, "gfx/streak1.png", 0, 0);
this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mBitmapTextureAtlasStreak);
}
#Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
// final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80);
final RectangleParticleEmitter particleEmitter = new RectangleParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f, 5f,5f);
// final PointParticleEmitter particleEmitter = new PointParticleEmitter(10, 10);
final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 100, 100, 1000, this.mParticleTextureRegion);
particleSystem.setParticlesSpawnEnabled(false);
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_MOVE){
particleSystem.setParticlesSpawnEnabled(true);
particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
mSprite[getIndex()].setPosition(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
mSprite[getIndex()].setVisible(true);
}else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP){
particleSystem.setParticlesSpawnEnabled(false);
hideAll();
}else if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
particleSystem.reset();
}
return true;
}
});
particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0));
particleSystem.addParticleInitializer(new AlphaInitializer(0));
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
// particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10));
particleSystem.addParticleInitializer(new GravityInitializer());
// particleSystem.addParticleModifier(new ScaleModifier(0.5f, 1.0f, 0, 1.5f));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6));
particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 0.5f));
particleSystem.addParticleModifier(new AlphaModifier(1, 0, 2.5f, 3.5f));
particleSystem.addParticleModifier(new ExpireModifier(6, 6f));
scene.attachChild(particleSystem);
for(int i = 0; i < mSprite.length; i++){
mSprite[i] = new Sprite(-20, 0, mStreadTextureRegion);
mSprite[i].setVisible(false);
scene.attachChild(mSprite[i]);
}
return scene;
}
#Override
public void onLoadComplete() {
}
private int getIndex(){
if(mIndex >= mSprite.length -1){
mIndex = 0;
}
System.out.println("Index ........ "+mIndex);
return mIndex++;
}
private void hideAll(){
for(int i = 0; i<mSprite.length; i++){
mSprite[i].setVisible(false);
mSprite[i].setPosition(-CAMERA_WIDTH, 0);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
image I used with this code is also attached
Updated
partial effect achieved.. but problem on fast swiping.. all complete projects are uploaded here http://www.andengine.org/forums/post31772.html#p31772
Here is a solution in LibGDX. It uses GL_TRIANGLE_STRIP.
https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Finger-Swipe
The final solution uses two triangle strips and a custom texCoord attribute, allowing for us to use a lookup texture to achieve fake (but efficient) anti-aliasing. A more efficient/flexible anti-aliasing would use shaders and a single triangle strip. Use vertex attribute -1.0 for the top and 1.0 for the bottom edge of your swipe, and 1.0 for the tips. Then in the frag shader, use abs() -- so 0.0 means "center" and 1.0 means "edge."
Something like this:
color.a *= smoothstep(0.0, 2./thickness, 1.0-abs(vTexCoord.t));