I have a GameScene in which I used ZoomCamera, a background and a few "viruses".
The problem is that when I pinchzoom in or out the background also scales, I do not want that, please help.
http://puu.sh/9XPUl/c6725806ae.png
http://puu.sh/9XQ5g/609d77e962.png
public class GameScene extends BaseScene implements IScrollDetectorListener, IPinchZoomDetectorListener, IOnSceneTouchListener {
private static final String TAG_ENTITY = "entity";
private static final String TAG_ENTITY_ATTRIBUTE_X = "x";
private static final String TAG_ENTITY_ATTRIBUTE_Y = "y";
private static final String TAG_ENTITY_ATTRIBUTE_TYPE = "type";
private ZoomCamera mZoomCamera = GameActivity.mZoomCamera;
private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CELL = "cell";
//private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM1 = "platform1";
//private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM2 = "platform2";
//private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM3 = "platform3";
//private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_COIN = "coin";
private SurfaceScrollDetector mScrollDetector;
private PinchZoomDetector mPinchZoomDetector;
private float mPinchZoomStartedCameraZoomFactor;
#Override
public void createScene() {
this.mScrollDetector = new SurfaceScrollDetector(this);
this.mPinchZoomDetector = new PinchZoomDetector(this);
this.setOnSceneTouchListener(this);
this.setTouchAreaBindingOnActionDownEnabled(true);
this.setOnAreaTouchTraversalFrontToBack();
createBackground();
createHUD();
createPhysics();
loadLevel(1);
}
#Override
public void onBackKeyPressed() {
SceneManager.getInstance().loadMenuScene(engine);
}
private void createBackground()
{ Sprite bg=new Sprite(400, 240, resourcesManager.menu_background_region, vbom);
attachChild(bg);
/*attachChild(new Sprite(400, 240, resourcesManager.menu_background_region, vbom)
{
#Override
protected void preDraw(GLState pGLState, Camera pCamera)
{
super.preDraw(pGLState, pCamera);
pGLState.enableDither();
}
});*/
}
#Override
public SceneType getSceneType() {
// TODO Auto-generated method stub
return null;
}
#Override
public void disposeScene()
{
camera.setHUD(null);
camera.setCenter(400, 240);
mZoomCamera.setZoomFactor(1.0f);
// TODO code responsible for disposing scene
// removing all game scene objects.
}
private HUD gameHUD;
private Text scoreText;
private void createHUD()
{
gameHUD = new HUD();
// CREATE SCORE TEXT
scoreText = new Text(20, 420, resourcesManager.font, "Score: 0123456789", new TextOptions(HorizontalAlign.LEFT), vbom);
scoreText.setAnchorCenter(0, 0);
scoreText.setText("Score: 0");
gameHUD.attachChild(scoreText);
camera.setHUD(gameHUD);
}
private int score = 0;
private void addToScore(int i)
{
score += i;
scoreText.setText("Score: " + score);
}
private PhysicsWorld physicsWorld;
private void createPhysics()
{
physicsWorld = new FixedStepPhysicsWorld(60, new Vector2(0, -17), false);
registerUpdateHandler(physicsWorld);
}
private void loadLevel(int levelID)
{
final SimpleLevelLoader levelLoader = new SimpleLevelLoader(vbom);
final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.01f, 0.5f);
levelLoader.registerEntityLoader(new EntityLoader<SimpleLevelEntityLoaderData>(LevelConstants.TAG_LEVEL)
{
public IEntity onLoadEntity(final String pEntityName, final IEntity pParent, final Attributes pAttributes, final SimpleLevelEntityLoaderData pSimpleLevelEntityLoaderData) throws IOException
{
SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_WIDTH);
SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_HEIGHT);
// TODO later we will specify camera BOUNDS and create invisible walls
// on the beginning and on the end of the level.
return GameScene.this;
}
});
levelLoader.registerEntityLoader(new EntityLoader<SimpleLevelEntityLoaderData>(TAG_ENTITY)
{
public IEntity onLoadEntity(final String pEntityName, final IEntity pParent, final Attributes pAttributes, final SimpleLevelEntityLoaderData pSimpleLevelEntityLoaderData) throws IOException
{
final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X);
final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y);
final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE);
final Sprite levelObject;
/* if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM1))
{
levelObject = new Sprite(x, y, resourcesManager.platform1_region, vbom);
PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF).setUserData("platform1");
}
else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM2))
{
levelObject = new Sprite(x, y, resourcesManager.platform2_region, vbom);
final Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
body.setUserData("platform2");
physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));
}
else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM3))
{
levelObject = new Sprite(x, y, resourcesManager.platform3_region, vbom);
final Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
body.setUserData("platform3");
physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));
}
else*/ if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CELL))
{
levelObject = new Sprite(x, y, resourcesManager.cell_region, vbom);
final Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
body.setUserData("cell");
physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));
}
/*else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_COIN))
{
levelObject = new Sprite(x, y, resourcesManager.coin_region, vbom)
{
#Override
protected void onManagedUpdate(float pSecondsElapsed)
{
super.onManagedUpdate(pSecondsElapsed);
/**
* TODO
* we will later check if player collide with this (coin)
* and if it does, we will increase score and hide coin
* it will be completed in next articles (after creating player code)
}
};
levelObject.registerEntityModifier(new LoopEntityModifier(new ScaleModifier(1, 1, 1.3f)));
} */
else
{
throw new IllegalArgumentException();
}
levelObject.setCullingEnabled(true);
return levelObject;
}
});
levelLoader.loadLevelFromAsset(activity.getAssets(), "level/" + levelID + ".lvl");
}
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);
if(this.mPinchZoomDetector.isZooming()) {
this.mScrollDetector.setEnabled(false);
} else {
if(pSceneTouchEvent.isActionDown()) {
this.mScrollDetector.setEnabled(true);
}
this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
}
return true;
}
#Override
public void onPinchZoomStarted(PinchZoomDetector pPinchZoomDetector,
TouchEvent pSceneTouchEvent) {
this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor();
}
#Override
public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
TouchEvent pTouchEvent, float pZoomFactor) {
this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
}
#Override
public void onPinchZoomFinished(PinchZoomDetector pPinchZoomDetector,
TouchEvent pTouchEvent, float pZoomFactor) {
this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
}
#Override
public void onScrollStarted(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
final float zoomFactor = mZoomCamera.getZoomFactor();
mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, pDistanceY / zoomFactor);
}
#Override
public void onScroll(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
final float zoomFactor = mZoomCamera.getZoomFactor();
mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, pDistanceY / zoomFactor);
}
#Override
public void onScrollFinished(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
final float zoomFactor = mZoomCamera.getZoomFactor();
mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, pDistanceY / zoomFactor);
}
}
You're attaching your background as Entity using attachChild() method. You have to use setBackground() method instead.
setBackground(new SpriteBackground(bg));
Related
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).
I made a button, witch stops the game. The is a menu, where you can continue the game. But if the cam moves with the player, the button doesn't work any more. You can see it, but if you click on it nothing happens. If you come back to the "start position" of the cam, the button works again. But the InputProcessor is always the stage with the button.
public class PlayState extends State {
//Objects
private final GameStateManager gameStateManager;
private final State me;
private EntityManager entityManager;
private Player player;
private Texture background;
private Texture filter;
private BitmapFont font;
private Sound click, boost;
private Drug drug;
private Border border;
private House house;
//Constants
public static final int FIELD_SIZE_HEIGHT = 1000;
public static final int FIELD_SIZE_WIDTH = 500;
//Variables
private int collectedDrugs;
private boolean pause, renderLost;
private boolean boostSound;
//Button pause
private Stage stage;
private ImageButton button;
private Drawable drawable;
private Texture textureBtn;
public PlayState(GameStateManager gsm) {
super(gsm);
gameStateManager = gsm;
me = this;
entityManager = new EntityManager();
player = new Player(this, 100, 100);
border = new Border();
background = new Texture("bggame.png");
filter = new Texture("filter.png");
cam.setToOrtho(false, MinniMafia.WIDTH, MinniMafia.HEIGHT);
click = Gdx.audio.newSound(Gdx.files.internal("Click.mp3"));
boost = Gdx.audio.newSound(Gdx.files.internal("boost.mp3"));
drug = new Drug();
house = new House();
collectedDrugs = 0;
font = new BitmapFont();
entityManager.addEntity(player);
entityManager.addEntity(drug);
entityManager.addEntity(border);
entityManager.addEntity(house);
pause = false;
renderLost = false;
boostSound = false;
stage = new Stage();
textureBtn = new Texture("pausebtn.png");
drawable = new TextureRegionDrawable(new TextureRegion(textureBtn));
button = new ImageButton(drawable);
button.setPosition(cam.position.x + cam.viewportWidth/2 - 50, cam.position.y + cam.viewportHeight/2 - 50);
button.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
gameStateManager.set(new PauseState(gameStateManager, me));
}
});
stage.addActor(button);
Gdx.input.setInputProcessor(button.getStage());
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched()) {
click.play(0.2f);
}
if (Gdx.input.isTouched()) {
player.setStop(true);
boostSound = false;
} else {
if (!boostSound) {
boost.play(0.2f);
boostSound = true;
}
player.setStop(false);
}
}
#Override
public void update(float dt) {
Gdx.input.setInputProcessor(stage);
if(Gdx.input.getInputProcessor() == stage){
System.out.println("All working");
}else{
System.out.println("Error");
}
if (!pause) {
handleInput();
entityManager.updateEntities(dt);
setCam();
button.setPosition(cam.position.x + cam.viewportWidth/2 - 60, cam.position.y + cam.viewportHeight/2 - 60);
if (drug.collides(player.getBounds())) {
entityManager.disposeEntity(drug);
player.setGotDrug(true);
}
if (border.collides(player.getBounds()) && !border.isOpen()) {
pause = true;
renderLost = true;
}
if (house.collides(player.getBounds()) && player.isGotDrug()) {
player.setGotDrug(false);
collectedDrugs++;
drug = new Drug();
entityManager.addEntity(drug);
}
} else if (renderLost = true) {
if (Gdx.input.isTouched()) {
gsm.set(new MenuState(gsm));
dispose();
}
}
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, 0, 0);
entityManager.renderEntities(sb);
button.draw(sb, 10f);
font.draw(sb, "" + collectedDrugs, cam.position.x - cam.viewportWidth / 2 + 10, cam.position.y - cam.viewportHeight / 2 + 20);
if (renderLost) {
sb.draw(filter, cam.position.x - cam.viewportWidth / 2, cam.position.y - cam.viewportHeight / 2);
font.draw(sb, "LOST! SCORE:" + collectedDrugs, cam.position.x - 50, cam.position.y);
}
sb.end();
}
#Override
public void dispose() {
background.dispose();
entityManager.disposeAll();
click.dispose();
}
private void setCam() {
float camViewportHalfX = cam.viewportWidth * .5f;
float camViewportHalfY = cam.viewportHeight * .5f;
cam.position.x = player.getPosition().x;
cam.position.y = player.getPosition().y;
cam.position.x = MathUtils.clamp(cam.position.x, camViewportHalfX, FIELD_SIZE_WIDTH - camViewportHalfX);
cam.position.y = MathUtils.clamp(cam.position.y, camViewportHalfY, FIELD_SIZE_HEIGHT - camViewportHalfY);
cam.update();
}
public Drug getDrug() {
return drug;
}
public House getHouse() {
return house;
}
}
I really don't know where the problem is. Could you help me please?
I recently got into LibGDX using the book "LibGDX Game Development By Example" (Pretty good one btw) and have been playing around with the tutorial projects for the last month.
One of these games is a FlappyBird-clone (of course it is) and I decided to add features, change sprites etc.
Now the problem is that the normal obstacle graphics (flowers) don't fit the new theme and need to be exchanged.
Doing so results in jiggering graphics for the new sprites.
I should point out that the code used to visualize these obstacles has not changed at all, simply exchanging the sprites causes this problem.
I tried a lot of different sprites and all that are not identical to the flowers seem to have this problem.
So whatever is the cause, the old flower sprites are unaffected, every other sprite is.
On to the code (Removed some Getters/Setters and other unrelated methods)
The Flower/Obstacle Class:
public class Flower
{
private static final float COLLISION_RECTANGLE_WIDTH = 13f;
private static final float COLLISION_RECTANGLE_HEIGHT = 447f;
private static final float COLLISION_CIRCLE_RADIUS = 33f;
private float x = 0;
private float y = 0;
private static final float MAX_SPEED_PER_SECOND = 100f;
public static final float WIDTH = COLLISION_CIRCLE_RADIUS * 2;
private static final float HEIGHT_OFFSET = -400.0f;
private static final float DISTANCE_BETWEEN_FLOOR_AND_CEILING = 225.0f;
private final Circle floorCollisionCircle;
private final Rectangle floorCollisionRectangle;
private final Circle ceilingCollisionCircle;
private final Rectangle ceilingCollisionRectangle;
private boolean pointClaimed = false;
private final TextureRegion floorTexture;
private final TextureRegion ceilingTexture;
float textureX,textureY;
public Flower(TextureRegion floorTexture, TextureRegion ceilingTexture)
{
this.floorTexture = floorTexture;
this.ceilingTexture = ceilingTexture;
this.y = MathUtils.random(HEIGHT_OFFSET);
this.floorCollisionRectangle = new Rectangle(x,y,COLLISION_RECTANGLE_WIDTH,COLLISION_RECTANGLE_HEIGHT);
this.floorCollisionCircle = new Circle(x + floorCollisionRectangle.width / 2, y + floorCollisionRectangle.height, COLLISION_CIRCLE_RADIUS);
this.ceilingCollisionRectangle = new Rectangle(x,floorCollisionCircle.y + DISTANCE_BETWEEN_FLOOR_AND_CEILING,COLLISION_RECTANGLE_WIDTH,
COLLISION_RECTANGLE_HEIGHT);
this.ceilingCollisionCircle = new Circle(x + ceilingCollisionRectangle.width / 2, ceilingCollisionRectangle.y, COLLISION_CIRCLE_RADIUS);
}
public void update(float delta)
{
setPosition(x - (MAX_SPEED_PER_SECOND * delta));
}
public void setPosition(float x)
{
this.x = x;
updateCollisionCircle();
updateCollisionRectangle();
}
private void updateCollisionCircle()
{
floorCollisionCircle.setX(x + floorCollisionRectangle.width / 2);
ceilingCollisionCircle.setX(x + ceilingCollisionRectangle.width / 2);
}
private void updateCollisionRectangle()
{
floorCollisionRectangle.setX(x);
ceilingCollisionRectangle.setX(x);
}
public void draw(SpriteBatch batch)
{
drawFloorFlower(batch);
drawCeilingFlower(batch);
}
private void drawFloorFlower(SpriteBatch batch)
{
textureX = floorCollisionCircle.x - floorTexture.getRegionWidth() / 2;
textureY = floorCollisionRectangle.getY() + COLLISION_CIRCLE_RADIUS;
batch.draw(floorTexture,textureX,textureY);
}
private void drawCeilingFlower(SpriteBatch batch)
{
textureX = ceilingCollisionCircle.x - ceilingTexture.getRegionWidth() / 2;
textureY = ceilingCollisionRectangle.getY() - COLLISION_CIRCLE_RADIUS;
batch.draw(ceilingTexture,textureX, textureY);
}
}
And the GameScreen/Main Class:
public class GameScreen extends ScreenAdapter
{
private static final float WORLD_WIDTH = 480;
private static final float WORLD_HEIGHT = 640;
private java.util.prefs.Preferences prefs;
private int highscore;
FlappeeBeeGame flappeeBeeGame;
private ShapeRenderer shapeRenderer;
private Viewport viewport;
private Camera camera;
private SpriteBatch batch;
private Flappee flappee;
private Flower flower;
private Array<Flower> flowers = new Array<Flower>();
private static final float GAP_BETWEEN_FLOWERS = 200.0f;
private boolean gameOver = false;
int score = 0;
BitmapFont bitmapFont;
GlyphLayout glyphLayout;
private TextureRegion background;
private TextureRegion flowerBottom;
private TextureRegion flowerTop;
private TextureRegion bee;
private TextureRegion smallCloud;
private TextureRegion lowCloud;
private Music music_background;
TextureAtlas textureAtlas;
List<Cloud> activeClouds = new ArrayList<Cloud>();
List<Cloud> cloudBarriers = new ArrayList<Cloud>();
private float cloud_minScale = 0.6f;
private float cloud_maxScale = 1.0f;
private float cloud_minY, cloud_maxY;
private float cloud_minDis, cloud_maxDis;
private float cloud_minSpeed = 17.0f;
private float cloud_maxSpeed = 27.0f;
private final float barrierCloud_speed = 150.0f;
private boolean inputBlocked = false;
private float blockTime = 0.5f;
private float remainingblockTime = blockTime;
public GameScreen(FlappeeBeeGame fpg)
{
flappeeBeeGame = fpg;
flappeeBeeGame.getAssetManager().load("assets/flappee_bee_assets.atlas",TextureAtlas.class);
flappeeBeeGame.getAssetManager().finishLoading();
textureAtlas = flappeeBeeGame.getAssetManager().get("assets/flappee_bee_assets.atlas");
prefs = java.util.prefs.Preferences.userRoot().node(this.getClass().getName());
highscore = prefs.getInt("highscore",0);
music_background = Gdx.audio.newMusic(Gdx.files.internal("assets/backgroundmusic.ogg"));
music_background.setLooping(true);
music_background.setVolume(0.5f);
music_background.play();
}
private void createNewFlower()
{
Flower newFlower = new Flower(flowerBottom,flowerTop);
newFlower.setPosition(WORLD_WIDTH + Flower.WIDTH);
flowers.add(newFlower);
}
private void checkIfNewFlowerIsNeeded()
{
if(flowers.size == 0)
{
createNewFlower();
}
else
{
Flower flower = flowers.peek();
if(flower.getX() < WORLD_WIDTH - GAP_BETWEEN_FLOWERS)
{
createNewFlower();
}
}
}
private void drawFlowers()
{
for(Flower flower : flowers)
{
flower.draw(batch);
}
}
private void removeFlowersIfPassed()
{
if(flowers.size > 0)
{
Flower firstFlower = flowers.first();
if(firstFlower.getX() < -Flower.WIDTH)
{
flowers.removeValue(firstFlower,true);
}
}
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
viewport.update(width,height);
}
#Override
public void show() {
super.show();
camera = new OrthographicCamera();
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
camera.update();
viewport = new FitViewport(WORLD_WIDTH,WORLD_HEIGHT, camera);
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
bitmapFont = new BitmapFont(Gdx.files.internal("assets/score_new.fnt"));
glyphLayout = new GlyphLayout();
background = textureAtlas.findRegion("bg");
flowerBottom = textureAtlas.findRegion("pipeBottom");
flowerTop = textureAtlas.findRegion("flowerTop");
bee = textureAtlas.findRegion("bee");
smallCloud = textureAtlas.findRegion("smallCloud");
lowCloud = textureAtlas.findRegion("lowerCloud");
flower = new Flower(flowerBottom,flowerTop);
flappee = new Flappee(bee,textureAtlas);
flappee.setPosition(WORLD_WIDTH/4,WORLD_HEIGHT/2);
cloud_minDis = smallCloud.getRegionWidth() / 4;
cloud_maxDis = smallCloud.getRegionWidth();
cloud_maxY = viewport.getWorldHeight() - smallCloud.getRegionHeight()/2;
cloud_minY = viewport.getWorldHeight() - smallCloud.getRegionHeight() * 2;
Cloud a = generateCloud(null);
Cloud b = generateCloud(a);
Cloud c = generateCloud(b);
Cloud d = generateCloud(c);
Cloud e = generateCloud(d);
activeClouds.add(a);
activeClouds.add(b);
activeClouds.add(c);
activeClouds.add(d);
activeClouds.add(e);
a = new Cloud(lowCloud,batch,0,0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
b = new Cloud(lowCloud,batch,lowCloud.getRegionWidth(),0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
c = new Cloud(lowCloud,batch,lowCloud.getRegionWidth()*2,0 - lowCloud.getRegionHeight()/4,barrierCloud_speed,1.0f);
cloudBarriers.add(a);
cloudBarriers.add(b);
cloudBarriers.add(c);
}
public Cloud generateCloud(Cloud formerCloud)
{
Cloud d;
if(formerCloud == null)
{
float randomVal = (float)Math.random();
d = new Cloud(smallCloud,batch,viewport.getWorldWidth(),
(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY,
randomVal * (cloud_maxSpeed-cloud_minSpeed) + cloud_minSpeed,
randomVal * (cloud_maxScale-cloud_minScale) + cloud_minScale);
return d;
}
float randomVal = (float)Math.random();
d = new Cloud(smallCloud,batch,formerCloud.getPosX() + ((float)
Math.random() * (cloud_maxDis - cloud_minDis) + cloud_minDis),(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY,
randomVal * (cloud_maxSpeed-cloud_minSpeed) + cloud_minSpeed,
randomVal * (cloud_maxScale-cloud_minScale) + cloud_minScale);
return d;
}
#Override
public void render(float delta) {
super.render(delta);
clearScreen();
shapeRenderer.setProjectionMatrix(camera.projection);
shapeRenderer.setTransformMatrix(camera.view);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.end();
draw(delta);
update(delta);
}
private void draw(float delta)
{
batch.setProjectionMatrix(camera.projection);
batch.setTransformMatrix(camera.view);
batch.begin();
batch.draw(background,0,0);
drawClouds(delta);
drawScore();
drawFlowers();
//drawDebug();
if(!gameOver)
{
flappee.draw(batch,delta);
}
drawBarrierClouds(delta);
batch.end();
}
private void updateClouds(float delta)
{
boolean move = false;
Cloud tmp = null;
for(Cloud c : cloudBarriers)
{
c.update(delta);
if(c.getPosX() <= -lowCloud.getRegionWidth())
{
tmp = c;
move = true;
}
}
if(move)
{
float positionX = cloudBarriers.get(cloudBarriers.size()-1).getPosX() + lowCloud.getRegionWidth();
if(positionX < viewport.getWorldWidth())
{
positionX = viewport.getWorldWidth();
}
tmp.setPos(positionX,0 - lowCloud.getRegionHeight()/4);
cloudBarriers.remove(tmp);
cloudBarriers.add(tmp);
tmp = null;
move = false;
}
for(Cloud c : activeClouds)
{
c.update(delta);
if(c.getPosX() <= -smallCloud.getRegionWidth())
{
tmp = c;
move = true;
}
}
if(move)
{
float randomVal = (float)Math.random();
float positionX = activeClouds.get(activeClouds.size()-1).getPosX() + ((float)
Math.random() * (cloud_maxDis - cloud_minDis) + cloud_minDis);
if(positionX < viewport.getWorldWidth())
{
positionX = viewport.getWorldWidth();
}
tmp.setPos(positionX,(float)Math.random() * (cloud_maxY - cloud_minY) + cloud_minY);
tmp.setSpeed(randomVal * (cloud_maxSpeed - cloud_minSpeed) + cloud_minSpeed);
tmp.setScale(randomVal * (cloud_maxScale - cloud_minScale) + cloud_minScale);
activeClouds.remove(tmp);
activeClouds.add(tmp);
move = false;
tmp = null;
}
}
private void drawBarrierClouds(float delta)
{
for(Cloud c : cloudBarriers)
{
c.render();
}
}
private void drawClouds(float delta)
{
for(Cloud c : activeClouds)
{
c.render();
}
}
private void clearScreen()
{
Gdx.gl.glClearColor(Color.BLACK.r,Color.BLACK.g,Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void blockFlappeeLeavingTheWorld()
{
flappee.setPosition(flappee.getX(), MathUtils.clamp(flappee.getY(),0,WORLD_HEIGHT));
}
private void updateFlowers(float delta)
{
for(Flower flower : flowers)
{
flower.update(delta);
}
checkIfNewFlowerIsNeeded();
removeFlowersIfPassed();
}
private void update(float delta)
{
updateClouds(delta);
if(!gameOver) {
updateFlappee(delta);
updateFlowers(delta);
updateScore();
if (checkForCollision())
{
gameOver = true;
inputBlocked = true;
remainingblockTime = blockTime;
restart();
}
}
else
{
if((Gdx.input.isKeyJustPressed(Input.Keys.SPACE) || Gdx.input.isButtonPressed(Input.Buttons.LEFT)) && !inputBlocked)
{
gameOver = false;
score = 0;
}
if(inputBlocked)
{
if(remainingblockTime > 0)
{
remainingblockTime -= delta;
}
else
{
inputBlocked = false;
remainingblockTime = blockTime;
}
}
}
}
private void restart()
{
flappee.setPosition(WORLD_WIDTH / 4, WORLD_HEIGHT / 2);
flowers.clear();
}
#Override
public void dispose() {
super.dispose();
}
private boolean checkForCollision()
{
for(Flower flower : flowers)
{
if(flower.isFlappeeColliding(flappee))
{
if(score > highscore)
{
highscore = score;
prefs.putInt("highscore",highscore);
inputBlocked = true;
remainingblockTime = blockTime;
}
return true;
}
}
return false;
}
}
I'd love to give you a runnable jar but I've got some problems building a working version. Let's just say a jar is out of the question for now.
What I can give you are screenshots:
Jiggering Sprite View
Functional Flower Sprite View
The first image shows the problem: The new sprites (which are just debug) become edgy like the top of the sprite can't compete with the speed of its lower half.
The second image shows the old sprites for comparison: They don't show any of this behaviour, even if they are longer than the one on the screenshot.
So what do you people think?
What causes this behaviour and how should I fix it?
Thanks in advance for any help, I appreciate it :)
Greetz!
EDIT:
I kind of fixed it.
When switching to another computer and running the game the issue didn't come up anymore.
Specifically I went from Debian to Windows 10 and from NVIDIA Optimus to a standard desktop AMD-Card.
If you should encounter this problem try another PC with a different OS and/or GPU.
Sadly (if you were to google this question) I can't tell you how to solve it on the first machine or what exactly caused it, but at least it shouldn't come up on anyone else's computer when you send them your project.
Im trying to use the technique shown here, but unfortunately I have one problem. Whenever the color fades into the next colour the screen flashes/blinks a white colour. The problem seems to be coming from this class:
public class ColorAnimationDrawable extends Drawable implements Animatable {
private static final long FRAME_DURATION = 1000 / 60;
private static final long ANIMATION_DURATION = 1500;
private static final int ACCCENT_COLOR = 0x33FFFFFF;
private static final int DIM_COLOR = 0x33000000;
private static final Random mRandom = new Random();
private final Paint mPaint = new Paint();
private boolean mIsRunning;
private int mStartColor;
private int mEndColor;
private int mCurrentColor;
private long mStartTime;
#Override
public void draw(Canvas canvas) {
final Rect bounds = getBounds();
mPaint.setColor(mCurrentColor);
canvas.drawRect(bounds, mPaint);
mPaint.setColor(ACCCENT_COLOR);
canvas.drawRect(bounds.left, bounds.top, bounds.right, bounds.top + 1, mPaint);
mPaint.setColor(DIM_COLOR);
canvas.drawRect(bounds.left, bounds.bottom - 2, bounds.right, bounds.bottom, mPaint);
}
#Override
public void setAlpha(int alpha) {
oops("setAlpha(int)");
}
#Override
public void setColorFilter(ColorFilter cf) {
oops("setColorFilter(ColorFilter)");
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
#Override
public void start() {
if (!isRunning()) {
mIsRunning = true;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mStartColor = randomColor();
mEndColor = randomColor();
scheduleSelf(mUpdater, SystemClock.uptimeMillis() + FRAME_DURATION);
invalidateSelf();
}
}
#Override
public void stop() {
if (isRunning()) {
unscheduleSelf(mUpdater);
mIsRunning = false;
}
}
#Override
public boolean isRunning() {
return mIsRunning;
}
private void oops(String message) {
throw new UnsupportedOperationException("ColorAnimationDrawable doesn't support " + message);
}
private static int randomColor() {
return mRandom.nextInt() & 0x00FFFFFF;
}
private static int evaluate(float fraction, int startValue, int endValue) {
return (int) (startValue + fraction * (endValue - startValue));
}
private final Runnable mUpdater = new Runnable() {
#Override
public void run() {
long now = AnimationUtils.currentAnimationTimeMillis();
long duration = now - mStartTime;
if (duration >= ANIMATION_DURATION) {
mStartColor = mEndColor;
mEndColor = randomColor();
mStartTime = now;
mCurrentColor = mStartColor;
} else {
float fraction = duration / (float) ANIMATION_DURATION;
//#formatter:off
mCurrentColor = Color.rgb(
evaluate(fraction, Color.red(mStartColor), Color.red(mEndColor)), // red
evaluate(fraction, Color.green(mStartColor), Color.green(mEndColor)), // green
evaluate(fraction, Color.blue(mStartColor), Color.blue(mEndColor))); // blue
//#formatter:on
}
scheduleSelf(mUpdater, SystemClock.uptimeMillis() + FRAME_DURATION);
invalidateSelf();
}
};
}
Ive noticed that if I change ANIMATION_DURATION to something longer the delay in between the flashing is also longer. Does anyone know what the issue is and how I can get rid of the blinking?
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.