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;
}
}
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();
}
}
Background Info
Hey guys i am currently working on a little rpg :) and today i tried to implement some easy light ....
Main Question
When i use Point light in my Project the fps will get slower and slower ... i have got a very good pc, so it cant be my gpu or cpu ... So what did i miss?
Heres an Screenshot
You can see in the left bottom corner the fps : 6.
By the way, i disabled vsync and my gpu is an gtx 960 ... so i dont really know why i have so low fps ...
Player class :
package Mobs;
public class Player {
AnimatedSprite animatedSprite;
SpriteBatch batch;
Light licht = new Light(Color.WHITE,500);
public int state = 0;
public int netState = 1;
float speed = 2f;
public Vector2 position = new Vector2(256,256);
public Vector2 networkPosition = new Vector2(0,0);
public Player(){
}
public void update(){
state = 0;
if(Gdx.input.isKeyPressed(Keys.A)){
position.x -= Gdx.graphics.getDeltaTime() * 100f;
state = 1;
//System.out.println(currentState);
}
if(Gdx.input.isKeyPressed(Keys.D)){
position.x += Gdx.graphics.getDeltaTime() * 100f;
state = 2;
//System.out.println(currentState);
}
if(Gdx.input.isKeyPressed(Keys.W)){
position.y += Gdx.graphics.getDeltaTime() * 100f;
state = 3;
//System.out.println(currentState);
}
if(Gdx.input.isKeyPressed(Keys.S)){
position.y -= Gdx.graphics.getDeltaTime() * 100f;
state = 4;
//System.out.println(currentState);
}
}
public void setX(float x){
position.x = x;
}
public void setY(float y){
position.y = y;
}
public void draw(float f, float g, OrthographicCamera camera){
position.x = f;
position.y = g;
//System.out.println("In beforeSetState : "+currentState);
animatedSprite.setState(state);
//System.out.println("In after : "+currentState);
animatedSprite.createAnimation();
camera.position.set(f,g,0);
camera.update();
licht.drawLight(camera, f+25 , g+25);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(animatedSprite.convertAnimationTOframes(),f,g, Gdx.graphics.getWidth()/25,Gdx.graphics.getHeight()/15);
batch.end();
}
public void doSetup(){
batch = new SpriteBatch();
animatedSprite = new AnimatedSprite();
}
public float getX(){
return position.x;
}
public float getY(){
return position.y;
}
}
And my "Light" class :
package Screen;
public class Light {
World world;
RayHandler rayHandler;
PointLight pointLight;
Body player;
Box2DDebugRenderer debugRenderer;
public Light(Color farbe, int radius) {
world = new World(new Vector2(0,0),false);
rayHandler = new RayHandler(world);
pointLight = new PointLight(rayHandler, 500 , farbe , radius, 0, 0);
pointLight.setSoftnessLength(0f);
debugRenderer = new Box2DDebugRenderer();
}
public void drawLight(OrthographicCamera playerCam, float x, float y){
world.step(1 / 60f, 8, 3);
debugRenderer.render(world, playerCam.combined);
pointLight.setPosition(x,y);
rayHandler.setCombinedMatrix(playerCam.combined);
rayHandler.updateAndRender();
}
public void removeLights(){
rayHandler.removeAll();
pointLight.remove();
}
}
Because i still got laggs, heres my MainClass :
public class LauncherScreen implements Screen{
//-----------------------------------------------------------
//-----------------idle Animation----------------------------
//-----------------------------------------------------------
Map duengon;
AnimatedSprite animationForMultiplayer;
SpriteBatch spriteBatch;
Player mySelf;
OrthographicCamera mpPlayerCam;
OrthographicCamera camera;
static Client client = new Client();
Launcher launcher = new Launcher();
int[][] map = {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};
#Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
launcher.update();
//------------------------------------------------------------------------
//------------------------Draws the Map-----------------------------------
//------------------------------------------------------------------------
duengon.ubdate(map, camera);
//------------------------------------------------------------------------
//------------------------Draws the Players-------------------------------
//------------------------------------------------------------------------
for(MPPlayer mpPlayer : launcher.getPlayersValue()){
animationForMultiplayer.setState(mpPlayer.state);
animationForMultiplayer.createAnimation();
camera.position.set(mpPlayer.x,mpPlayer.y,0);
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
spriteBatch.draw(animationForMultiplayer.convertAnimationTOframes(), mpPlayer.x, mpPlayer.y,Gdx.graphics.getWidth()/25,Gdx.graphics.getHeight()/15); // #6
spriteBatch.end();
System.out.println("mpPlayer : "+mpPlayer.x+" "+mpPlayer.y);
}
mySelf.update();
mySelf.draw(launcher.getPlayerX(), launcher.getPlayerY(), camera);
camera.update();
System.out.println(Gdx.graphics.getFramesPerSecond());
System.out.println("player : "+launcher.getPlayerX()+" "+launcher.getPlayerY());
}
#Override
public void show() {
// TODO Auto-generated method stub
animationForMultiplayer = new AnimatedSprite();
spriteBatch = new SpriteBatch();
mySelf = new Player();
mySelf.doSetup();
mpPlayerCam = new OrthographicCamera(0,0);
mpPlayerCam.setToOrtho(false);
camera = new OrthographicCamera(0, 0);
camera.setToOrtho(false);
duengon = new Map();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#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
}
#Override
public void dispose() {
// TODO Auto-generated method stub
spriteBatch.dispose();
mySelf.doDispose();
animationForMultiplayer.doDispose();
duengon.doDispose();
}
}
The .doDispose() in my mainClass are methods which disposes the resource from the classes is use
Thanks for your help and your time :)
You are not disposing anything, you might want to look into the dispose() function of LibGDX
Here is the link
https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Disposable.html
if thats not the problem please let us know.
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() {
}
}