Rotate OrthographicCamera from a point (LibGdx) - java

I am studying the example of Orthographic Camera of wiki libgdx :
https://github.com/libgdx/libgdx/wiki/Orthographic-camera#description
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
public class OrthographicCameraExample implements ApplicationListener {
static final int WORLD_WIDTH = 100;
static final int WORLD_HEIGHT = 100;
private OrthographicCamera cam;
private SpriteBatch batch;
private Sprite mapSprite;
private float rotationSpeed;
#Override
public void create() {
rotationSpeed = 0.5f;
mapSprite = new Sprite(new Texture(Gdx.files.internal("sc_map.png")));
mapSprite.setPosition(0, 0);
mapSprite.setSize(WORLD_WIDTH, WORLD_HEIGHT);
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
// Constructs a new OrthographicCamera, using the given viewport width and height
// Height is multiplied by aspect ratio.
cam = new OrthographicCamera(30, 30 * (h / w));
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
cam.update();
batch = new SpriteBatch();
}
#Override
public void render() {
handleInput();
cam.update();
batch.setProjectionMatrix(cam.combined);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
mapSprite.draw(batch);
batch.end();
}
private void handleInput() {
if (Gdx.input.isKeyPressed(Input.Keys.A)) {
cam.zoom += 0.02;
}
if (Gdx.input.isKeyPressed(Input.Keys.Q)) {
cam.zoom -= 0.02;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
cam.translate(-3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
cam.translate(3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
cam.translate(0, -3, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
cam.translate(0, 3, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.W)) {
cam.rotate(-rotationSpeed, 0, 0, 1);
}
if (Gdx.input.isKeyPressed(Input.Keys.E)) {
cam.rotate(rotationSpeed, 0, 0, 1);
}
cam.zoom = MathUtils.clamp(cam.zoom, 0.1f, 100/cam.viewportWidth);
float effectiveViewportWidth = cam.viewportWidth * cam.zoom;
float effectiveViewportHeight = cam.viewportHeight * cam.zoom;
cam.position.x = MathUtils.clamp(cam.position.x, effectiveViewportWidth / 2f, 100 - effectiveViewportWidth / 2f);
cam.position.y = MathUtils.clamp(cam.position.y, effectiveViewportHeight / 2f, 100 - effectiveViewportHeight / 2f);
}
#Override
public void resize(int width, int height) {
cam.viewportWidth = 30f;
cam.viewportHeight = 30f * height/width;
cam.update();
}
#Override
public void resume() {
}
#Override
public void dispose() {
mapSprite.getTexture().dispose();
batch.dispose();
}
#Override
public void pause() {
}
public static void main(String[] args) {
new LwjglApplication(new OrthographicCameraExample());
}
}
On the rotation of the camera, map is rotated with the camera at the midpoint of the screen. I would like to rotate the camera from a certain point. For example, the point 0,0 . I tried to use the method rotateAround ( Vector3 point , Vector3 axis , float angle) , I did not get the expected result.
cam.rotateAround(new Vector3(0,0,0), new Vector3(0,0,1), 1);
I know it's possible to move the camera to the point 0.0 and then rotate . But that's not what I want .
In the game I'm doing the player is in a fixed position at the bottom of the screen in the middle and I turned the screen around it , but without taking the player to the middle of the screen and then rotate .
I appreciate the help .

You just need to update camera after cam.rotateround :)
It works for me.
cam.rotateAround(new Vector3(270, 0, 0), new Vector3(0, 0, 1), 0.1f);
cam.update();
Here is a screenshot of my test. As you can see screen rotating around red dot. (Perspective camera is also rotating around same point that in its own coordinate.)
Also i suggest you to use
cam.setToOrtho(false, cam.viewportWidth, cam.viewportHeight);
instead of
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);

Related

could not add an image in the right place [duplicate]

I have an issue in LibGDX where when i call upon Gdx.input.getY(), it selects a pixel that's on the other side of the application relative to the center of the screen.
public class Main extends ApplicationAdapter {
private SpriteBatch batch;
private Texture img;
private OrthographicCamera camera;
int xPos;
int yPos;
private Vector3 tp = new Vector3();
BitmapFont font;
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("crosshair.png");
camera = new OrthographicCamera();
camera.setToOrtho(false, 1280, 720);
font = new BitmapFont();
}
#Override
public void render () {
yPos = Gdx.input.getY();
xPos = Gdx.input.getX();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.unproject(tp.set(xPos, yPos, 0));
batch.begin();
font.draw(batch,xPos + " , " + yPos, Gdx.input.getX() - 25, Gdx.input.getY() - 5);
batch.draw(img, xPos, yPos);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
img.dispose();
}
Subtracting the viewport height with the touch location won't work, because that would be subtracting world coordinates with touch coordinates. (and even for a pixel perfect projection it would be height - 1 - y). Instead use the unproject method to convert touch coordinates to world coordinates.
There are two problems with your code:
You are never setting the batch projection matrix.
Even though you are using the unproject method, you are never using its result.
So instead use the following:
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
camera.unproject(tp.set(Gdx.input.getX(), Gdx.input.getY(), 0));
font.draw(batch,tp.x+ " , " + tp.y, tp.x - 25, tp.y - 5);
batch.draw(img, tp.x, tp.y);
batch.end();
}
I would suggest to read the following pages, which describe this and the reasoning behind it in detail:
https://github.com/libgdx/libgdx/wiki/Coordinate-systems
https://xoppa.github.io/blog/pixels/
https://github.com/libgdx/libgdx/wiki/Viewports
It's better to try this
yPos = camera.viewportHeight - Gdx.input.getY();

Why is my background image stretched out in libGDX?

This is my first try in libGDX and I've not seen an issue like this before, googling didn't help either. What I'm trying to to display a background, Later on I'll make this move, but for me it was a great start to actually display the image. It displays, but it's streched out (See picture below)
And my code is:
private BombArrangement game;
private OrthographicCamera gameCamera;
private Viewport gamePort;
private Texture backGroundTexture;
public PlayScreen(BombArrangement game) {
this.game = game;
gameCamera = new OrthographicCamera();
gamePort = new FitViewport(BombArrangement.V_WIDTH, BombArrangement.V_HEIGHT, gameCamera);
backGroundTexture = new Texture("startbackground.png");
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.batch.draw(new TextureRegion(backGroundTexture, 0, 0, BombArrangement.V_WIDTH, BombArrangement.V_HEIGHT), 0, 0);
game.batch.end();
}
#Override
public void resize(int width, int height) {
gamePort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
I tried several things like textureregions, sprites and more but all of them give this result.
not exactly sure what your want to do but i use this to render my background in my main menu:
//Camera
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//Viewport
ScreenViewport viewport = new ScreenViewport(camera);
//Background
backgroundImage = new Texture(pathToImage);
//Stage
stage = new Stage();
stage.setViewport(viewport);
(this is located in my constructor and camera, backgroundImage and stage are fields in my class)
in render method
(ConfigData holds data of settings applied to the game; DEFAULT_WIDHT and -HEIGHT are just some values I use to initialize the window when not in fullscreen mode; Replace them with your values used in the DesktopLauncher for
config.widht
and
config.height
):
#Override
public void render(float delta) {
//Clear screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.getBatch().begin();
stage.getBatch().draw(backgroundImage, 0, 0, ConfigData.DEFAULT_WIDTH, ConfigData.DEFAULT_HEIGHT);
stage.getBatch().end();
stage.draw();
}
my resize method:
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
stage.getViewport().update(width, height);
}
hopes this helps somehow someone because i figured out this by myself and it costed some effort (:
As a response to your last comment:
You are now scaling down the height correctly but the width remains the same. Try to multiply the width by the same amount you scale the height down, so with some alterations to the code you linked in the comment (not tested):
private Texture texture;
private int x1, x2, speed, scaledHeight, scaledWidth;
public StartBackground() {
texture = new Texture("startbackground.png");
x1 = 0;
x2 = texture.getWidth();
speed = 5;
float imageRatio = Gdx.graphics.getHeight() / texture.getHeight();
scaledHeight = (int) (texture.getHeight() * imageRatio);
scaledWidth = (int) (texture.getWidth() * imageRatio);
}
public void updateAndRender(float deltaTime, SpriteBatch spriteBatch) {
x1 -= speed;
x2 -= speed;
// If image is off screen and not visible
if (x1 + texture.getWidth() <= 0) x1 = x2 + texture.getWidth();
if (x2 + texture.getWidth() <= 0) x2 = x1 + texture.getWidth();
// Render
spriteBatch.draw(texture, x1, 0, scaledWidth, scaledHeight);
spriteBatch.draw(texture, x2, 0, scaledWidth, scaledHeight);
}

OpenGL glColor3f(r, b, g) while drawing Quads changes colour of whole map

I'm currently trying to make a game(Java, lwjgl, OpenGL) so that I can get a basic understanding of the how a top down RPG game works(i.e. in learning process). Recently, I tried to implement a healthbar that would hover over the player's sprite, but when I tried to draw it through my Draw class, the display goes haywire and almost everything except the player turn black, while the player sprite itself gets tinted the color passed(in R, G, B) to the Draw method.
The Source Code:
Player Class
package GameObjects;
import Graphics.ImageLoader;
import java.awt.Rectangle;
import java.util.ArrayList;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import org.newdawn.slick.opengl.Texture;
import rpgmain.*;
/**
*
* #author Samsung
*/
public class Player extends GameObject{
private float velX, velY;
private int curHealth, maxHealth;
private Texture tex;
public Player(float x, float y, ObjectId id) {
super(x, y, id);
velX = velY = 0;
curHealth = maxHealth = 100;
tex = ImageLoader.loadTexture("Player", "png");
}
protected void update(ArrayList<GameObject> objects) {
x += velX;
y += velY;
Collisions(objects);
}
protected void render() {
Draw.rect(x, y, 32, 32, tex);
dispHealth();
}
public void Collisions(ArrayList<GameObject> objects) {
for(GameObject obj : objects) {
if(obj.getId() == ObjectId.WaterTile) {
if(Collision.checkCollision(getBoundsTop(), obj.getBounds())) {
velX = velY = 0;
y = obj.getY() - 32;
}
if(Collision.checkCollision(getBoundsBottom(), obj.getBounds())) {
velX = velY = 0;
y = obj.getY() + 32;
}
if(Collision.checkCollision(getBoundsLeft(), obj.getBounds())) {
velX = velY = 0;
x = obj.getX() + 32;
}
if(Collision.checkCollision(getBoundsRight(), obj.getBounds())) {
velX = velY = 0;
x = obj.getX() - 32;
}
}
}
}
public void dispHealth() {
Draw.rect(x, y + 34, 10, 5, 1F, 0F, 0F); //THIS CODE TINTS THE PLAYER RED
}
public void setVelX(float velX) {
this.velX = velX;
}
public void setVelY(float velY) {
this.velY = velY;
}
public Rectangle getBounds() {
return new Rectangle((int)x, (int) y, 32, 32);
}
public Rectangle getBoundsTop() {
return new Rectangle((int)x + 7, (int) y + 26, 16, 6);
}
public Rectangle getBoundsBottom() {
return new Rectangle((int)x + 7, (int) y, 16, 6);
}
public Rectangle getBoundsLeft() {
return new Rectangle((int)x + 4, (int) y, 1, 32);
}
public Rectangle getBoundsRight() {
return new Rectangle((int)x + 31, (int) y, 1, 32);
}
public Rectangle getBoundsCentre() {
return new Rectangle((int)x + 20, (int) y, 4, 32);
}
}
Draw Class
package rpgmain;
import static org.lwjgl.opengl.GL11.*;
import org.newdawn.slick.opengl.*;
/**
*
* #author Samsung
*/
public class Draw {
public static void rect(float x, float y, float width, float height, Texture tex) {
glTranslatef(x, y, 0);
//glColor3f(1F, 1F, 1F);
glClearColor(0.7f, 0.7f, 0.7f, 1.0f);
tex.bind();
glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
{
//PNG format for images
glTexCoord2f(0,1); glVertex2f(0, 0); //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
glTexCoord2f(0,0); glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
glTexCoord2f(1,0); glVertex2f(width, height);
glTexCoord2f(1,1); glVertex2f(width, 0);
}
glEnd();
}
public static void rect(float x, float y, float width, float height, Texture tex, float r, float g, float b) {
glTranslatef(x, y, 0);
glColor3f(r, g, b);
tex.bind();
glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
{
glTexCoord2f(0,0); glVertex2f(0, 0); //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
glTexCoord2f(0,1); glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
glTexCoord2f(1,1); glVertex2f(width, height);
glTexCoord2f(1,0); glVertex2f(width, 0);
}
glEnd();
}
public static void rect(float x, float y, float width, float height, float r, float g, float b) {
glTranslatef(x, y, 0);
glColor3f(r, g, b); //Problem seems to be here
glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
{
glVertex2f(0, 0); //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
glVertex2f(width, height);
glVertex2f(width, 0);
}
glEnd();
}
}
I don't know whether to include other classes as well,but I guess I'll include the GameObject class as well.
GameObject Class
package rpgmain;
import java.awt.Rectangle;
import java.util.ArrayList;
/**
*
* #author Samsung
*/
public abstract class GameObject {
protected float x, y;
ObjectId id;
public GameObject(float x, float y, ObjectId id) {
this.x = x;
this.y = y;
this.id = id;
}
protected abstract void update(ArrayList<GameObject> objects);
protected abstract void render();
public abstract Rectangle getBounds();
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public ObjectId getId() {
return id;
}
}
I figured it out. There where two main problems with my code, ll in the Draw class.
GL_TEXTURE_2D
I disabled this using glDisable(GL_Texture_2D) every time I started drawing a a normal non textured rectangle, and enabled it after I was done, and did the reverse in the texture drawing method (i.e. enable before start drawing, disable after finish). This resulted in the health bar actually showing up.
glColor3f(r, g, b);
This is the actual problem of the question. The rectangle ended up tinting every texture on the display because I did not know that glColor3f affects every Vertex you draw. So to tackle this, before drawing a textured QUAD, I set it's color to white first(using glColor4f(1f, 1f, 1f, 1f);) and everything rendered perfectly.
The changes:
public static void rect(float x, float y, float width, float height, Texture tex) {
glEnable(GL_TEXTURE_2D);
glTranslatef(x, y, 0);
glColor4f(1f, 1f, 1f, 1f); //NEEDS to be white before drawing, else stuff will tint.
tex.bind();
glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
{
//PNG format for images
glTexCoord2f(0,1); glVertex2f(0, 0); //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
glTexCoord2f(0,0); glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
glTexCoord2f(1,0); glVertex2f(width, height);
glTexCoord2f(1,1); glVertex2f(width, 0);
}
glEnd();
glDisable(GL_TEXTURE_2D);
}

Android problems with Viewport

When i run the game in Desktop works fine, but when i run it in my android device, the image looks cuted in a half and when i use the PLAY button the game closes, anyone can help me? thank you.
public class GameScreen extends AbstractScreen {
private Viewport viewport;
private Camera camera;
private SpriteBatch batch;
private Texture texture;
private float escala;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void create(){
camera = new PerspectiveCamera();
viewport = new FitViewport(800, 480, camera);
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont();
font.setColor(Color.WHITE);
font.setScale(1f);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
escala = width / widthImage;
if(Gdx.app.getType()== ApplicationType.Android)
viewport.update(width, height);
}
}
Firstly, use an orthograpic camera.
camera=new OrthographicCamera(800,480);
camera.position.set(800/2f,480/2f,0);
viewport=new FitViewport(800,480,camera);
Now 0,0 is in the left bottom corner of your screen.
And before doing batch.begin don't forget to set your projection matrix
batch.setProjectionMatrix(camera.combined);
batch.begin();
////
////
batch.end();

Is it possible to draw more than one object using OpenGL ES 2.0

This is an update to a question I recently asked, but with new problems after I tried some stuff. What I want is to draw multiple circles on the screen. I created a class for the circle object. In my renderer class, I created an array list of these circles each with a different position. When called to draw, it only draws one of them. I logged what was going on and each object is being called to get drawn, but it seems only one appears on the screen. It's not just my circles. It appears throughout personal testing OpenGL ES 2.0 will only draw one object on the screen. I have no idea how to fix this. Is there something special I have to do in OpenGL ES 2.0? Here is my code. Ignore the incredibly sloppy and inefficient code right now. I am aware of it and will fix it later. Here is my circle object class:
GLCircle:
package com.background.gl.objects;
import static android.opengl.GLES20.GL_TRIANGLE_FAN;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.Matrix.multiplyMM;
import static android.opengl.Matrix.setIdentityM;
import static android.opengl.Matrix.translateM;
import static com.background.gl.glcirclebackgroundanimation.Constants.BYTES_PER_FLOAT;
import java.util.Random;
import android.opengl.Matrix;
import android.util.Log;
import com.background.gl.data.VertexArray;
import com.background.gl.helper.TextureShaderProgram;
public class GLCircle {
private static final int POSITION_COMPONENT_COUNT = 2;
private static final int TEXTURE_COORDINATES_COMPONENT_COUNT = 2;
private static final int STRIDE = (POSITION_COMPONENT_COUNT
+ TEXTURE_COORDINATES_COMPONENT_COUNT) * BYTES_PER_FLOAT;
public float x;
public float y;
protected float[] wallBounds;
protected boolean positiveX, positiveY;
public boolean nullify;
protected float xCounter = 0f;
protected float yCounter = 0f;
public float[] bounds;
protected Random ran;
private float[] VERTEX_DATA = {
// Order of coordinates: X, Y, S, T
// Triangle Fan
0f, 0f, 0.5f, 0.5f,
-0.25f, -0.25f, 0f, 0.9f,
0.25f, -0.25f, 1f, 0.9f,
0.25f, 0.25f, 1f, 0.1f,
-0.25f, 0.25f, 0f, 0.1f,
-0.25f, -0.25f, 0f, 0.9f };
private final VertexArray vertexArray;
public GLCircle(float x, float y) {
vertexArray = new VertexArray(VERTEX_DATA);
ran = new Random();
wallBounds = new float[4];
nullify = false;
this.x = x;
this.y = y;
}
public void bindData(TextureShaderProgram textureProgram) {
//Bind the position data to the shader attribute
vertexArray.setVertexAttribPointer(
0,
textureProgram.getPositionAttributeLocation(),
POSITION_COMPONENT_COUNT,
STRIDE);
//Bind the texture coordinate data to the shader attribute
vertexArray.setVertexAttribPointer(
POSITION_COMPONENT_COUNT,
textureProgram.getTextureCoordinatesAttributeLocation(),
TEXTURE_COORDINATES_COMPONENT_COUNT,
STRIDE);
}
public void drawCircle() {
glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
}
public float getX() {
return this.x;
}
public float getY() {
return this.y;
}
public boolean isPositiveX() {
return positiveX;
}
public boolean isPositiveY() {
return positiveY;
}
public float[] getBounds(float ranX, float ranY) {
if(!positiveX) {
/*if(ranX >= 0f) {
wallBounds[0] = 1.05f + ranX;
} else {*/
this.wallBounds[0] = 1.05f + ranX;
//}
} else {
/*
if(ranX >= 0f) {
wallBounds[0] = 1.05f - ranX;
} else {*/
this.wallBounds[1] = 1.05f - ranX;
//}
}
if(!positiveY) {
this.wallBounds[2] = 1.75f + ranY;
} else {
this.wallBounds[3] = 1.75f - ranY;
}
return this.wallBounds;
}
public void setPos(float[] modelMatrix,
float[] projectionMatrix, TextureShaderProgram textureProgram,
int texture, float x, float y, String log) {
setIdentityM(modelMatrix, 0);
translateM(modelMatrix, 0, 0f, 0.01f, 0f);
final float[] temp = new float[16];
multiplyMM(temp, 0, projectionMatrix, 0, modelMatrix, 0);
System.arraycopy(temp, 0, projectionMatrix, 0, temp.length);
textureProgram.useProgram();
textureProgram.setUniforms(projectionMatrix, texture);
bindData(textureProgram);
drawCircle();
Log.d("Drawing", "Drawing " + log);
}
public void scaleCircle(float[] modelMatrix, float x, float y, float z) {
Matrix.scaleM(modelMatrix, 0, x, y, z);
}
public void storeResults(float[] results) {
this.x = results[0];
this.y = results[1];
}
public void translateCircle(float x, float[] modelMatrix, float[] projectionMatrix) {
setIdentityM(modelMatrix, 0);
translateM(modelMatrix, 0, /*-0.001f*/ x, -3f, -2f);
final float[] temp = new float[16];
multiplyMM(temp, 0, projectionMatrix, 0, modelMatrix, 0);
System.arraycopy(temp, 0, projectionMatrix, 0, temp.length);
}
}
Again, I'm aware of most things I'm doing incorrectly, but currently I just need to figure out why I can't draw multiple objects on the screen. Here is my renderer code:
package com.background.gl.glcirclebackgroundanimation;
import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;
import static android.opengl.Matrix.multiplyMM;
import static android.opengl.Matrix.setIdentityM;
import static android.opengl.Matrix.translateM;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Log;
import com.background.gl.helper.TextureShaderProgram;
import com.background.gl.objects.GLCircle;
import com.background.gl.objects.Mallet;
import com.background.gl.objects.Table;
import com.background.gl.util.MatrixHelper;
import com.background.gl.util.TextureHelper;
public class CircleDynamicBackgroundRenderer implements Renderer {
private final Context context;
private final float[] projectionMatrix = new float[16];
private final float[] modelMatrix = new float[16];
protected static float ranX,
ranY, ranSignX, ranSignY, ranSignVeloX, ranSignVeloY;
public boolean logNums;
private Table table;
private Mallet mallet;
private List<GLCircle> circles;
private GLCircle circle2;
float xPos, yPos;
int x = 1;
float[] bounds;
Random ran;
private TextureShaderProgram textureProgram;
private int texture;
public CircleDynamicBackgroundRenderer(Context context) {
this.context = context;
circles = new ArrayList<GLCircle>();
xPos = 0.1f;
ran = new Random();
logNums = true;
}
#Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
glViewport(0, 0, width, height);
Log.w("Width and height", Integer.toString(width) + ", " + Integer.toString(height));
MatrixHelper.perspectiveM(projectionMatrix, 90, (float) width
/ (float) height, 1f, 10f);
for(int i = 0; i < circles.size(); i++) {
circles.get(i).translateCircle(circles.get(i).x, modelMatrix, projectionMatrix);
}
// /circle2.translateCircle(circle2.x, modelMatrix);
/*final float[] temp = new float[16];
multiplyMM(temp, 0, projectionMatrix, 0, modelMatrix, 0);
System.arraycopy(temp, 0, projectionMatrix, 0, temp.length);*/
}
#Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
table = new Table();
mallet = new Mallet();
textureProgram = new TextureShaderProgram(context);
texture = TextureHelper.loadTexture(context, R.drawable.air_hockey_surface);
//texture2 = TextureHelper.loadTexture(context, R.drawable.air_hockey_surface_2);
for(int i = 0; i < 3; i++) {
GLCircle circle = new GLCircle(generateRanFloats()[0], generateRanFloats()[1]);
circles.add(circle);
/*circle[i].x = circle[i].getX();
circle[i].y = circle[i].getY();
circle[i].bounds = circle[i].getBounds();*/
}
//circle2 = new GLCircle(generateRanFloats()[0], generateRanFloats()[1]);
Log.d("Circles size", Integer.toString(circles.size()));
Log.d("circles", Float.toString(circles.get(1).getX()) + " " + Float.toString(circles.get(2).getX()));
}
#Override
public void onDrawFrame(GL10 glUnused) {
//Clear the rendering surface
glClear(GL_COLOR_BUFFER_BIT);
for(int i = 0; i < circles.size(); i++) {
circles.get(i).setPos(modelMatrix, projectionMatrix, textureProgram, texture, circles.get(i).x, circles.get(i).y, "1"); if(logNums) {
Log.d("Circle1, c2", Float.toString(circles.get(i).x) + ", " + Float.toString(circles.get(i).x));
logNums = false;
}
//Log.d("Circles", Float.toString(circles.get(i).x));
}
}
public float[] generateRanFloats() {
ranSignX = ran.nextFloat();
ranSignY = ran.nextFloat();
ranSignX = ranSignX > 0.5f? -1:1;
ranSignY = ranSignY > 0.5f? -1:1;
ranSignVeloX = ran.nextFloat();
ranSignVeloY = ran.nextFloat();
ranX = ran.nextFloat() * 1.05f;
ranY = ran.nextFloat() * 1.75f;
ranX = ranSignX > 0.5? -ranX:ranX;
ranY = ranSignY > 0.5? -ranY:ranY;
Log.d("Generated", Float.toString(ranX));
return new float[] {ranX, ranY};
}
}
It's been two days now and I cannot for the live of me figure out what is wrong and how to fix this. I really need to figure out a way to fix this. Any assistance will be greatly appreciated. If you need to see more code, let me know.
Per the last discussion - did you work on the perspective matrix ? I would recommend first starting with the ortho projection, get your code working, then move to working with perspective projection. You can use the below as a starting point for ortho projection.
mat4.ortho(-1.0, 1.0, -1, 1.0, -10.0, 100.0, projectionMatrix);
Also remove all the z translations in your code, make your code work on xy, then add z translations.
PS: Isnt it better to continue in the same thread as (OpenGL ES 2.0 only draws the object once) ?

Categories