TextureRegion in ArrayList Won't draw to screen - libgdx

I'm having some issues drawing TextureRegions with a spriteBatch in LibGDX.
So I have a main class that hosts the game logic.
In the constructor, I have:
atlas = new TextureAtlas(Gdx.files.internal("sheet.txt") );
this.loadTileGFX();
the loadTileGFX() method does this:
roseFrames = new ArrayList<AtlasRegion>();
roseFrames.add(atlas.findRegion("Dirt", 0));
roseFrames.add(atlas.findRegion("Dirt", 1));
roseFrames.add(atlas.findRegion("Dirt", 2));
roseFrames.add(atlas.findRegion("Dirt", 3));
Then I pass the arrayList of AtlasRegions into the object:
///in the main class
rsoe = new RoseSquare(roseFrames, st, col, row, tileWidth);
//in the constructor for the object to draw
this.textureRegions = roseFrames;
Then every render() loop I call:
batch.begin();
rose.draw(batch);
batch.end()
The rose.draw() method looks like this:
public void draw(SpriteBatch batch){
batch.draw(this.textureRegions.get(1), rect.x, rect.y, rect.width, rect.height);
}
But the thing is, this doesn't draw anything to the screen.
BUT HERE'S THE THING.
If I change the code to be:
public void draw(SpriteBatch batch){
batch.draw(new TextureAtlas(Gdx.files.internal("sheet.txt")).findRegion("Dirt", 0)), rect.x, rect.y, rect.width, rect.height);
}
Then it draws correctly.
Can anybody shed some light on what error I might have?
Keep in ming I don't get any errors with the "nothing drawn" code.
Also, I can trace the details of this.textureRegions.get(1), and they all are correct....
Thanks.

If you need to draw an array of something that has textures you can do like this:
batch.begin();
for (Ground ground : groundArray){
batch.draw(ground.getTextureRegion(), ground.x, ground.y);
}
batch.end();
As you see i am drawing the TextureRegion here.
You can check related classes and other information in my answers HERE and HERE
Answering drew's comment:
public TextureRegion customGetTextureRegion(int i){
switch(i){
case 1: return atlas.findRegion("dirt1"); break;
case 2: return atlas.findRegion("dirt2"); break;
case 3: return atlas.findRegion("dirt3"); break;
}
}

I have found a solution to my own problem.
I was also drawing some debug ShapeRenderer stuff.
The issue seemed to be that libGDX didn't like a SpriteBatch and a ShapeRenderer to be "on" at the same time:
//LibGDX Doesn't like this:
spriteBatch.begin();
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.drawRect(x, y, width, height);
shapeRenderer.end();
sprtieBatch.draw(texRegion, x, y, width, height);
spriteBatch.end();
It prefers:
//LibGDX likes this:
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.drawRect(x, y, width, height);
shapeRenderer.end();
spriteBatch.begin();
sprtieBatch.draw(texRegion, x, y, width, height);
spriteBatch.end();
Thanks for your responses everyone.

Related

Why camera in stage is not required to be centered in libgdx

How stage camera is able to see full stage view if (0,0) of the camera is located by default at (0,0) of stage. if update method for viewport is not called nor camera position set method is called.
If you look into the Stage Constructor:
public Stage (Viewport viewport, Batch batch) {
if (viewport == null) throw new IllegalArgumentException("viewport cannot be null.");
if (batch == null) throw new IllegalArgumentException("batch cannot be null.");
this.viewport = viewport;
this.batch = batch;
root = new Group();
root.setStage(this);
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
}
We see on the last line viewport.update() with the width, height and true as parameters.
Let's look at this viewport.update() method:
public void update (int screenWidth, int screenHeight, boolean centerCamera) {
apply(centerCamera);
}
Now let's look on the apply() method. We know centerCamera is true:
public void apply (boolean centerCamera) {
HdpiUtils.glViewport(screenX, screenY, screenWidth, screenHeight);
camera.viewportWidth = worldWidth;
camera.viewportHeight = worldHeight;
if (centerCamera) camera.position.set(worldWidth / 2, worldHeight / 2, 0);
camera.update();
}
And here we find the answer: if (centerCamera) camera.position.set(worldWidth / 2, worldHeight / 2, 0);
The stage centered the camera position on her own.

Pixmaps or Textures for dynamicalliy colored graphics in LibGdx?

I was trying to create a dynamic array containing sprites, that created from pixmap textures. I want to give randomly different colors to this array elements also.
None is working.
Then I tried to create a single pixmap. That also shows same behavior.
I created a pixmap in show() like this:
pixmap = new Pixmap(128, 128, Format.RGBA8888);
Pixmap.setBlending(Pixmap.Blending.None);
pixmap.setColor(128, 0, 0, 1f);
pixmap.fillCircle(64, 64, 64);
texture = new Texture(pixmap);
pixmap.dispose();
in render()
sprite = new Sprite(texture);
sprite.setPosition(b.getX()-sprite.getWidth()/2, b.getY()-sprite.getHeight()/2);
sprite.draw(batch);
Whenever I give an rgb color code, it gives either some different colors or black as output. Tried hex code also.
What wrong I did here?
Previousely I used pixmaps as overlay and single texture etc. But did not go deep in to it and tried.
Here, I planned to draw filled circles with pixmap, instead of using graphics. Because my game elements are very simple filled circles and more than 10 colors I should implement.
These circle objects will be generated dynamically throughout the game.
Now I am wondering what I planned to do will be effective with pixmaps. No exapmples I found on net.
Is it possible to create dynamic array with different colored objects?
Or using graphics is the better option compared to pixmaps?
It would be very helpful if I get suggestions from experienced persons.
r,g,b,a values should be in range from 0f to 1f. And it's bad to create new sprites in render(), since it's called every frame.
I'll try to answer your questions with this small code sample (left comments in the code):
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch spriteBatch;
Pixmap pixmap;
Texture texture;
Array<Sprite> sprites = new Array<Sprite>();
#Override
public void create() {
spriteBatch = new SpriteBatch();
// you should use only one Pixmap object and one Texture object
pixmap = new Pixmap(128, 128, Pixmap.Format.RGBA8888);
pixmap.setBlending(Pixmap.Blending.None);
pixmap.setColor(Color.WHITE);
pixmap.fillCircle(64, 64, 64);
texture = new Texture(pixmap);
pixmap.dispose();
// generate sprites with different colors
// r,g,b,a values should be in range from 0f to 1f
addCircleSprite(128f / 255f, 0f, 0f, 1f);
addCircleSprite(0.4f, 0.2f, 0.5f, 1f);
addCircleSprite(0.6f, 0f, 1f, 1f);
addCircleSprite(0.3f, 0.8f, 1f, 1f);
addCircleSprite(0.1f, 1f, 1f, 1f);
}
void addCircleSprite(float r, float g, float b, float a) {
// every sprite references on the same Texture object
Sprite sprite = new Sprite(texture);
sprite.setColor(r, g, b, a);
// I just set random positions, but you should handle them differently of course
sprite.setCenter(
MathUtils.random(Gdx.graphics.getWidth()),
MathUtils.random(Gdx.graphics.getHeight()));
sprites.add(sprite);
}
#Override
public void render() {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
for (Sprite sprite : sprites) {
sprite.draw(spriteBatch);
}
spriteBatch.end();
}
#Override
public void dispose() {
texture.dispose();
}
}
also read this Q/A. I guess you could load your Texture object from .png file with white circle:
texture = new Texture("whiteCircle.png");
but creating Pixmap circle with only 64 pixels in radius (and then creating a Texture from it) is ok too, shouldn't make much difference.
setColor() takes r, g, b, a parameters to convert it to rgba8888 format -
public void setColor (float r, float g, float b, float a) {
color = Color.rgba8888(r, g, b, a);
}
So set r, g, b and alpha component as floats in the range [0,1].
use
pixmap.setColor(128f/255, 0, 0, 1f);
instead of
pixmap.setColor(128, 0, 0, 1f);
If you want to use hex then -
Color color = new Color(0x000000a6) //(Black with 65% alpha).

LWJGL/OpenGL -- Not drawing basic quad

I have looked everywhere, and I can't seem to get OpenGL to draw a simple quad.
The window shows up fine with the correct color background, but OpenGL just won't draw the box.
I am using OpenGL 4.4.0 - Build 20.19.15.4463
The window size is 1920x1080
This is the code I currently have:
in Main.java:
public void init(){
if(glfwInit() != true){
System.err.println("GLFW failed to initialize");
}
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
//TODO change name.
window = glfwCreateWindow(width, height, "GameName", NULL, NULL);
if(window == NULL){
System.err.println("Window failed to be created");
}
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, 100, 100);
glfwMakeContextCurrent(window);
glfwShowWindow(window);
GL.createCapabilities();
glClearColor(0.0f, 0.5f, 1.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
//set up projection matrix; allows us to draw.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
testBox = new EntityBox(3, Color.RED);//just to test right now
System.out.println("OpenGL: "+ glGetString(GL_VERSION));
}
public void update(){
glfwPollEvents();
}
public void render(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glfwSwapBuffers(window);
testBox.draw();
}
in EntityBox:
public void draw(){
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2f(0,0);
glVertex2f(0,100);
glVertex2f(100,0);
glVertex2f(100,100);
glEnd();
}
I fixed it:
glClear needs to be
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
don't know why, because i was tole depth_buffer is used if you want 3d.
and
glfwSwapBuffers(window);
needs to be called after drawing.

How to make a sprite blink X seconds?

I'm using libGDX and I want to make my main character of my game to blinking x seconds on enemy touch (lose life)
Can someone tell me how can I make sprite to blinding?
Here is my solution, I use it exactly for the same purpose you described (blinking character when he injured).
public class Blinker {
private float BLINK_TIME = 1f;
private int BLINKING_FRAMES = 4;
private boolean isBlinking;
private int blinkFrameCounter;
private float blinkTimer;
public Blinker() {
this.blinkTimer = 0;
this.blinkFrameCounter = 0;
this.isBlinking = false;
}
public boolean shouldBlink(float delta) {
if (isBlinking) {
blinkTimer += delta;
blinkFrameCounter++;
if (blinkTimer < BLINK_TIME) {
if (blinkFrameCounter % BLINKING_FRAMES == 0) {
return true;
}
} else {
blinkTimer = 0;
isBlinking = false;
}
}
return false;
}
public boolean isBlinking() {
return isBlinking;
}
public void setBlinking(boolean isBlinking) {
this.isBlinking = isBlinking;
}
}
Usage:
first init the blinker object;
Blinker blinker= new Blinker();
blinker.setBlinking(true);
and then just add this to your draw() method (I suppose that you have separate method for drawing character, which you call in your screen draw method), before you draw the sprite you want to blink.
if (blinker.shouldBlink(delta))
return;
I recommend looking at something like this.
https://github.com/libgdx/libgdx/wiki/2D-Animation
You use this technique and adjust the frame duration.
walkAnimation = new Animation(0.025f, walkFrames); // #11
When you need to start making the animation blink faster. adjust the frame duration value.
public void setFrameDuration(float frameDuration)
I recommend doing it this way but if you HAVE to tint it w/e.... I guess this works.
private Texture texture;
private TextureRegion region;
private Sprite sprite;
...
texture = new Texture(Gdx.files.internal("image.png"));
region = new TextureRegion(texture, 20, 20, 50, 50);
sprite = new Sprite(texture, 20, 20, 50, 50);
sprite.setPosition(100, 10);
sprite.setColor(0, 0, 1, 1);
...
batch.begin();
batch.setColor(1, 0, 0, 1);
batch.draw(texture, 10, 10);
batch.setColor(0, 1, 0, 1);
batch.draw(region, 50, 10);
sprite.draw(batch);
batch.end();
key thing is Alpha is ignored if blending is disabled.
The previous answer from prgenhard will work, but I don't think that is sufficient enough, if you are using it without care.
You can use TweenEngine to interpolate alpha value with different functions.
It can be really cool.
Those values you can set on sprite's or actor's alpha and easily achieve flashing effect.
You can read more about it here:
http://www.aurelienribon.com/blog/projects/universal-tween-engine/
It should be enough.
And also it can be easily used within Libgdx engine.
Hope this helps.

Libgdx: screen resize and ClickListener (libgdx)

I develope a 2D game and use OrthographicCamera and Viewport to resize virtaul board to real display size. I add images to stage and use ClickListener to detect clicks. It works fine, but when I change resolution it works incorrent(can't detect correct actor, I think the problem with new and original x and y). Is there any way to fix this?
You will need to translate the screen coordinates to world coordinates.
Your camera can do that. You can do both ways, cam.project(...) and cam.unproject(...)
Or if you are already using Actors, don't initialize a camera yourself, but use a Stage. Create a Stage and add the actors to it. The Stage will then do coordinate translation for you.
Once me too suffered from this problem but at end i got the working solution, for drawing anything using SpriteBatch or Stage in libgdx. Using orthogrphic camera we can do this.
first choose one constant resolution which is best for game. Here i have taken 1280*720(landscape).
class ScreenTest implements Screen{
final float appWidth = 1280, screenWidth = Gdx.graphics.getWidth();
final float appHeight = 720, screenHeight = Gdx.graphics.getHeight();
OrthographicCamera camera;
SpriteBatch batch;
Stage stage;
Texture img1;
Image img2;
public ScreenTest(){
camera = new OrthographicCamera();
camera.setToOrtho(false, appWidth, appHeight);
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.combined);
img1 = new Texture("your_image1.png");
img2 = new Image(new Texture("your_image2.png"));
img2.setPosition(0, 0); // drawing from (0,0)
stage = new Stage(new StretchViewport(appWidth, appHeight, camera));
stage.addActor(img2);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
stage.act();
stage.act(delta);
stage.draw();
// Also You can get touch input according to your Screen.
if (Gdx.input.isTouched()) {
System.out.println(" X " + Gdx.input.getX() * (appWidth / screenWidth));
System.out.println(" Y " + Gdx.input.getY() * (appHeight / screenHeight));
}
}
//
:
:
//
}
run this code in Any type of resolution it will going to adjust in that resolution without any disturbance.
I just think Stage is easy to use.
If there are some wrong,i consider you should check your code:
public Actor hit(float x, float y)