2015-09-18 2 views
3

Я пытался выяснить это наши за 6 часов, как сейчас ... У меня есть 2 классов (Player и UiButton), оба из них extends Sprite. Проблема заключается в том, что Sprite от игрока оказывает и один из UIButton не.LibGDX - Sprite из пользовательского класса не отображается

Вот, взгляните на код:

Player.java (упрощенный)

public class Player extends Sprite 
{ 
    public Player(float posX, float posY) 
    { 
     super(new Texture(Gdx.files.internal("character/char_idle.png"))); 
     super.setPosition(posX, posY); 
    } 
} 

UiButton.java

import com.badlogic.gdx.Gdx; 
import com.badlogic.gdx.graphics.Texture; 
import com.badlogic.gdx.graphics.g2d.Sprite; 

public class UiButton extends Sprite 
{ 
    public UiButton(Texture texture, float posX, float posY, float rotation) 
    { 
     super(new Texture(Gdx.files.internal("ui/arrow.png"))); 

     setPosition(posX, posY); 
     setRotation(rotation); 
    } 

    public UiButton(UiButton button) 
    { 
     super(); 
    } 

    public void setSize(float toWidth, float toHeight) 
    { 
     float scaleX = toWidth/super.getWidth(); 
     float scaleY = toHeight/super.getHeight(); 

     setScale(scaleX, scaleY); 
    } 

    public boolean isTouched(int touchX, int touchY) 
    { 
     if(touchX >= getX() && touchX <= getX() + getWidth()) 
      if(touchY >= getY() && touchY <= getY() + getHeight()) 
       return true; 

     return false; 
    } 

} 

GameEngine.java (не весь файл, а требуемые функции и переменные)

public class GameEngine extends ApplicationAdapter implements ApplicationListener 
{ 
    private SpriteBatch spriteBatch; 
    private Player  player; 
    private Sprite  grid; 

    private UiButton arrow_right; 
    private UiButton arrow_left; 
    private UiButton arrow_down; 
    private UiButton arrow_up; 

    @Override public void create() 
    { 
     /** Setting InputProcessor **/ 
     InitializeInputProcessor(); 

     /** Initializing SpriteBatch **/ 
     spriteBatch = new SpriteBatch(); 
     spriteBatch.maxSpritesInBatch = 10; 

     /** Creating UI **/ 
     GenerateUiArrows(10, Gdx.graphics.getHeight()/4); 

     /** Creating Player **/ 
     player = new Player(100, 100); 

     /** Creating background grid **/ 
     grid = new Sprite(new Texture(generateGrid(50))); 
    } 

    @Override public void dispose() 
    { 
     spriteBatch.dispose(); 
    } 

    public void doUpdating() 
    { 
     player.update(); 
    } 

    public void doRendering() 
    { 
     /** Clearing the screen **/ 
     Gdx.gl.glClearColor(1, 1, 1, 1); 
     Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 

     /** Beginning SpriteBatch rendering **/ 
     spriteBatch.begin(); 

     /** Drawing background grid **/ 
     grid.draw(spriteBatch); 

     /** Drawing Player **/ 
     player.draw(spriteBatch); 

     /** Drawing UI **/ 
     arrow_right.draw(spriteBatch); 
     arrow_left.draw(spriteBatch); 
     arrow_down.draw(spriteBatch); 
     arrow_up.draw(spriteBatch); 

     /** Ending SpriteBatch rendering **/ 
     spriteBatch.end(); 
    } 

    @Override public void render() 
    { 
     doUpdating(); 
     doRendering(); 

     /******************************************/ 
     /** Here was a loop to control framerate **/ 
     /******************************************/ 
    } 

    private Pixmap generateGrid(int interval) 
    { 
     /** Creating temporary Pixmap **/ 
     Pixmap tempMap = new Pixmap(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), Pixmap.Format.RGBA8888); 

     /** Setting lines color to BLACK **/ 
     tempMap.setColor(Color.BLACK); 

     /** Creating horizontal lines **/ 
     for(int i = interval; i < Gdx.graphics.getWidth(); i += interval) 
      tempMap.drawLine(i, 0, i, Gdx.graphics.getHeight()); 

     /** Creating vertical lines **/ 
     for(int i = interval; i < Gdx.graphics.getHeight(); i += interval) 
      tempMap.drawLine(0, i, Gdx.graphics.getWidth(), i); 

     /** Returning the result **/ 
     return tempMap; 
    } 

    private void GenerateUiArrows(float padding, float button_size) 
    { 
     arrow_right = new UiButton(new Texture(Gdx.files.internal("ui/arrow.png")), button_size * 2 + padding * 3, padding, 90); 
     arrow_right.setSize(button_size, button_size); 

     arrow_left = new UiButton(new Texture(Gdx.files.internal("ui/arrow.png")), padding, padding, 270); 
     arrow_left.setSize(button_size, button_size); 

     arrow_down = new UiButton(new Texture(Gdx.files.internal("ui/arrow.png")), button_size + padding * 2, padding, 180); 
     arrow_down.setSize(button_size, button_size); 

     arrow_up = new UiButton(new Texture(Gdx.files.internal("ui/arrow.png")), button_size + padding * 2, button_size + padding * 2, 0); 
     arrow_up.setSize(button_size, button_size); 
    } 

} 

Не отображается никаких ошибок или предупреждений. Только UiButtons не отображаются. Я еще не установил OrthographicCamera. Так что это не должно быть так как ...

+0

Вы можете оставить свой 'arrow.png' образ ?, Я хотел бы начать с размещения ваших кнопок в то же положение вашего игрока –

+0

http://i.imgur.com/VBW99je.png - the arrow.png. И я попытался установить ту же позицию, что и игрок ... – Sw3das

+0

попробуйте удалить вращение или 'setOriginCenter()' перед вращением –

ответ

3

ваша проблема в SetSize() метод в классе UIButton:

public void setSize(float toWidth, float toHeight) 
    { 
     //System.out.println("super.width = " + super.getWidth() + ", super.height = " + super.getHeight()); - you can uncomment it to see the super width/height value in the console 

     float scaleX = toWidth/super.getWidth(); 
     float scaleY = toHeight/super.getHeight(); 

     setScale(scaleX, scaleY); 
    } 

Оба super.getWidth() и super.getHeight() возвращает ZERO (потому что вы не задали ширину/высоту для объекта суперкласса). Затем в переменных scaleX/scaleY у вас есть infinity value - вы можете увидеть это, раскомментируя отмеченную строку в моем коде.

Самое смешное в том, что Java позволяет разделить плавающий нуль - возвращение упоминается бесконечность значения (read more here), и именно поэтому вы не исключение, там.

Решение должно исправить этот метод, вызвав super.setSize (ширина, высота) или просто удалить его вообще и опираться на реализацию метода setSize() класса Sprite по умолчанию.


Ещё одна вещь - после устранения проблемы вы будете наблюдать проблемы с вращением - это о происхождении. Вы можете просто изменить вас SetSize метод

@Override 
    public void setSize(float w, float h) 
    { 
     super.setSize(w,h); 

     setOrigin(w/2f, h/2f); 
    } 

, и он будет делать то, что

enter image description here

+0

Спасибо, вы спасли мой день: D Похоже, я случайно переоценил метод setSize() ... Еще раз спасибо за заботясь об этом! – Sw3das

+0

О, и ... Есть ли в libGDX опоры на 90 и 270 градусов? Поскольку 90 градусов должны вращать стрелку так, чтобы она указывала на право: / – Sw3das

Смежные вопросы