How to draw a Sprite in Libgdx/Android? - java

im working on a libgdx Game where you avoid Asteroids with a spaceship. When i launch my project i only see a white Screen :( Here u can see a big part of my code to understand what iam trying to do.
Main Class:
package com.me.mygdxgame;
import screen.MenuScreen;
import screen.ScreenManager;
public class MyGdxGame implements ApplicationListener {
SpriteBatch batch;
public static int WIDTH = 800 , HEIGHT = 480; // resolution
#Override
public void create() {
batch = new SpriteBatch();
ScreenManager.setScreen(new MenuScreen());
}
#Override
public void dispose() {
if(ScreenManager.getCurrentScreen() != null){
ScreenManager.getCurrentScreen().dispose();
}
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(ScreenManager.getCurrentScreen() != null){
ScreenManager.getCurrentScreen().update();
}
if(ScreenManager.getCurrentScreen() != null){
ScreenManager.getCurrentScreen().render(batch);
}
}
Screen class:
package screen;
public abstract class Screen {
public abstract void create();
public abstract void render(SpriteBatch batch);
public abstract void update();
public abstract void resize(int width, int height);
public abstract void dispose(int width, int height);
public abstract void dispose();
public abstract void pause();
public abstract void resume();
}
ScreenManager:
public class ScreenManager {
private static Screen currentScreen;
public static void setScreen(Screen screen){
if(currentScreen != null){
currentScreen.dispose();
currentScreen = screen;
currentScreen.create();
}
}
public static Screen getCurrentScreen() {
return currentScreen;
}
}
MenuScreen:
public class MenuScreen extends Screen {
private OrthoCamera cam;
private Spaceship spaceship;
#Override
public void create() {
// TODO Auto-generated method stub
cam = new OrthoCamera();
spaceship = new Spaceship();
}
#Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
batch.setProjectionMatrix(cam.combined);
batch.begin();
spaceship.render(batch);
batch.end();
}
#Override
public void update() {
// TODO Auto-generated method stub
cam.update();
spaceship.update();
}
Spaceship Class:
public class Spaceship extends Entity {
Texture texture;
Sprite sprite;
public Spaceship() {
texture = new Texture("spritesheet.png");
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear );
TextureRegion region = new TextureRegion(texture, 0, 312, 258, 144);
sprite = new Sprite(region);
sprite.setSize(sprite.getWidth(), sprite.getHeight());
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
sprite.setPosition(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
}
public void update() {
if (Gdx.input.isTouched()) {
pos.x = Gdx.input.getX() - MyGdxGame.WIDTH / 2;
pos.y = -Gdx.input.getY() + MyGdxGame.HEIGHT / 2;
}
}
#Override
public void render(SpriteBatch batch) {
sprite.draw(batch);
}

The problem should be in your ScreenManager. The method setScreen is incapable of initializing a screen if there is no previous screen:
public static void setScreen(Screen screen){
if(currentScreen != null){
currentScreen.dispose();
currentScreen = screen;
currentScreen.create();
}
}
Should be:
public static void setScreen(Screen screen) {
if (currentScreen != null){
currentScreen.dispose();
}
currentScreen = screen;
currentScreen.create();
}

Related

LibGDX How to put the game in the table? *** FIXED ***

I have a game screen in which I want to implement both the game itself and the control buttons. I divided this screen into two parts using TABLE.
The control buttons and the game are implemented in different classes. Everything works correctly, except for displaying the game.
How to make the game fit in the top window?
Game Screen code
public class GameScreen implements Screen {
private Main parent;
private Stage stage;
public static SnakeControl snakeControl;
private SpriteBatch batch;
private GameControl game;
public GameScreen(Main main) {
parent = main;
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
snakeControl = new SnakeControl();
GameAssets.instance().loadAssets();
batch = new SpriteBatch();
game = new GameControl();
}
#Override
public void show() {
Table table = new Table();
table.setFillParent(true);
table.setDebug(true);
table.row();
table.add(game).expand().pad(10f, 5f, 10f, 5f);
table.row();
table.add(snakeControl.get_tSnakeControl()).fillX().height(GameInfo.SCREEN_HEIGHT/3.5f).pad(0f, 5f, 10f, 5f);
stage.addActor(table);
}
#Override
public void render(float delta) {
game.update(Gdx.graphics.getDeltaTime());
clearScreen();
batch.begin();
game.render(batch);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
batch.end();
}
private void clearScreen() {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
batch.dispose();
GameAssets.instance().dispose();
}
The Game code
public class GameControl extends Actor {
private Board board;
private Snake snake;
private float timeState;
private BitmapFont font;
private GameObject food;
private boolean isGameOver;
public GameControl() {
TextureAtlas atlas = GameAssets.instance().get(GameAssets.SNAKE_PACK);
font = GameAssets.instance().get(GameAssets.PIXEL_FONT);
snake = new Snake(atlas);
board = new Board(snake, GameInfo.SCREEN_WIDTH, GameInfo.SCREEN_HEIGHT);
food = board.generateFood();
init();
}
private void init() {
GameSoundsPlayer.init();
GameSoundsPlayer.playMusic(GameAssets.MEMO_SOUND, false);
}
public void update(float delta) {
if (snake.hasLive()) {
timeState += delta;
snake.handleEvents();
if (timeState >= .09f) {
snake.moveBody();
timeState = 0;
}
if (snake.isCrash()) {
snake.reset();
snake.popLife();
GameSoundsPlayer.playSound(GameAssets.CRASH_SOUND, false);
}
if (snake.isFoodTouch(food)) {
GameSoundsPlayer.playSound(GameAssets.EAT_FOOD_SOUND, false);
Scorer.score();
snake.grow();
food = board.generateFood();
}
} else {
gameOver();
if (Gdx.input.isKeyJustPressed(Input.Keys.ANY_KEY)) start();
}
}
private void gameOver() {
isGameOver = true;
GameSoundsPlayer.stopMusic(GameAssets.MEMO_SOUND);
GameSoundsPlayer.playMusic(GameAssets.GAME_OVER_SOUND, false);
}
private void start() {
GameSoundsPlayer.playMusic(GameAssets.MEMO_SOUND, false);
GameSoundsPlayer.stopMusic(GameAssets.GAME_OVER_SOUND);
isGameOver = false;
snake.reset();
snake.restoreHealth();
food = board.generateFood();
Scorer.reset();
}
public void render(SpriteBatch batch) {
board.render(batch);
food.draw(batch);
snake.render(batch);
if (isGameOver) {
font.draw(batch, "GAME OVER", (GameInfo.SCREEN_WIDTH - 100) / 2, (GameInfo.SCREEN_HEIGHT + 100) / 2);
font.draw(batch, "Press any key to continue", (GameInfo.SCREEN_WIDTH - 250) / 2, (GameInfo.SCREEN_HEIGHT + 50) / 2);
}
font.draw(batch, "Player: ", GameInfo.SCALE * 4, GameInfo.SCREEN_HEIGHT - 10);
font.draw(batch, "Score: " + Scorer.getScore(), GameInfo.SCALE / 2, GameInfo.SCREEN_HEIGHT - 10);
font.draw(batch, "Size: " + snake.getBody().size(), GameInfo.SCALE / 2, GameInfo.SCREEN_HEIGHT - 40);
}
}
I used Viewport for this!!!
#Override
public void render(float delta) {
clearScreen();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/3);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
Gdx.gl.glViewport(0, Gdx.graphics.getHeight()/3, Gdx.graphics.getWidth(), (Gdx.graphics.getHeight() - Gdx.graphics.getHeight()/3));
game.update(Gdx.graphics.getDeltaTime());
batch.begin();
game.render(batch);
batch.end();
}

Clickable textures

I'm kind of new to LibGdx and android studio.
I'm trying to create clickable textures, one for play and one for credits.
Both should be opening a new empty screen/event.
public void create() {
batch = new SpriteBatch();
img = new Texture("Main_Screen.png");
music = Gdx.audio.newMusic(Gdx.files.internal("bgmusic.wav"));
music.play();
music.setLooping(true);
credits = new Texture("credits.png");
play = new Texture("play.png");
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.draw(play, 340, 1400);
batch.draw(credits, 340, 400);
batch.end();
}
However i'm unsure on how to do this since i'm also creating the background with a texture, so i'd be very happy if someone could assist me with helping me out.
Use Sprite instead of Texture, that holds the geometry, color, and texture information for drawing 2D sprites.
MyGdxGame
public class MyGdxGame extends Game {
public Screen menuScreen,creditsScreen,playScreen;
#Override
public void create () {
menuScreen=new MenuScreen(this);
creditsScreen=new CreditsScreen();
playScreen=new PlayScreen();
setScreen(menuScreen);
}
}
MenuScreen
public class MenuScreen extends InputAdapter implements Screen {
SpriteBatch batch;
Texture background,play,credits;
Sprite backgoundSprite,playSprite,creditsSprite;
private ExtendViewport extendViewport;
OrthographicCamera cam;
private float w=480;
private float h=800;
private Vector3 vector3;
MyGdxGame game;
Music music;
public MenuScreen(MyGdxGame game){
this.game=game;
}
#Override
public void show() {
batch = new SpriteBatch();
cam = new OrthographicCamera();
extendViewport=new ExtendViewport(w,h,cam);
vector3=new Vector3();
background = new Texture("Main_Screen.png");
play=new Texture("play.png");
credits=new Texture("credits.png");
backgoundSprite=new Sprite(background);
backgoundSprite.setSize(w,h); // If resources are not in context of your viewport
backgoundSprite.setPosition(0,0); //Default Position
playSprite=new Sprite(play);
playSprite.setSize(100,100);
playSprite.setPosition(w/2-playSprite.getWidth()/2,h/2+100);
creditsSprite=new Sprite(credits);
creditsSprite.setSize(100,100);
creditsSprite.setPosition(w/2-creditsSprite.getWidth()/2,h/2-100);
Gdx.input.setInputProcessor(this);
music = Gdx.audio.newMusic(Gdx.files.internal("bgmusic.wav"));
music.play();
music.setLooping(true);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(cam.combined);
batch.begin();
backgoundSprite.draw(batch);
playSprite.draw(batch);
creditsSprite.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
extendViewport.update(width,height);
cam.position.x = w /2;
cam.position.y = h/2;
cam.update();
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
vector3.set(screenX,screenY,0);
Vector3 position=cam.unproject(vector3);
if(playSprite.getBoundingRectangle().contains(position.x,position.y)) {
game.setScreen(game.playScreen);
}
if(creditsSprite.getBoundingRectangle().contains(position.x,position.y)){
game.setScreen(game.creditsScreen);
}
return super.touchDown(screenX, screenY, pointer, button);
}
#Override
public void pause() { }
#Override
public void resume() { }
#Override
public void hide() { }
#Override
public void dispose() {
batch.dispose();
background.dispose();
play.dispose();
credits.dispose();
}
}
CreditsScreen
public class CreditsScreen implements Screen {
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
#Override
public void resize(int width, int height) { }
#Override
public void pause() { }
#Override
public void resume() { }
#Override
public void hide() { }
#Override
public void dispose() { }
}
PlayScreen
public class PlayScreen implements Screen {
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
#Override
public void resize(int width, int height) { }
#Override
public void pause() { }
#Override
public void resume() { }
#Override
public void hide() { }
#Override
public void dispose() { }
}
Welcome to libGDX!
If I understand your question correctly, you are trying to figure out how to change screens in your game. At a high level, this is what you'd need to do:
Draw your button texture on the screen.
Use Gdx.input to detect when the player lifts their mouse button (and if it's over one of your buttons when they do it)
Switch to the new screen (presumably with a new background) when this happens.
I would recommend that you first complete the "A Simple Game" and "Extending the Simple Game" tutorials in order to familiarize yourself with the basics of libGDX and the Game and Screen classes.
Next, try using Scene2D.UI (there are links at the bottom of the second tutorial) to add a Stage and TextButtons to your main menu.
Hopefully that helps you get started- there is a lot of helpful information on that libGDX wiki which I think you will find helpful.

Why are my actors not being drawn with the correct bounds in LibGDX?

I have been having a hell of a time trying to get this stage thing figured out. I basically want to draw a background image that fills the entire stage. The image is 1920x1080. The problem is that the image is being drawn at half the width and half of the height that it should be. The application is set to fullscreen and the inside corner of the image is at the center of the screen. I have tested the dimensions of the camera, the viewport, and the stage. All are correct. What am I doing wrong? By the way, I am using a custom game state manager to handle different screens so I apologize for the seemingly needless extra code.
Application.java
public class Application extends ApplicationAdapter {
public static boolean DEBUG = false;
public static final String TITLE = "Hexatan";
public static final int V_WIDTH = 720, V_HEIGHT = 480;
public static final float SCALE = 2.0f;
private GameStateManager gsm;
private OrthographicCamera camera;
private FitViewport vp;
private SpriteBatch batch;
private Stage stage;
private float w, h;
#Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(true, w / SCALE, h / SCALE);
vp = new FitViewport(w, h, camera);
stage = new Stage(vp, batch);
gsm = new GameStateManager(this);
}
#Override
public void render() {
gsm.update(Gdx.graphics.getDeltaTime());
gsm.render();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
gsm.dispose();
batch.dispose();
}
#Override
public void resize(int width, int height) {
gsm.resize((int)(width / SCALE), (int)(height / SCALE));
}
public SpriteBatch getBatch() {
return this.batch;
}
public OrthographicCamera getCamera(){
return this.camera;
}
public Stage getStage(){
return this.stage;
}
}
GameStateManager.java
public class GameStateManager {
private final Application app;
private Stack<GameState> states;
public enum State {
SPLASH, MAINMENU, GAME
}
public GameStateManager(final Application app){
this.app = app;
this.states = new Stack<GameState>();
this.setState(State.GAME);
}
public Application getApp(){
return app;
}
public void update(float delta){
states.peek().update(delta);
}
public void render(){
states.peek().render();
}
public void dispose(){
for(GameState gs : states){
gs.dispose();
}
states.clear();
}
public void resize(int w, int h){
states.peek().resize(w, h);
}
public void setState(State state){
if(states.size() >= 1) {
states.pop().dispose();
}
states.push(getState(state));
}
public GameState getState(State state){
return new GameLoop(this);
}
}
GameState.java
public abstract class GameState {
protected GameStateManager gsm;
protected Application app;
protected SpriteBatch batch;
protected OrthographicCamera camera;
public GameState(GameStateManager gsm){
this.gsm = gsm;
this.app = gsm.getApp();
batch = app.getBatch();
camera = app.getCamera();
}
public void resize(int w, int h){
camera.setToOrtho(true, w, h);
camera.update();
}
public abstract void update(float delta);
public abstract void render();
public abstract void dispose();
}
GameLoop.java
public class GameLoop extends GameState {
private boolean DEV_MODE = true;
private int WIDTH, HEIGHT;
private float mouseX, mouseY;
private Stage stage;
private Game game;
private Application app;
Texture hexture, water, island, robber, highlight, scoreboard;
BitmapFont font = new BitmapFont(Gdx.files.internal("core/assets/Playbill.fnt"));
BitmapFont devFont = new BitmapFont(Gdx.files.internal("core/assets/Arial.fnt"));
public GameLoop(GameStateManager gsm){
super(gsm);
app = gsm.getApp();
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
stage = app.getStage();
System.out.println(stage.getCamera().position.x);
Gdx.input.setInputProcessor(stage);
water = new Texture(Gdx.files.internal("core/assets/img/water.png"));
island = new Texture(Gdx.files.internal("core/assets/img/island.png"));
highlight = new Texture(Gdx.files.internal("core/assets/img/highlightVertex.png"));
scoreboard = new Texture(Gdx.files.internal("core/assets/img/scoreboard.png"));
Image waterImg = new Image(new TextureRegionDrawable(new TextureRegion(water)));
waterImg.setWidth(WIDTH);
waterImg.setHeight(HEIGHT);
stage.addActor(waterImg);
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
app.getStage().act(Gdx.graphics.getDeltaTime());
app.getStage().draw();
}
#Override
public void update(float delta) {
}
#Override
public void dispose() {
}
#Override
public void resize(int w, int h){
camera.setToOrtho(true, w, h);
app.getStage().getViewport().update(w, h, true);
}

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.

Sprite flicker while moving libgdx

This code makes image Border flicker(Flash) while moving left,right,down or up. Why image border flash wile moving even if I use Screen class render() method delta value.
package com.me.mygdxgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
public class MoveSpriteExample extends GdxTest implements InputProcessor {
Texture texture;
SpriteBatch batch;
OrthographicCamera camera;
Vector3 spritePosition = new Vector3();
Sprite sprite;
public void resize (int width, int height) {
}
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
batch = new SpriteBatch();
camera= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.setToOrtho(false, w, h);
texture = new Texture(Gdx.files.internal("data/grasswall.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
sprite = new Sprite(texture);
sprite.setSize(32, 32);
spritePosition.y=100;
sprite.setPosition(spritePosition.x,spritePosition.x);
lastUpdateTime = System.nanoTime();
}
public void Update(float Delta)
{
if (Gdx.input.isKeyPressed(Keys.D)==true)
{
spritePosition.x += 150*(Delta / 1000000000.0);
}else if (Gdx.input.isKeyPressed( Keys.A)==true)
{
spritePosition.x -= 150*(Delta / 1000000000.0);
}
else if (Gdx.input.isKeyPressed( Keys.Z)==true)
{
spritePosition.y -= 150*(Delta / 1000000000.0);
}
else if (Gdx.input.isKeyPressed( Keys.W)==true)
{
spritePosition.y += 150*(Delta / 1000000000.0);
}
}
float lastUpdateTime;
float currentTime;
public void render() {
currentTime = System.nanoTime();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
Update(currentTime - lastUpdateTime);
sprite.setPosition(spritePosition.x,spritePosition.y);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
batch.end();
lastUpdateTime = currentTime;
}
}
pls provide code with sample
As i said in the last post of you, you should take a look at the Tutorial!
First of all you do not need to calculate the delta time yourself. I already postet how you get it in the last post for you.
Ill give you a super short example with a moving sprite without flickering.
At first here is the ApplicationListener. (not a GDXtest)
public class MainClass implements ApplicationListener {
private Screen currentScreen = null;
#Override
public void create() {
Texture.setEnforcePotImages(false);
this.currentScreen = new TestScreen();
}
#Override
public void dispose() {
this.currentScreen.dispose();
}
#Override
public void render() {
this.currentScreen.render(Gdx.graphics.getDeltaTime());
}
#Override
public void resize(int width, int height) {
this.currentScreen.resize(width, height);
}
#Override
public void pause() {
this.currentScreen.pause();
}
#Override
public void resume() {
this.currentScreen.resume();
;
}
}
It's preaty simple and as you can see it does call the render of the screen automatically with the delta time! this.currentScreen.render(Gdx.graphics.getDeltaTime()).
The next thing you need is a simple Screen. So something that does implement the Screeninterface. Id really recommand that you use a Scene2D setup with a stage. But here is an example without.
public class TestScreen implements Screen {
private Sprite mySprite;
private SpriteBatch batch = new SpriteBatch();
public TestScreen() {
this.mySprite = new Sprite(new Texture(
Gdx.files.internal("data/appicon.png")));
this.mySprite.setPosition(50f, 50f);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
this.update(delta);
this.batch.begin();
this.mySprite.draw(batch);
this.batch.end();
}
public void update(float delta) {
if (Gdx.input.isKeyPressed(Keys.D) == true) {
mySprite.setX(mySprite.getX() + 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.A) == true) {
mySprite.setX(mySprite.getX() - 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.Z) == true) {
mySprite.setY(mySprite.getY() - 150 * delta);
} else if (Gdx.input.isKeyPressed(Keys.W) == true) {
mySprite.setY(mySprite.getY() + 150 * delta);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Regardas and do take a look at the tutorial. (Here is again the beginning of it)

Categories

Resources