LibGdx MoveTo() action method for Actor is not working - java

I have a problem with moveTo() action. There is no error, but Actor is not moving to the position. The method is called in touchDown(). I spent a few hours and cant find the solution.
Please can you help? Parameters in moveTo() are random for now, so don't worry about it
Please see below the code.
public class GameScreen implements Screen, InputProcessor {
private final float REMOTE_WIDTH = 30;
private final float BATTERY_WIDTH = 11;
private final float BATTERY_HEIGHT = 30;
private final float TRIANGLE_X1 = RgbSortGame.GAME_SCREEN_WIDTH/2 - REMOTE_WIDTH /2;
private final float TRIANGLE_Y1 = RgbSortGame.GAME_SCREEN_HEIGHT/2;
private final float TRIANGLE_X2 = RgbSortGame.GAME_SCREEN_WIDTH/2 + REMOTE_WIDTH /2;
private final float TRIANGLE_Y2 = RgbSortGame.GAME_SCREEN_HEIGHT/2;
private final float TRIANGLE_X3 = RgbSortGame.GAME_SCREEN_WIDTH/2;
private final float TRIANGLE_Y3 = RgbSortGame.GAME_SCREEN_HEIGHT/2 - REMOTE_WIDTH;
private final float BUTTON_RADIUS = REMOTE_WIDTH/4f;
private final float TV_OFFSET_X = (RgbSortGame.GAME_SCREEN_WIDTH-RgbSortGame.GAME_SCREEN_WIDTH/2)/2;
private final float TV_OFFSET_Y = (RgbSortGame.GAME_SCREEN_HEIGHT-RgbSortGame.GAME_SCREEN_HEIGHT/4)/1.1f;
private Level level;
private List<BatteryView> batteryViews;
private Map<Integer, Battery> strategy;
private Viewport viewport;
private TextureAtlas atlas;
private OrthographicCamera camera;
private SpriteBatch batch;
private ShapeRenderer shapeRenderer;
private Texture background;
private Texture tv;
private Texture battery;
private Stage stage;
private Vector2 tempVector;
private Vector2 tempScreenToStage;
private Queue<String> hitActorsNames;
public GameScreen() {
Level1 level1 = new Level1();
level = new Level(level1.getRelativeCoordinates());
batteryViews = new ArrayList<>();
strategy = level.getBatteries();
batch = new SpriteBatch();
camera = new OrthographicCamera();
viewport = new StretchViewport(RgbSortGame.GAME_SCREEN_WIDTH, RgbSortGame.GAME_SCREEN_HEIGHT, camera);
viewport.apply();
stage = new Stage(viewport, batch);
Gdx.input.setInputProcessor(this);
shapeRenderer = new ShapeRenderer();
atlas = new TextureAtlas("buttons/buttons.atlas");
background = new Texture("images/97916b7c0f1f5f582723426ee1f876ce.jpg");
tv = new Texture("images/tv1.png");
battery = new Texture("images/battery.png");
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
camera.update();
hitActorsNames = new ArrayDeque<>();
calculateBatteriesStartCoordinates();
tempVector = new Vector2(0,0);
tempScreenToStage = new Vector2(0,0);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, 0f,0f,RgbSortGame.GAME_SCREEN_WIDTH, RgbSortGame.GAME_SCREEN_HEIGHT);
batch.draw(tv, TV_OFFSET_X, TV_OFFSET_Y,
RgbSortGame.GAME_SCREEN_WIDTH/2, RgbSortGame.GAME_SCREEN_HEIGHT/4);
batch.end();
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.GOLD);
shapeRenderer.triangle(TRIANGLE_X1, TRIANGLE_Y1,
TRIANGLE_X2, TRIANGLE_Y2,
TRIANGLE_X3, TRIANGLE_Y3);
shapeRenderer.end();
stage.draw();
stage.act(Gdx.graphics.getDeltaTime());
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
camera.update();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
background.dispose();
batch.dispose();
shapeRenderer.dispose();
atlas.dispose();
stage.dispose();
}
public void calculateBatteriesStartCoordinates(){
float batteryStartPositionX = RgbSortGame.GAME_SCREEN_WIDTH/24;
for (int i = 0; i < strategy.size(); i++) {
if (batteryStartPositionX >= TRIANGLE_X1 && batteryStartPositionX<= TRIANGLE_X2){
batteryStartPositionX += REMOTE_WIDTH;
}
Actor batteryView = new BatteryView(batteryStartPositionX, TRIANGLE_Y3, BATTERY_WIDTH, BATTERY_HEIGHT, BUTTON_RADIUS, strategy.get(i), battery, atlas);
batteryStartPositionX += RgbSortGame.GAME_SCREEN_WIDTH/24 + BATTERY_WIDTH;
batteryView.setName(i + "");
stage.addActor(batteryView);
}
}
#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) {
tempScreenToStage = stage.screenToStageCoordinates(tempVector.set((float)screenX,(float)screenY));
Actor hitActor = stage.hit(tempScreenToStage.x,tempScreenToStage.y,true);
if (hitActor != null){
hitActorsNames.add(hitActor.getName());
if (hitActorsNames.size() >= 2){
Actor actor = stage.getRoot().findActor(hitActorsNames.poll());
actor.addAction(Actions.moveTo(100f,200f,0.7f));
hitActorsNames.clear();
}
}
}
return true;
}
#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 scrolledenter code here(float amountX, float amountY) {
return false;
}
And BatteryView:
public class BatteryView extends Actor{
private float positionX;
private float positionY;
private float width;
private float height;
private float buttonRadius;
private Texture batteryTexture;
private Deque<GameButton> buttonsStrategy;
private TextureAtlas atlas;
public BatteryView(float positionX, float positionY, float width, float height,
float buttonRadius, Battery strategy,
Texture batteryTexture, TextureAtlas atlas) {
this.positionX = positionX;
this.positionY = positionY;
this.batteryTexture = batteryTexture;
this.width = width;
this.height = height;
this.atlas = atlas;
this.buttonRadius = buttonRadius;
this.buttonsStrategy = strategy.getGameButtons();
this.setBounds(positionX,positionY,width,height);
this.setTouchable(Touchable.enabled);
this.setSize(width, height);
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float parentAlpha){
batch.draw(batteryTexture,positionX,positionY,width,height);
float xButtonPosition = positionX + width / 2 - buttonRadius / 2;
float yButtonPosition = positionY;
for (GameButton gameButton : buttonsStrategy) {
new GameButtonView(xButtonPosition, yButtonPosition,
buttonRadius, atlas.findRegion(gameButton.getColor())).draw(batch);
yButtonPosition += buttonRadius;
}
}
public float getPositionX() {
return positionX;
}
public float getPositionY() {
return positionY;
}
public float getWidth() {
return width;
}`enter code here`
public float getHeight() {
return height;
}
}
Thank you in advance!

UPDATE: I found a solution! I had to change draw method in BatteryView class. It should be batch.draw(batteryTexture,getX(),getY(),width,height)instead off
batch.draw(batteryTexture,positionX,positionY,width,height).

Related

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;
}
}

libgdx making a touch event

I'm currently following this book to create my libgdx game..
So far, i have these classes to create my game :
AbstractGameScreen.java - that Implements libgdx's Screen
AbstractGameObject.java - that extends libgdx's Actor
GamePlay.java - which is my game screen
GameController.java - where i init my game objects
GameRenderer.java - when i render all my objects
Assets.java - a class that organizes my game assets
Ring.java - an object in my game
And here is my code..
AbstractGameScreen
public abstract class AbstractGameScreen implements Screen {
protected Game game;
public AbstractGameScreen(Game game){
this.game = game;
}
public abstract void render(float deltaTime);
public abstract void resize(int width, int height);
public abstract void show();
public abstract void hide();
public abstract void pause();
public void resume(String bg, String ring){
Assets.instance.init(new AssetManager(), bg, ring); // kosongin, jadinya default
}
public void dispose(){
Assets.instance.dispose();
}
}
AbstractGameObject
public abstract class AbstractGameObject extends Actor{ //implements EventListener{ //extends Sprite{
public Vector2 position;
public Vector2 dimension;
public Vector2 origin;
public Vector2 scale;
public float rotation;
public AbstractGameObject(){
position = new Vector2();
dimension = new Vector2(1, 1);
origin = new Vector2();
scale = new Vector2(1, 1);
rotation = 0;
}
public void update (float deltaTime){
}
public abstract void render(SpriteBatch batch);
}
GamePlay
public class GamePlay extends AbstractGameScreen implements InputProcessor{
private GameController gameController;
private GameRenderer gameRenderer;
private String dummyBg, dummyRing;
private boolean paused;
// for touch purposes
private static final int appWidth = Constants.VIEWPORT_GUI_WIDTH_INT;
private static final int appHeight = Constants.VIEWPORT_GUI_HEIGHT_INT;
public GamePlay(Game game) {
super(game);
// still dummy.. nantinya ngambil dari database nya
this.dummyBg = "bg-default";
this.dummyRing = "ring-default";
Gdx.input.setInputProcessor(this);
}
#Override
public void render(float deltaTime) {
if(!paused){
gameController.update(deltaTime);
}
//Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f,0xed / 255.0f, 0xff / 255.0f);
//Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// render game nya
gameRenderer.render();
}
#Override
public void resize(int width, int height) {
gameRenderer.resize(width, height);
}
#Override
public void show() {
Assets.instance.init(new AssetManager(), "bg-default", "ring-default");
Gdx.app.log("GamePlay", "After show() method");
gameController = new GameController(game);
gameRenderer = new GameRenderer(gameController);
Gdx.input.setCatchBackKey(true);
}
#Override
public void hide() {
gameRenderer.dispose();
Gdx.input.setCatchBackKey(false);
}
#Override
public void dispose(){
gameRenderer.dispose();
Assets.instance.dispose();
}
#Override
public void pause() {
paused = true;
}
#Override
public void resume() {
super.resume(this.dummyBg, this.dummyRing);
//Assets.instance.init(new AssetManager(), this.dummyBg, this.dummyRing);
paused = false;
}
#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) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return true;
}
// for touch purposes
private float getCursorToModelX(int screenX, int cursorX) {
return (((float)cursorX) * appWidth) / ((float)screenX);
}
private float getCursorToModelY(int screenY, int cursorY) {
return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
}
#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;
}
}
GameController
public class GameController extends InputAdapter{
// game objects
public Array<Tiang> tiangs;
public Array<Ring> rings;
//private Game game;
// game decorations
public Background background; public Sprite[] testSprite;
private Game game;
public GameController(Game game){
this.game = game;
init();
}
private void init(){
// preparing variables
rings = new Array<Ring>();
tiangs = new Array<Tiang>();
initObjects();
initDecorations();
initGui();
}
private void initObjects(){
AbstractGameObject obj = null;
obj = new Ring(1, "default");
obj.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
//super.clicked(event, x, y);
Gdx.app.log("tag", "test clisk");
}
});
rings.add((Ring)obj);
}
private void initDecorations(){
}
private void initGui(){
}
private void handleInput(float deltatime){
}
public void update(float deltaTime){
//if(Gdx.input.isTouched()){
// Gdx.app.log("update", "screen touched");
//}
}
}
GameRenderer
public class GameRenderer implements Disposable{
private OrthographicCamera camera;
private GameController controller;
private SpriteBatch batch;
public GameRenderer(GameController controller){
this.controller = controller;
init();
}
private void init(){
batch = new SpriteBatch();
camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT); //diambil dari class "Constants" (di package util)
camera.position.set(0, 0, 0);
camera.update();
}
public void resize(int width, int height){
camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) * width;
camera.update();
}
public void render(){
renderGui();
renderDecorations();
renderObjects();
}
private void renderGui(){
}
private void renderDecorations(){
}
private void renderObjects(){
batch.setProjectionMatrix(camera.combined);
batch.begin();
for(Ring rings : controller.rings){
rings.render(batch);
}
batch.end();
}
#Override
public void dispose() {
}
}
Assets
public class Assets implements Disposable, AssetErrorListener{
public static final String TAG = Assets.class.getName();
public static final Assets instance = new Assets();
private AssetManager assetManager;
// inner class objects
public AssetTiang tiang;
public AssetBackgroud bg;
public AssetTombol tombol;
public AssetTombolBg tombolBg;
public AssetRing ring;
//singleton pattern, buat mencegah instansiasi dari class yang lain
private Assets(){}
//public void init(AssetManager assetManager){
public void init(AssetManager assetManager, String jenisBg, String jenisRing){
this.assetManager = assetManager;
assetManager.setErrorListener(this);
//load texture atlas yang udah dibikin pake TexturePacker nya (liat ebook page 167)
assetManager.load(Constants.TEXTURE_ATLAS_OBJECTS, TextureAtlas.class);
assetManager.load(Constants.TEXTURE_ATLAS_DECORATION, TextureAtlas.class);
assetManager.load(Constants.TEXTURE_ATLAS_GUI, TextureAtlas.class);
// inner class objects
tiang = new AssetTiang(atlasObject);
bg = new AssetBackgroud(atlasDecoration, jenisBg);
tombol = new AssetTombol(atlasGui);
tombolBg = new AssetTombolBg(atlasDecoration);
ring = new AssetRing(atlasObject, jenisRing);
}
#Override
public void error(AssetDescriptor asset, Throwable throwable) {
// TODO Auto-generated method stub
}
#Override
public void dispose(){
assetManager.dispose();
}
public class AssetRing{
public final AtlasRegion ring;
// jenis ring dimasukin disini, karena jenis ring bisa diganti-ganti sesuai yang dipilih
public AssetRing(TextureAtlas atlas, String jenisRing){
if(!jenisRing.equals("")){
ring = atlas.findRegion(jenisRing);
}
else{
ring = atlas.findRegion("ring-default");
}
}
}
}
And finally, Ring (Object)
public class Ring extends AbstractGameObject{
private TextureRegion ringOverLay;
private float length;
// jenis ring nya
public String jenis;
public Ring(float length, String jenis){
init();
setLength(length);
setJenis(jenis);
}
// getters
public float getLength(){
return this.length;
}
public String getJenis(){
return this.jenis;
}
public Vector2 getPosition(){
return position;
}
// setters
public void setLength(float length){
this.length = length;
dimension.set(5.0f, 1.0f);
}
public void setJenis(String jenis){
this.jenis = jenis;
}
public void setPosition(float x, float y){
position.set(x, y);
}
private void init(){
ringOverLay = Assets.instance.ring.ring; // Assets.instance.namaobjek.atlasregion
origin.x = dimension.x/2; // -dimension.x/2;
origin.y = dimension.y/2;
position.x = -5.0f;
position.y = -2.5f;
}
#Override
public void render(SpriteBatch batch) {
TextureRegion reg = null;
reg = ringOverLay;
batch.draw(reg.getTexture(), position.x, position.y, origin.x, origin.y, dimension.x, dimension.y, scale.x, scale.y, rotation, reg.getRegionX(), reg.getRegionY(), reg.getRegionWidth(), reg.getRegionHeight(), false, false);
}
}
So what's the problem? Okay, the problem is i cannot make the Ring (game object) become clickable.. the Ring is extending AbstractGameObject (which is Actor), and, in the GameController i've add a ClickListener to the Ring object, but the object still unclickable..
Please, anyone tell me what's my mistake?
You're using your Actor (in your case, the Ring) incorrectly: Actors are part of Scene2d, and as such must follow precise rules to work correctly.
To answer your question more specifically, Ring needs to be added to a Stage which itself is an InputProcessor. The Stage is responsible to distribute the input events (such as touch events) to the its Actors. Without defining a Stage your Actors will not respond to any input events.
Read up on Scene2d from the link above. This video tutorial is also helpful.

trying to make my (very simple) libgdx game more object-oriented. added GameObject class - game doesn't launch anymore

what the title says.
first of all, here are my 3 classes:
MyGdxGame:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Sprite sp;
Texture img;
int width;
int height;
Player p;
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("dildo.png");
sp = new Sprite(img);
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
p = new Player(img);
Gdx.input.setInputProcessor(p);
}
#Override
public void render () {
//sp.flip(true, false);
p.update();
Gdx.gl.glClearColor(255,255,255,255);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
//batch.draw(img, 0, height/6, -img.getWidth(), img.getHeight());
p.draw(batch);
//sp.draw(batch);
batch.end();
}
}
Player:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.TimeUtils;
public class Player extends GameObject implements InputProcessor {
private Sprite sp;
private Texture te;
private float xPos;
private float yPos;
private float xSpeed;
private float ySpeed;
private float accelerationX;
private float g;
Vector2 position;
private float accelerationJump = 9f;
private boolean allowJump = true;
private boolean isDragged = false;
public Player(Texture sprite) {
xPos = 0;
yPos = (super.getHeight()/6);
xSpeed = 5.5f;
ySpeed = 0;
te = sprite;
sp.setX(xPos);
sp.setY(yPos);
g = 0.2f;
accelerationX=0.02f;
}
public void update() {
ySpeed -= g;
if(isDragged) {
xSpeed += accelerationX;
moveBy(xSpeed,0);
isDragged = false;
}
if (getxPos() > super.getWidth()) {
setxPos(0);
} else {
moveBy(xSpeed, ySpeed);
}
if (getyPos() < super.getHeight() / 6) {
moveTo(sp.getX(), getHeight() / 6);
}
if (onGround()) {
allowJump = true;
ySpeed = 0;
}
}
public void jump() {
ySpeed += accelerationJump;
}
public boolean onGround() {
return (sp.getY() == super.getHeight()/6);
}
#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) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (allowJump && isDragged == false) {
allowJump = false;
jump();
}
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
if(isDragged==false) {
isDragged = true;
}
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
GameObject:
package com.mygdx.game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public abstract class GameObject {
private Sprite sp;
private int width;
private int height;
private float xPos;
private float yPos;
private float xSpeed;
private float ySpeed;
public GameObject(int width, int height) {
this.width = width;
this.height = height;
}
public GameObject() {
}
public void moveTo(float xPos2, float yPos2) {
setxPos(xPos2);
setyPos(yPos2);
}
public void moveBy(float dx, float dy) {
sp.setY(sp.getY() + dy);
sp.setX(sp.getX() + dx);
}
public float getxPos() {
return xPos;
}
public float getyPos() {
return yPos;
}
public void setxPos(float xPos2) {
sp.setX(xPos2);
}
public void setyPos(float yPos) {
sp.setY(yPos);
}
public float getxSpeed() {
return xSpeed;
}
public float getySpeed() {
return ySpeed;
}
public void setxSpeed(float xSpeed2) {
xSpeed = xSpeed2;
}
public void setySpeed(float ySpeed2) {
ySpeed = ySpeed2;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height
}
public void draw(SpriteBatch batch) {
sp.draw(batch);
}
}
basically, the game as it is now is just a sprite moving from left to right of the screen - when you tap, it jumps, when you drag the screen it dashes forward. i want to now start adding things like power-ups and platforms so i thought it would be a good idea to create a GameObject class. but now when i run it the screen goes black and the application just crashes, i have a feeling it has something to do with the way i'm initialising my Texture? any ideas?
any help is highly appreciated, many thanks in advance :)
edit: in GameObject constructor width and height are the width and height of the screen
if you have your image in asset folder of android project, test img = new Texture (Gdx.files.internal ("dildo.png"));
example:
AdroidProyect->Asset->YourFile.png
and in player i think
1-
public Player(Texture sprite) {
xPos = 0;
yPos = (super.getHeight()/6);
xSpeed = 5.5f;
ySpeed = 0;
te = sprite;
//add and refactor your code if it works
sp = new Sprite(sprite);
sp.setX(xPos);
sp.setY(yPos);
g = 0.2f;
accelerationX=0.02f;
}
or 2-
I do not want to do, but in your MyGdxGame, your
you say,
..//
img = new Texture ("dildo.png");
         sp = new Sprite (img);
         p = new Player (img);
..//
but after you pass the player a texture, because no sprite or as I said before initializing the player, you could also change the constructor of the player.
public Player(Sprite sprite){t
..//
this.sp = sprite;
ADD NEW:
Musta Been to look at your code and no offense, you have a code a little crazy :)
visibility of variables is somewhat confusing because what you want but do not test well and looks over the access modifiers, aver if they match what you want to do.
my English is also a little crazy too.
in your class MyGdxGame;
..//
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture(Gdx.files.internal("dildo.png"));
sp = new Sprite(img);
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
p = new Player(sp);
Gdx.input.setInputProcessor(p);
}
..//
class GameObject Change;
public abstract class GameObject {
protected Sprite sp;
protected int width;
protected int height;
protected float xPos;
protected float yPos;
protected float xSpeed;
protected float ySpeed;
player class.
public class Player extends GameObject implements InputProcessor {
//private Sprite sp; remove
private Texture te;
//private float xPos; remove
//private float yPos; remove
//private float xSpeed; remove
//private float ySpeed; remove
private float accelerationX;
private float g;
Vector2 position;
private float accelerationJump = 9f;
private boolean allowJump = true;
private boolean isDragged = false;
public Player(Sprite sprite) {
..//
sp = sprite;

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.

LibGDX Player only faces left and movement isn't animated

I am working on a game in LibGDX and both my players direction and walking animation won't change. He can walk up, down, left, and right, but only faces left no matter what direction he's walking.
public class WorldController {
enum KeyBinds {
LEFT, RIGHT, UP, DOWN, JUMP, FIRE
}
private World world;
private Player p;
static Map<KeyBinds, Boolean> keys = new HashMap<WorldController.KeyBinds, Boolean>();
static {
keys.put(KeyBinds.LEFT, false);
keys.put(KeyBinds.RIGHT, false);
keys.put(KeyBinds.UP, false);
keys.put(KeyBinds.DOWN, false);
keys.put(KeyBinds.JUMP, false);
keys.put(KeyBinds.FIRE, false);
};
public WorldController(World world) {
this.world = world;
this.p = world.getPlayer();
}
// ** Key presses and touches **************** //
public void leftPressed() {
keys.get(keys.put(KeyBinds.LEFT, true));
}
public void rightPressed() {
keys.get(keys.put(KeyBinds.RIGHT, true));
}
public void upPressed() {
keys.get(keys.put(KeyBinds.UP, true));
}
public void downPressed() {
keys.get(keys.put(KeyBinds.DOWN, true));
}
public void jumpPressed() {
keys.get(keys.put(KeyBinds.JUMP, true));
}
public void firePressed() {
keys.get(keys.put(KeyBinds.FIRE, false));
}
public void leftReleased() {
keys.get(keys.put(KeyBinds.LEFT, false));
}
public void rightReleased() {
keys.get(keys.put(KeyBinds.RIGHT, false));
}
public void upReleased() {
keys.get(keys.put(KeyBinds.UP, false));
}
public void downReleased() {
keys.get(keys.put(KeyBinds.DOWN, false));
}
public void jumpReleased() {
keys.get(keys.put(KeyBinds.JUMP, false));
}
public void fireReleased() {
keys.get(keys.put(KeyBinds.FIRE, false));
}
/** The main update method **/
public void update(float delta) {
processInput();
p.update(delta);
}
/** Change player's state and parameters based on input controls **/
private void processInput() {
if(Gdx.input.isKeyPressed(Keys.LEFT)) {
// left is pressed
//p.setFacingLeft(true);
p.setState(State.WALKING);
p.getVelocity().x = -Player.SPEED;
p.getVelocity().y = 0;
}
if(Gdx.input.isKeyPressed(Keys.RIGHT)){
// right is pressed
//p.setFacingRight(true);
p.setState(State.WALKING);
p.getVelocity().x = Player.SPEED;
p.getVelocity().y = 0;
}
if(Gdx.input.isKeyPressed(Keys.UP)) {
// up is pressed
//p.setFacingUp(true);
p.setState(State.WALKING);
p.getVelocity().y = Player.SPEED;
p.getVelocity().x = 0;
}
if(Gdx.input.isKeyPressed(Keys.DOWN)) {
// down is pressed
//p.setFacingDown(true);
p.setState(State.WALKING);
p.getVelocity().y = -Player.SPEED;
p.getVelocity().x = 0;
}
// need to check if both or none direction are pressed, then player is idle
// if ((keys.get(Keys.LEFT) && keys.get(Keys.RIGHT)) ||
// (!keys.get(Keys.LEFT) && !(keys.get(Keys.RIGHT)))) {
// p.setState(State.IDLE);
// // acceleration is 0 on the x
// p.getAcceleration().x = 0;
// // horizontal speed is 0
// p.getVelocity().x = 0;
// }
}
}
public class WorldRenderer {
private static final float CAMERA_WIDTH = 10f;
private static final float CAMERA_HEIGHT = 7f;
private World world;
private OrthographicCamera cam;
/** for debug rendering **/
ShapeRenderer debugRenderer = new ShapeRenderer();
private SpriteBatch spriteBatch;
private boolean debug = false;
private int width;
private int height;
private float ppuX;
private float ppuY;
private static final float RUNNING_FRAME_DURATION = 0.06f;
/** Textures **/
private TextureRegion pIdleLeft;
private TextureRegion pIdleRight;
private TextureRegion pIdleUp;
private TextureRegion pIdleDown;
private TextureRegion blockTexture;
private TextureRegion pFrame;
/** Animations **/
private Animation walkLeftAnimation;
private Animation walkRightAnimation;
private Animation walkUpAnimation;
private Animation walkDownAnimation;
private void loadTextures() {
TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("images/textures/textures.pack"));
pIdleLeft = atlas.findRegion("Left1");
pIdleRight = new TextureRegion(pIdleLeft);
pIdleRight.flip(true, false);
pIdleUp = atlas.findRegion("Back1");
pIdleDown = atlas.findRegion("Front1");
blockTexture = atlas.findRegion("stone");
//Walking Left Animation
TextureRegion[] walkLeftFrames = new TextureRegion[2];
walkLeftFrames[0] = atlas.findRegion("Left1");
walkLeftFrames[1] = atlas.findRegion("Left2");
walkLeftAnimation = new Animation(RUNNING_FRAME_DURATION, walkLeftFrames);
//Walking Right Animation
TextureRegion[] walkRightFrames = new TextureRegion[2];
walkRightFrames[0] = new TextureRegion(walkLeftFrames[0]);
walkRightFrames[0].flip(true, false);
walkRightFrames[1] = new TextureRegion(walkLeftFrames[1]);
walkRightFrames[1].flip(true, false);
walkRightAnimation = new Animation(RUNNING_FRAME_DURATION, walkRightFrames);
//Walking Up Animation
TextureRegion[] walkUpFrames = new TextureRegion[2];
walkUpFrames[0] = atlas.findRegion("Back1");
walkUpFrames[1] = atlas.findRegion("Back2");
walkUpAnimation = new Animation(RUNNING_FRAME_DURATION, walkUpFrames);
//Walking Down Animation
TextureRegion[] walkDownFrames = new TextureRegion[2];
walkLeftFrames[0] = atlas.findRegion("Front1");
walkLeftFrames[1] = atlas.findRegion("Front2");
walkDownAnimation = new Animation(RUNNING_FRAME_DURATION, walkDownFrames);
}
public void drawPlayer() {
Player p = world.getPlayer();
if(p.getState().equals(State.IDLE)) {
if(Gdx.input.isKeyPressed(Keys.LEFT)) pFrame = pIdleLeft;
else if(Gdx.input.isKeyPressed(Keys.RIGHT)) pFrame = pIdleRight;
else if(Gdx.input.isKeyPressed(Keys.UP)) pFrame = pIdleUp;
else if(Gdx.input.isKeyPressed(Keys.DOWN)) pFrame = pIdleDown;
}
if(p.getState().equals(State.WALKING)) {
if(Gdx.input.isKeyPressed(Keys.LEFT)) walkLeftAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.RIGHT)) walkRightAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.UP)) walkUpAnimation.getKeyFrame(p.getStateTime(), true);
else if(Gdx.input.isKeyPressed(Keys.DOWN)) walkDownAnimation.getKeyFrame(p.getStateTime(), true);
}
spriteBatch.draw(pFrame, p.getXPosition() * ppuX, p.getYPosition() * ppuY, Player.SIZE * ppuX, Player.SIZE * ppuY);
}
public void setSize(int w, int h){
this.width = w;
this.height = h;
ppuX = (float)width / CAMERA_WIDTH;
ppuY = (float)height / CAMERA_HEIGHT;
}
public WorldRenderer(World world, boolean debug) {
this.world = world;
this.cam = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
this.cam.position.set(CAMERA_WIDTH / 2f, CAMERA_HEIGHT / 2f, 0);
this.cam.update();
this.debug = debug;
spriteBatch = new SpriteBatch();
loadTextures();
}
public void render(){
spriteBatch.begin();
drawBlocks();
drawPlayer();
spriteBatch.end();
if(debug){
drawDebug();
}
}
public void drawBlocks(){
for(Block block : world.getBlocks()){
spriteBatch.draw(blockTexture, block.getXPosition() * ppuX, block.getYPosition() * ppuY, Block.getSize() * ppuX, Block.getSize() * ppuY );
}
}
public void drawDebug() {
// render blocks
debugRenderer.setProjectionMatrix(cam.combined);
debugRenderer.begin(ShapeType.Line);
for (Block block : world.getBlocks()) {
Rectangle rect = block.getBounds();
float x1 = block.getXPosition() + rect.x;
float y1 = block.getYPosition() + rect.y;
debugRenderer.setColor(new Color(1, 0, 0, 1));
debugRenderer.rect(x1, y1, rect.width, rect.height);
}
// render Player
Player p = world.getPlayer();
Rectangle rect = p.getBounds();
float x1 = p.getXPosition() + rect.x;
float y1 = p.getYPosition() + rect.y;
debugRenderer.setColor(new Color(0, 1, 0, 1));
debugRenderer.rect(x1, y1, rect.width, rect.height);
debugRenderer.end();
}
}
public class Player {
public enum State{
IDLE, WALKING, JUMPING, DYING
}
public static final float SPEED = 4f; //units per second
public static final float SIZE = 0.5f; //half a unit
float stateTime = 0;
Vector2 position = new Vector2();
Vector2 acceleration = new Vector2();
Vector2 velocity = new Vector2();
Rectangle bounds = new Rectangle();
State state = State.IDLE;
boolean facingLeft;
boolean facingRight;
boolean facingUp;
boolean facingDown;
public Player(Vector2 position){
this.position = position;
this.bounds.height = SIZE;
this.bounds.width = SIZE;
}
public void setFacingLeft(boolean facingLeft) {
this.facingLeft = facingLeft;
}
public void setFacingRight(boolean facingRight) {
this.facingRight = facingRight;
}
public void setFacingUp(boolean facingUp) {
this.facingUp = facingUp;
}
public void setFacingDown(boolean facingDown) {
this.facingDown = facingDown;
}
public Vector2 getAcceleration() {
return acceleration;
}
public Vector2 getVelocity() {
return velocity;
}
public void setState(State newState){
this.state = newState;
}
public void update(float delta){
stateTime += delta;
position.add(velocity.cpy().scl(delta));
}
public Rectangle getBounds() {
return bounds;
}
public Object getPosition() {
return position;
}
public float getXPosition(){
return this.position.x;
}
public float getYPosition(){
return this.position.y;
}
public Object getState() {
return state;
}
public float getStateTime() {
return stateTime;
}
}
Sorry for all the code but I don't know where the problem is and didn't want to leave out anything relevant. I'm sure it's a silly mistake but I've been starring at it for a long time.
Also, I made an effort to put each class in it's own code block but it wasn't working out, I'm new to stackoverflow. Thanks to anyone who tries to help.

Categories

Resources