Creating Pause Screen Menu inside play screen in LibGdx? - java

Inside my gameplay screen I want to create a Pause Screen Menu which I can select the Retry button or Back to main screen if I click the pause button.I already draw the pause button inside my class.My problem is how can I draw the pause menu screen?
Here is my code
//pause
pause = new Texture("pause.png");
myTextureRegion = new TextureRegion(pause);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
pause_btnDialog = new ImageButton(myTexRegionDrawable); //Set the button up
pause_btnDialog.setPosition(580,1150);
stage.addActor(pause_btnDialog); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Pause Button Pressed");
//Show Pause Screen menu
//game.setScreen(new PauseGameday1(game));
}
});
stage.addActor(pause_btnDialog);
GameScreen
public class IngamedayOne implements Screen ,InputProcessor {
final MyGdxGame game;
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
private boolean peripheralAvailable;
private static final float ACCELERATION = 20f;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture cat ,left_paw,right_paw,progressbar_background,progressbar_knob,pause,meter;
Texture carpet,desk,plants,square_carpet,shoes;
SpriteBatch spriteBatch;
Sprite sprite;
private Texture Background;
ImageButton left_paw_btn,right_paw_btn,pause_btnDialog;
Viewport viewport;
private Stage stage;
// A variable for tracking elapsed time for the animation
float stateTime;
private TextureRegion myTextureRegion;
private TextureRegionDrawable myTexRegionDrawable;
private boolean isPause;
private Group pauseGroup;
//Screen Size
OrthographicCamera camera;
float catSpeed = 50.0f; // 10 pixels per second.
float catX;
float catY;
public boolean paused = false;
public IngamedayOne(final MyGdxGame game) {
this.game = game;
Gdx.input.setCatchBackKey(true);
Gdx.graphics.setContinuousRendering(false);
Gdx.graphics.requestRendering();
stage = new Stage(new StretchViewport( 720, 1280));
camera = new OrthographicCamera();
camera.setToOrtho(false, 720, 1280);
camera.translate( 1280/2, 720/2 );
Gdx.input.setInputProcessor(stage);
spriteBatch = new SpriteBatch();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Load the sprite sheet as a texture
cat = new Texture(Gdx.files.internal("cat.png"));
sprite = new Sprite(cat);
catX=300;
catY=0;
Gdx.input.setInputProcessor( this);
peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
int orientation = Gdx.input.getRotation();
Input.Orientation nativeOrientation = Gdx.input.getNativeOrientation();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Progressbar
progressbar_background = new Texture("progression_map.png");
progressbar_knob = new Texture("cat_head.png");
//pause
pause = new Texture("pause.png");
myTextureRegion = new TextureRegion(pause);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
pause_btnDialog = new ImageButton(myTexRegionDrawable); //Set the button up
pause_btnDialog.setPosition(580,1150);
stage.addActor(pause_btnDialog); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Pause Button Pressed");
//Show Pause Screen menu
game.setScreen(new PauseGameday1(game));
pause();
}
});
stage.addActor(pause_btnDialog);
meter = new Texture("meter.png");
//background
Background = new Texture(Gdx.files.internal("floor.png")); //File from assets folder
// Use the split utility method to create a 2D array of TextureRegions. This is
// possible because this sprite sheet contains frames of equal size and they are
// all aligned.
TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() / FRAME_COLS, cat.getHeight()/ FRAME_ROWS);
// Place the regions into a 1D array in the correct order, starting from the top
// left, going across first. The Animation constructor requires a 1D array.
TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
walkFrames[index++] = tmp[i][j];
}
}
// Initialize the Animation with the frame interval and array of frames
walkAnimation = new Animation<TextureRegion>(0.200f, walkFrames);
// Instantiate a SpriteBatch for drawing and reset the elapsed animation
// time to 0
spriteBatch = new SpriteBatch();
stateTime = 0f;
//left_control
left_paw = new Texture(Gdx.files.internal("left_paw.png"));
myTextureRegion = new TextureRegion(left_paw);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
left_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
left_paw_btn.setPosition(10,25);
stage.addActor(left_paw_btn); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
left_paw_btn.addListener(new InputListener(){
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Left Button Pressed");
//Start Animation
}
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
stage.addActor(left_paw_btn);
//right_control
right_paw = new Texture(Gdx.files.internal("right_paw.png"));
myTextureRegion = new TextureRegion(right_paw);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
right_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
right_paw_btn.setPosition(517,25);
stage.addActor(right_paw_btn); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
right_paw_btn.addListener(new InputListener(){
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Right Button Pressed");
//Start Animation
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
camera.update();
}
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
stage.addActor(right_paw_btn);
}
public enum State
{
PAUSE,
RUN,
RESUME,
STOPPED
}
private State state = State.RUN;
#Override
public void show() {
}
#Override
public void render(float delta) {
// clear previous frame
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
camera.update();
spriteBatch.begin();
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(currentFrame,catX,catY); // Draw current frame at (50, 50)
spriteBatch.draw(meter,190,990);
spriteBatch.draw(progressbar_background,20,1170);
spriteBatch.draw(progressbar_knob,18,1170);
//Moving player on desktop
if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
catX -= Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
catX += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.UP))
catY += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.DOWN))
catY -= Gdx.graphics.getDeltaTime() * catSpeed;
//Mobile acceleration
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
catX -= Gdx.input.getAccelerometerX();
catY += Gdx.input.getAccelerometerY();
}
if(catY<0) {
catY =0;
}
if(catY> Gdx.graphics.getWidth()-100) {
catY =Gdx.graphics.getWidth()-100;
}
if(catX<0){
catX =0;
}
if(catX> Gdx.graphics.getHeight()-250) {
catX =Gdx.graphics.getHeight()-250;
}
switch (state)
{
case RUN:
//do suff here
break;
case PAUSE:
break;
case RESUME:
break;
default:
break;
}
spriteBatch.end();
stage.act(); //acting a stage to calculate positions of actors etc
stage.draw(); //drawing it to render all
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
#Override
public void pause() {
this.state = State.PAUSE;
}
#Override
public void resume() {
this.state = State.RESUME;
}
#Override
public boolean keyDown(int keycode) {
return true;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
#Override
public void hide() {
}
#Override
public void dispose() { // SpriteBatches and Textures must always be disposed
spriteBatch.dispose();
cat.dispose();
left_paw.dispose();
right_paw.dispose();
stage.dispose();
Background.dispose();
progressbar_background.dispose();
progressbar_knob.dispose();
}
}
Pause Menu
public class PauseGameday1 implements Screen {
final MyGdxGame game;
private Texture Background,pauseImg;
private Stage stage;
SpriteBatch spriteBatch;
OrthographicCamera camera;
private static final int WIDTH= 720;
private static final int HEIGHT= 1280;
private TextureRegion myTextureRegion;
private TextureRegionDrawable myTexRegionDrawable;
Viewport viewport;
public PauseGameday1( MyGdxGame game) {
this.game = game;
stage = new Stage(new StretchViewport( 720, 1280));
camera = new OrthographicCamera();
camera.setToOrtho(false, 720, 1280);
camera.translate( 1280/2, 720/2 );
Gdx.input.setInputProcessor(stage);
spriteBatch = new SpriteBatch();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Background = new Texture(Gdx.files.internal("backgroundimage.png")); //background image
pauseImg = new Texture(Gdx.files.internal("pausemenu/pause_text.png"));
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
camera.update();
spriteBatch.begin();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(pauseImg,230,900);
stage.act(Gdx.graphics.getDeltaTime()); //Perform ui logic
spriteBatch.end();
stage.getViewport().apply();
stage.draw(); //Draw the ui
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
Can anyone correct my codes?

You only declared pauseGroup but never used in your game, Call pause() method from pause_button. It will create pauseGroup for you and add to your Stage. In pause() method, create Actor(UI) and add to pauseGroup. You can't use multiple screen at a time with your Game class because Game having reference of single Screen.
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
pause();
}
});
#Override
public void render(float delta) {
// clear previous frame
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
camera.update();
spriteBatch.begin();
spriteBatch.setProjectionMatrix(camera.combined);
if(this.state==State.RESUME)
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(currentFrame,catX,catY); // Draw current frame at (50, 50)
spriteBatch.draw(meter,190,990);
spriteBatch.draw(progressbar_background,20,1170);
spriteBatch.draw(progressbar_knob,18,1170);
if(this.state==State.RESUME){
//Moving player on desktop
if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
catX -= Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
catX += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.UP))
catY += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.DOWN))
catY -= Gdx.graphics.getDeltaTime() * catSpeed;
//Mobile acceleration
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
catX -= Gdx.input.getAccelerometerX();
catY += Gdx.input.getAccelerometerY();
}
if(catY<0) {
catY =0;
}
if(catY> Gdx.graphics.getWidth()-100) {
catY =Gdx.graphics.getWidth()-100;
}
if(catX<0){
catX =0;
}
if(catX> Gdx.graphics.getHeight()-250) {
catX =Gdx.graphics.getHeight()-250;
}
}
switch (state)
{
case RUN:
//do suff here
break;
case PAUSE:
break;
case RESUME:
break;
default:
break;
}
spriteBatch.end();
stage.act(); //acting a stage to calculate positions of actors etc
stage.draw(); //drawing it to render all
}
public void pause(){
this.state = State.PAUSE;
pauseGroup = new Group;
Image semiTransparentBG= ......
// setSize(Size of screen) and make it semi transparent.
pauseGroup.addActor(semiTransparentBG);
//crate all other pause UI buttons with listener and add to pauseGroup
stage.addActor(pauseGroup);
}
public void resume() {
if(this.state = State.PAUSE){
this.state = State.RESUME;
pauseGroup.remove();
}
}

Related

Temporary Sprite in Android App

I have an android game where there are sprites moving about the screen. When one is hit, it adds or takes away from the score and then disappears.
What I would like it to do is create a blood splatter when it is hit which will also disappear.
I have actually achieved this but the blood splatter doesn't appear where the sprite was hit. It always goes to the bottom right-hand corner. I was wondering if there is anyone out there that can see where my problem is.
I have a TempSprite class just for the blood splatter and this is below:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
All the other code is in the GameView class, specifically in the doDraw and GameView methods:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private final Bitmap bmpBlood;
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
private BadSprite badSprite;
// For recording the number of hits
private int hitCount;
// For displaying the highest score
private int highScore;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPool mySound;
private int zapSoundId;
private int screamSoundId;
// For multiple sprites
private ArrayList<Sprite> spritesArrayList;
private ArrayList<BadSprite> badSpriteArrayList;
// For the temp blood image
private List<TempSprite> temps = new ArrayList<TempSprite>();
//int backButtonCount = 0;
private void createSprites() {
// Initialise sprite object
spritesArrayList = new ArrayList<>();
badSpriteArrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
spritesArrayList.add(new Sprite(this));
badSpriteArrayList.add(new BadSprite(this));
}
}
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.castle);
// Populate multiple sprites
//createSprites();
//Vibrator vibe = (Vibrator) sprite.getSystemService(Context.VIBRATOR_SERVICE);
//vibe.vibrate(500);
// For the temp blood splatter
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
//Sound effects for the sprite touch
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
screamSoundId = mySound.load(context, R.raw.scream, 1);
zapSoundId = mySound.load(context, R.raw.zap, 1);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
#SuppressWarnings("ResourceAsColor")
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
//paint.setColor(R.color.red);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 35, 85, paint);
// Draw the blood splatter
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
// Draw all the objects on the canvas
for (int i = 0; i < spritesArrayList.size(); i++) {
Sprite sprite = spritesArrayList.get(i);
sprite.draw(canvas);
}
for (int i = 0; i < badSpriteArrayList.size(); i++) {
BadSprite badSprite = badSpriteArrayList.get(i);
badSprite.draw(canvas);
}
} else {
canvas.drawText("Game Over!", 35, 50, paint);
canvas.drawText("Your score was: " + hitCount, 35, 80, paint);
canvas.drawText("To go back home,", 280, 50, paint);
canvas.drawText("press the 'back' key", 280, 70, paint);
}
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
for (int i = spritesArrayList.size()-1; i>=0; i--) {
Sprite sprite = spritesArrayList.get(i);
if (sprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(zapSoundId, 1.0f, 1.0f, 0,0, 1.5f);
spritesArrayList.remove(sprite);
//temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount--;
return super.onTouchEvent(event);
}
for (int i1 = badSpriteArrayList.size()-1; i1>=0; i1--) {
BadSprite badSprite = badSpriteArrayList.get(i1);
if (badSprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(screamSoundId, 1.0f, 1.0f, 0, 0, 1.5f);
badSpriteArrayList.remove(badSprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount++;
return super.onTouchEvent(event);
}
}
}
//else {
return true;
// }
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public int getHitCount() {
return hitCount;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
As always, any help greatly appreciated.
Thanks
This was solved with the following code:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
/*this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());*/
this.x = x;
this.y = y;
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
You can see where the commented out sections are and below are what they were replaced with. I was trying to make things a little too complicated.

libgdx world to screen pos and factors

I want to draw a texture on a body, which is a box.
How do I convert the coordinates of the body to screen coordinates?
I know that the other way around is with camera.unproject(pos), is it similar to this?
I see a lot of people using constants such as WORLD_TO_SCREEN = 32, but I currently don't have that in my game. Is that a problem, and how can I implement it now? Because it seems like people that are using these factors can convert world to screen positions easily. I currently have a camera and an ExtendViewport
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
viewport = new ExtendViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, camera);
camera.position.set(VIEWPORT_WIDTH/2, VIEWPORT_HEIGHT/2, 0f);
Viewport width and height are set to this
public static final int VIEWPORT_WIDTH = 20;
public static final int VIEWPORT_HEIGHT = 22;
I don't really know what I'm doing, I read documentation and read some tutorials, but if someone could give some explanation about these variables and the world_to_screen factor that would really help me out.
I also set APP_WIDTH=1280, APP_HEIGHT = 720
Do viewport width and height mean that for box2d my screen is 20 meters wide and 22 meters high?
(asking it again because I added a lot the question and I would really like to know these things)
[EDIT]
So I'm trying to draw a ground picture on the ground body
float x = stage.getGround().getX();
float y = stage.getGround().getY();
float w = stage.getGround().getWidth();
float h = stage.getGround().getHeight();
stage.act(delta);
stage.draw();
stage.updateCamera();
Texture texture = new Texture(Gdx.files.internal("ground.png"));
Sprite sprite = new Sprite(texture);
sprite.setSize(w, h);
sprite.setPosition(x-sprite.getWidth()/2, y-sprite.getHeight()/2);
But I don't see it anywhere
[EDIT 2]
Stage Class
public class Mission1Stage extends Stage{
public static final int VIEWPORT_WIDTH = 20;
public static final int VIEWPORT_HEIGHT = 22;
private World world;
private Ground ground;
private LeftWall leftWall;
private Rocket rocket;
private static final float TIME_STEP = 1 / 300f;
private float accumulator = 0f;
private OrthographicCamera camera;
private Box2DDebugRenderer renderer;
private Viewport viewport;
private SpriteBatch spriteBatch = new SpriteBatch();
private Vector3 touchPoint;
private ShapeRenderer shapeRenderer;
private Button boostButton;
private Skin boostSkin;
private Button boostLeftButton;
private Skin boostLeftSkin;
private Button boostRightButton;
private Skin boostRightSkin;
private Button resetButton;
private Skin resetSkin;
private Game game;
private boolean isTouched = false;
public Mission1Stage(Game game) {
setUpWorld();
renderer = new Box2DDebugRenderer();
shapeRenderer = new ShapeRenderer();
setupCamera();
setUpButtons();
addActor(new Background(ground));
}
private void setUpWorld() {
world = WorldUtils.createWorld();
setUpGround();
setUpRocket();
}
private void setUpGround() {
ground = new Ground(WorldUtils.createGround(world));
addActor(ground);
}
private void setUpLeftWall() {
leftWall = new LeftWall(WorldUtils.createLeftWall(world));
}
private void setUpRocket() {
rocket = new Rocket(WorldUtils.createRocket(world));
addActor(rocket);
}
private void setupCamera() {
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
viewport = new ExtendViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, camera);
camera.position.set(VIEWPORT_WIDTH/2, VIEWPORT_HEIGHT/2, 0f);
camera.update();
}
private void setUpButtons() {
boostSkin = new Skin(Gdx.files.internal("skin/flat-earth-ui.json"));
boostButton = new Button(boostSkin);
boostButton.setSize(80,80);
boostButton.setPosition(Gdx.graphics.getWidth()-boostButton.getWidth()*2,0);
boostButton.setTransform(true);
boostButton.scaleBy(0.5f);
Gdx.input.setInputProcessor(this);
addActor(boostButton);
boostLeftSkin = new Skin(Gdx.files.internal("skin/flat-earth-ui.json"));
boostLeftButton = new Button(boostLeftSkin);
boostLeftButton.setSize(100, 100);
boostLeftButton.setPosition(0, 0);
addActor(boostLeftButton);
boostRightSkin = new Skin(Gdx.files.internal("skin/flat-earth-ui.json"));
boostRightButton = new Button(boostRightSkin);
boostRightButton.setSize(100, 100);
boostRightButton.setPosition(boostLeftButton.getWidth(), 0);
addActor(boostRightButton);
resetSkin = new Skin(Gdx.files.internal("skin/flat-earth-ui.json"));
resetButton = new Button(resetSkin);
resetButton.setSize(100, 100);
resetButton.setPosition(Gdx.graphics.getWidth()-100, Gdx.graphics.getHeight()-100);
addActor(resetButton);
}
#Override
public void act(float delta) {
super.act(delta);
handleInput();
accumulator += delta;
while(accumulator >= delta) {
world.step(TIME_STEP, 6, 2);
accumulator -= TIME_STEP;
}
}
#Override
public void draw() {
super.draw();
renderer.render(world, camera.combined);
float x = getGround().getBody().getPosition().x;
float y = getGround().getBody().getPosition().y;
float w = getGround().getWidth() * 2;
float h = getGround().getHeight() * 2;
spriteBatch.setProjectionMatrix(getCamera().combined);
Texture texture = new Texture(Gdx.files.internal("ground.png"));
Sprite sprite = new Sprite(texture);
sprite.setSize(w, h);
sprite.setPosition(x-sprite.getWidth()/2, y-sprite.getHeight()/2);
spriteBatch.begin();
sprite.draw(spriteBatch);
spriteBatch.end();
}
public void handleInput() {
if(boostButton.isPressed()) {
rocket.boost();
}
if(boostLeftButton.isPressed()) {
rocket.turnLeft();
}
if(boostRightButton.isPressed()) {
rocket.turnRight();
}
if(resetButton.isPressed()) {
}
}
public boolean resetScreen() {
if(resetButton.isPressed()) return true;
return false;
}
public void updateCamera() {
}
public Ground getGround() {
return ground;
}
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.x = VIEWPORT_WIDTH / 2;
camera.position.y = VIEWPORT_HEIGHT /2;
}
private void translateScreenToWorldCoordinates(int x, int y) {
getCamera().unproject(touchPoint.set(x, y, 0));getCamera();
}
}
Screen class
public class Mission1Screen implements Screen{
private Game game;
private Mission1Stage stage;
private SpriteBatch spriteBatch = new SpriteBatch();
private Skin boostSkin;
private Button boostButton;
public Mission1Screen(Game game) {
this.game = game;
stage = new Mission1Stage(game);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(stage.resetScreen()) {
game.setScreen(new Mission1Screen(game));
}
stage.act(delta);
stage.draw();
stage.updateCamera();
}
#Override
public void resize(int width, int height) {
stage.resize(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
[EDIT 3]
public class Main extends Game {
#Override
public void create () {
this.setScreen(new Mission1Screen(this));
}
#Override
public void render () {
super.render();
}
#Override
public void dispose () {
}
}
We mostly use Pixel to meter conversion because box2d best works in meters (0-10) but you can avoid this conversion by using small worldwidth and height of your viewport. I mostly prefer 48 and 80 as viewport width and height.
You can use unproject(vector3) method of camera that translate a point given in screen coordinates to world space. I am using this method in touchdown because I get screen coordinate as parameter then I need to convert it into camera world space so that I can generate object at a particular position in world.
public class MyGdxTest extends Game implements InputProcessor {
private SpriteBatch batch;
private ExtendViewport extendViewport;
private OrthographicCamera cam;
private float w=20;
private float h=22;
private World world;
private Box2DDebugRenderer debugRenderer;
private Array<Body> array;
private Vector3 vector3;
#Override
public void create() {
cam=new OrthographicCamera();
extendViewport=new ExtendViewport(w,h,cam);
batch =new SpriteBatch();
Gdx.input.setInputProcessor(this);
world=new World(new Vector2(0,-9.8f),true);
array=new Array<Body>();
debugRenderer=new Box2DDebugRenderer();
vector3=new Vector3();
BodyDef bodyDef=new BodyDef();
bodyDef.type= BodyDef.BodyType.StaticBody;
bodyDef.position.set(0,0);
Body body=world.createBody(bodyDef);
ChainShape chainShape=new ChainShape();
chainShape.createChain(new float[]{1,1,55,1});
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=chainShape;
fixtureDef.restitution=.5f;
body.createFixture(fixtureDef);
chainShape.dispose();
}
#Override
public void render() {
super.render();
Gdx.gl.glClearColor(0,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1/60f,6,2);
batch.setProjectionMatrix(cam.combined);
batch.begin();
world.getBodies(array);
for (Body body:array){
if(body.getUserData()!=null) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition(body.getPosition().x-sprite.getWidth()/2, body.getPosition().y-sprite.getHeight()/2);
sprite.setRotation(body.getAngle()*MathUtils.radDeg);
sprite.draw(batch);
}
}
batch.end();
debugRenderer.render(world,cam.combined);
}
#Override
public void resize(int width, int height) {
super.resize(width,height);
extendViewport.update(width,height);
cam.position.x = w /2;
cam.position.y = h/2;
cam.update();
}
private void createPhysicsObject(float x,float y){
float sizeX=2,sizeY=2;
BodyDef bodyDef=new BodyDef();
bodyDef.position.set(x,y);
bodyDef.type= BodyDef.BodyType.DynamicBody;
Body body=world.createBody(bodyDef);
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(sizeX,sizeY);
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.restitution=.2f;
fixtureDef.density=2;
body.createFixture(fixtureDef);
body.setFixedRotation(false);
polygonShape.dispose();
Sprite sprite=new Sprite(new Texture("badlogic.jpg"));
sprite.setSize(2*sizeX,2*sizeY);
sprite.setPosition(x-sprite.getWidth()/2,y-sprite.getHeight()/2);
sprite.setOrigin(sizeX,sizeY);
body.setUserData(sprite);
}
#Override
public void dispose() {
batch.dispose();
debugRenderer.dispose();
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
vector3.set(screenX,screenY,0);
Vector3 position=cam.unproject(vector3);
createPhysicsObject(vector3.x,vector3.y);
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}

How to make a sprite move with keyboard in java(libgdx)

i'm making a game for school motives, i have already made the sprite and the background(tiled map) my problem is how i can make the sprite move left, right, back and down using the keyboard, please guys help me as soon as possible here is my code:
public class LEVEL1 implements ApplicationListener, Screen {
private Music music;
private SpriteBatch batch;
private Texture Sprite;
private Vector2 position;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
position.y = position.y - 5;
// player Controls
if(position.y < 0){
position.y = 0;
}
//..................................................
// renderer camera and map
camera.update();
renderer.setView(camera);
renderer.render();
//...................................................
//tells the computer when to start drawing textures
batch.begin();
batch.draw(Sprite, position.x, position.y, 50, 50);
batch.end();
//...................................................
camera = new OrthographicCamera();
camera.setToOrtho(true, 2920,950);
}
#Override
public void show() {
Sprite = new Texture("Sprite.png");
batch = new SpriteBatch();
position = new Vector2(650, Gdx.graphics.getHeight());
map = new TmxMapLoader().load("map1.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
music = Gdx.audio.newMusic((Gdx.files.internal("GameSound.mp3")));
music.setLooping(false);
music.setVolume(0.5f);
music.play();
}
#Override
public void create() {
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.position.set(width/2f, height/3f, 0); //by default camera position on (0,0,0)
camera.update();
}
#Override
public void render() {
if(Gdx.input.justTouched())
music.play();
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
music.dispose();
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
}
Here i make a little example of moving a sprite using keys (up,down, left,right)
you should find more details in libgdx wiki
public class Level1 implements ApplicationListener {
Sprite sprite;
SpriteBatch batch;
float spriteXposition;
float spriteYposition;
#Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//tells the computer when to start drawing textures
batch.begin();
sprite.setPosition(spriteXposition, spriteYposition);
sprite.draw(batch);
batch.end();
spriteControl();
}
public void spriteControl() {
if(Gdx.input.isKeyPressed(Keys.UP)) {
spriteYposition++;
}
if(Gdx.input.isKeyPressed(Keys.DOWN)) {
spriteYposition--;
}
if(Gdx.input.isKeyPressed(Keys.LEFT)) {
spriteXposition--;
}
if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
spriteXposition++;
}
}
#Override
public void create() {
sprite = new Sprite(new Texture(Gdx.files.internal("sprite.png")));
batch = new SpriteBatch();
}
}
To react on input events you need to implement InputProcessor. It has the methods keyDown (called when a key is pressed) and keyUp (called when a key is released).
Those methods have an argument keyCode, which defines the int code of the pressed/released key.
So you need to override this 2 methods and depending on the keyCode you get, you should do something or not.
To move the player for example, you might keep a member speed, which you set, depending on the pressed/released key. In the render method you then need to update the position depending on the elapsed time (delta) and the speed.
To get the input event, you need to tell libgdx, that your InputProcessor should be the active one. This is done by calling Gdx.input.setInputProcessor(yourInputProcessor).
Also make sure to read the Libgdx wiki, many of your questions will be answered there.
EDIT:
Some code:
public class Level implements ApplicationListener, InputProcessor {
private int speedX; // Speed in x direction
private Vector2 position; // Position
private boolean keyDown(int keyCode) {
boolean result = false;
if (keyCode == Keys.D) {
result = true;
speed += 5;
}
else if (keyCode == Keys.A) {
result = true;
speed -= 5;
}
return result;
}
private boolean keyUp(int keyCode) {
boolean result = false;
if (keyCode == Keys.D) {
result = true;
speed -= 5;
}
else if (keyCode == Keys.A) {
result = true;
speed += 5;
}
return result;
}
public void render(float delta) {
position.x += speed*delta;
// Render here
}
}

libgdx drag and drop

Im trying to add drag and drop functionality to several images in Libgdx. I have looked at this example: https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/DragAndDropTest.java but Its still not working. The images do not drag and drop. Would anyone be able to give me some pointers in why its not working?
Thanks
private void createButton() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
skin = new Skin();
skin.add("up", new Texture(Gdx.files.internal("assets/data/up.png")));
skin.add("def", new Texture(Gdx.files.internal("assets/data/Goal.png")));
final Image up = new Image(skin, "up");
up.setBounds(1090, 630, 40, 40);
stage.addActor(up);
Image def = new Image(skin, "def");
def.setBounds(1090, 585, 40, 40);
stage.addActor(def);
DragAndDrop dragAndDrop = new DragAndDrop();
dragAndDrop.addSource(new Source(up) {
public Payload dragStart (InputEvent event, float x, float y, int pointer) {
Payload payload = new Payload();
payload.setObject(payload);
payload.setDragActor(up);
payload.setDragActor(new Label("up", skin));
Label validLabel = new Label("up", skin);
validLabel.setColor(0, 1, 0, 1);
payload.setValidDragActor(validLabel);
return payload;
}
});
dragAndDrop.addTarget(new Target(def) {
public boolean drag (Source source, Payload payload, float x, float y, int pointer) {
getActor().setColor(Color.GREEN);
return true;
}
public void reset (Source source, Payload payload) {
getActor().setColor(Color.WHITE);
}
public void drop (Source source, Payload payload, float x, float y, int pointer) {
System.out.println("Accepted: " + payload.getObject() + " " + x + ", " + y);
}
});
render();
}
public void render () {
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
Table.drawDebug(stage);
}
I implemented your code on a project of mine.
I removed your render and used the one below. Also, you shouldn't need the assets/ prefix to your image import.
skin.add("up", new Texture(Gdx.files.internal("images/coin.png")));
skin.add("def", new Texture(Gdx.files.internal("images/coin.png")));
#Override
public void render(float delta) {
super.render(delta);
stage.draw();
stage.act(Gdx.graphics.getDeltaTime());
}
Another way to do drag in a better way...
public class CaveInterection implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture bgTexture;
private Sprite sprite;
private Stage stage;
private Texture mirrTexture;
private MyActor mirrorActor;
Sprite img1,img2;
#Override
public void create() {
camera = new OrthographicCamera(1024, 550);
camera.position.set(1024 / 2, 550 / 2, 0);
batch = new SpriteBatch();
stage = new Stage(1024, 550, false);
//bgTexture = new Texture(Gdx.files.internal("data/cave.jpg"));
//bgTexture = new Texture(Gdx.files.internal("data/bg.jpg"));
mirrTexture = new Texture(Gdx.files.internal("data/mirror.png"));
mirrTexture
.setFilter(TextureFilter.Linear, TextureFilter.Linear);
mirrorActor = new MyActor(new TextureRegion(mirrTexture));
mirrorActor.setPosition(700, 400);
mirrorActor.setOrigin(mirrorActor.getWidth()/2, mirrorActor.getHeight()/2);
stage.addActor(mirrorActor);
// finally stage as the input process
Gdx.input.setInputProcessor(stage);
}
#Override
public void dispose() {
batch.dispose();
//bgTexture.dispose();
}
#Override
public void render() {
// clear the screen, update the camera and make the sprite batch
// use its matrices.
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
//batch.draw(bgTexture, 0,0);
// Gdx.app.log("arvind","X :"+mirrorActor.getX()+ " Y :"+mirrorActor.getY());
//batch.draw(bgTexture, 0, 0);
batch.end();
// tell the stage to act and draw itself
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
public class MyActor extends Actor {
TextureRegion region;
float lastX;
float lastY;
public MyActor (TextureRegion region) {
this.region = region;
setWidth(region.getRegionWidth());
setHeight(region.getRegionHeight());
addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log("arv", "pointer1+"+pointer);
// we only care for the first finger to make things easier
if (pointer != 0) return false;
// record the coordinates the finger went down on. they
// are given relative to the actor's corner (0, 0)
Gdx.app.log("arvind", "touchDown");
Gdx.app.log("arv", "pointer2+"+pointer+""+x+"::::"+y);
lastX = x;
lastY = y;
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
// we only care for the first finger to make things easier
if (pointer != 0) return;
Gdx.app.log("arv", "touchDragged");
// adjust the actor's position by (current mouse position - last mouse position)
// in the actor's coordinate system.
translate(x - lastX, y - lastY);
// rotate(2);
// save the current mouse position as the basis for the next drag event.
// we adjust by the same delta so next time drag is called, lastX/lastY
// are in the actor's local coordinate system automatically.
lastX = x - (x - lastX);
lastY = y - (y - lastY);
}
});
}
#Override
public void draw (SpriteBatch batch, float parentAlpha) {
//batch.draw(region, getX(), getY());
batch.draw(region, getX(), getY(), mirrorActor.getOriginX(), mirrorActor.getOriginY(), mirrorActor.getWidth(), mirrorActor.getHeight(), 1, 1,getRotation(), true);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}

Can't draw a ninepatch image and stage at the same time

Whenever I try to draw a ninepatch image and a stage the last thing that's called is being drawn. I have tried to use a orthographic camera but didn't succeed. What I have tried:
batch.setProjectionMatrix(camera.combined);
ninePatch.draw(batch, xPos, yPos, width, height);
stage.act(delta);
stage.draw();
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage.setCamera(camera)
EDIT: The code
The CreateQuiz class
public class CreateQuiz implements Screen{
public CreateQuiz(Quiz quiz){
this.quiz = quiz;
}
private Quiz quiz;
private FallDownPanel fallDownPanel;
private OrthographicCamera camera;
#Override
public void render(float delta) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
quiz.beginBatch();
fallDownPanel.render(quiz.getSpriteBatch(), delta);
quiz.endBatch();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
fallDownPanel = new FallDownPanel(FallDownPanel.START_LOWER_SIDE, 200, quiz.getTextureAtlas().createPatch("fallDownWindow"));
Stage stage = new Stage(fallDownPanel.getWidth(), fallDownPanel.getHeight(), false);
TextFieldStyle style = quiz.getGreenTextFieldStyle();
style.font.scale(-0.30f);
TextFieldQuiz test = new TextFieldQuiz("Hej åäö 123 !", style, 0, 2, 400, 16);
test.setTextFieldListener(new TextFieldListener() {
#Override
public void keyTyped (TextField textField, char key) {
if (key == '\n') {
textField.getOnscreenKeyboard().show(false);
}
}
});
stage.addActor(test);
Gdx.input.setInputProcessor(stage);
fallDownPanel.setStage(stage);
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage.setCamera(camera);
fallDownPanel.setCamera(camera);
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
The FallDownPanel.class
public class FallDownPanel {
//With repeat
public FallDownPanel(int startSide, int size, NinePatch ninePatch){
Tween.registerAccessor(FallDownPanel.class, new FallDownPanelTween());
Tween.registerAccessor(Widget.class, new WidgetTween());
tweenManager = new TweenManager();
final int screenWidth = Gdx.graphics.getWidth();
final int screenHeight = Gdx.graphics.getHeight();
int target = 0;
int tweenType = 0;
if(startSide == START_LEFT_SIDE){
setSize(size, screenHeight);
xPos = -size;
yPos = 0;
target = 0;
tweenType = FallDownPanelTween.POSITION_X;
}
else if(startSide == START_RIGHT_SIDE){
setSize(size, screenHeight);
xPos = screenWidth;
yPos = 0;
target = screenWidth - size;
tweenType = FallDownPanelTween.POSITION_X;
}
else if(startSide == START_UPPER_SIDE){
setSize(screenWidth, size);
xPos = 0;
yPos = screenHeight + size;
target = screenHeight - size;
tweenType = FallDownPanelTween.POSITION_Y;
}
else if(startSide == START_LOWER_SIDE){
setSize(screenWidth, size);
xPos = 0;
yPos = -size;
target = 0;
tweenType = FallDownPanelTween.POSITION_Y;
}
Tween.to(this, tweenType, 1).target(target).start(tweenManager);
this.tweenType = tweenType;
this.startSide = startSide;
this.ninePatch = ninePatch;
}
private TweenManager tweenManager;
private NinePatch ninePatch;
private Stage stage;
private OrthographicCamera camera;
private float xPos, yPos;
private int width, height;
private int tweenType;
private int startSide;
public static final int START_LEFT_SIDE = 0, START_RIGHT_SIDE = 1, START_UPPER_SIDE = 2, START_LOWER_SIDE = 3;
public void render(SpriteBatch batch, float delta){
tweenManager.update(delta);
batch.setProjectionMatrix(camera.combined);
ninePatch.draw(batch, xPos, yPos, width, height);
stage.act(delta);
stage.draw();
}
public void setX(float x){
this.xPos = x;
}
public void setY(float y){
this.yPos = y;
}
public float getX(){
return xPos;
}
public float getY(){
return yPos;
}
public float getWidth(){
return width;
}
public float getHeight(){
return height;
}
private void setSize(int w, int h){
width = w;
height = h;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
startWidgetTweens();
}
private void startWidgetTweens(){
float size = getShortestSide();
Array<Actor> actors = stage.getActors();
for(int i = 0; i < actors.size; i++){
Widget w = (Widget) actors.get(i);
Tween.to(w, tweenType, 1).target(0).start(tweenManager);
}
}
private float getShortestSide() {
if(startSide == START_LEFT_SIDE){
return width;
}
else if(startSide == START_RIGHT_SIDE){
return width;
}
else if(startSide == START_UPPER_SIDE){
return height;
}
else if(startSide == START_LOWER_SIDE){
return height;
}
return -1;
}
public void setCamera(OrthographicCamera camera) {
this.camera = camera;
}
}
Always make sure you have only one active Renderer at a time. The Renderers are:
Batch
SpriteBatch
ShapeRenderer
Box2DDebugRenderer if i am not wrong
ModelBatch for 3D
I hope i did not forget one.
Make sure you always call end() for the active one, before calling begin() for a new one.
Also remember, that a Stage has its own SpriteBatch and it calls begin() for this SpriteBatch, if you call stage.draw(). So make sure you end() the active Renderer, before stage.draw().
If you need a ShapeRenderer or any other renderer to draw an Actor (maybe cause of debuging), you have to end the stages SpriteBatch, which you get with the draw() method. Make sure you begin() it again at the end of the method.
Hope this is clear enough.

Categories

Resources