Libgdx render for a rectangle array different textures - java

I am developing a game with libgdx and i got stuck at a point. So My SpriteBatch draws for all the Rectangles that are in an array with the same texture but I want that every single one has its own texture. MY Code looks like this
public class GameScreen implements Screen{
final MrJetpack game;
OrthographicCamera camera;
SpriteBatch batch;
ShapeRenderer rend;
private Array<Rectangle> raindrops;
Texture enemy1,enemy2,enemy3,enemy4,endScreen;
TextureRegion[] enemys = new TextureRegion[4];
private int random;
public GameScreen(final MrJetpack game){
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
enemy1 = new Texture(Gdx.files.internal("boxk.png"));
enemy2 = new Texture(Gdx.files.internal("boxg.png"));
enemy3 = new Texture(Gdx.files.internal("kugel.png"));
enemy4 = new Texture(Gdx.files.internal("kugelk.png"));
enemys[0] = new TextureRegion(enemy1);
enemys[1] = new TextureRegion(enemy2);
enemys[2] = new TextureRegion(enemy3);
enemys[3] = new TextureRegion(enemy4);
raindrops = new Array<Rectangle>();
rend = new ShapeRenderer();
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
//Gdx.gl.glClearColor(0, (float)148/255,(float) 255/255, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
rend.begin(ShapeType.Filled);
rend.rect(0, 0, 800, 10);
rend.rect(0, 160, 800, 10);
rend.rect(0, 320, 800, 10);
rend.setColor(Color.ORANGE);
rend.end();
batch.begin();
for(Rectangle raindrop: raindrops) {
batch.draw(enemys[random], raindrop.x - 10, raindrop.y);
}
batch.end();
if(TimeUtils.nanoTime() - lastDropTime > spawnTime){
spawnRaindrop();
}
Iterator<Rectangle> iter = raindrops.iterator();
while(iter.hasNext()) {
Rectangle raindrop = iter.next();
raindrop.x -= 20 * Gdx.graphics.getDeltaTime();
if(raindrop.x < 0) {
spawnRaindrop();
iter.remove();
}
}
}
private void spawnRaindrop() {
Rectangle raindrop = new Rectangle();
raindrop.x = 800;
stages = MathUtils.random(1, 3);
random = MathUtils.random(0, 3);
raindrop.width = 30;
raindrop.height = 53;
raindrops.add(raindrop);
lastDropTime = TimeUtils.nanoTime();
}
So what actually happening is that everytime a new Rectangle spawns in the screen the other ones who were already displayed change the Texture so every Rectangle got the same Texture . Any solutions or examples?
EDIT: http://imgur.com/46ywYyy
This is my problem for people who understood my question false :)
Like you can see the texture is changing for all the other rectangles but i want everyone to have their static texture

They told you, one way to do it, but I see you do not clear, I'll put more or less as you might do.
I'll try to make the form more similar to what you already have in your code.
note
this code may have syntax error, among others, becouse I'm doing from the editor StackOverflow.
1- create a class that is derived from sprite, for example something like:
public class SpriteRaindrop extends Sprite{
Rectangle raindrop = new Rectangle();
public SpriteRaindrop(Texture t, int srcWidth,
int srcHeigth,
float posX,
float posY){
super(t, srcWidth, srcHeigth);
raindrop.x = posX;
raindrop.y = posY;
raindrop.width = srcWidth;
raindrop.height = srcHeigth;
setPosition(posX, posY);
}
public void updateR(){
raindrod.x = getX();
raindrod.y = getY();
}
}
This your code with with any changes
public class GameScreen implements Screen{
final MrJetpack game;
OrthographicCamera camera;
SpriteBatch batch;
ShapeRenderer rend;
private Array<SpriteRaindrop> raindrops;
Texture enemy1,enemy2,enemy3,enemy4,endScreen;
TextureRegion[] enemys = new TextureRegion[4];
private int random;
public GameScreen(final MrJetpack game){
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
enemy1 = new Texture(Gdx.files.internal("boxk.png"));
enemy2 = new Texture(Gdx.files.internal("boxg.png"));
enemy3 = new Texture(Gdx.files.internal("kugel.png"));
enemy4 = new Texture(Gdx.files.internal("kugelk.png"));
enemys[0] = new TextureRegion(enemy1);
enemys[1] = new TextureRegion(enemy2);
enemys[2] = new TextureRegion(enemy3);
enemys[3] = new TextureRegion(enemy4);
raindrops = new Array<SpriteRaindrop>();
rend = new ShapeRenderer();
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
//Gdx.gl.glClearColor(0, (float)148/255,(float) 255/255, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
rend.begin(ShapeType.Filled);
rend.rect(0, 0, 800, 10);
rend.rect(0, 160, 800, 10);
rend.rect(0, 320, 800, 10);
rend.setColor(Color.ORANGE);
rend.end();
batch.begin();
for(SpriteRaindrop raindrop: raindrops) {
//raindrop.translatex(-10f);
//what is raindrop.y value
raindrop.updateR();
raindrop.draw(batch);
}
batch.end();
if(TimeUtils.nanoTime() - lastDropTime > spawnTime){
spawnRaindrop();
}
Iterator<SpriteRaindrop> iter = raindrops.iterator();
while(iter.hasNext()) {
SpriteRaindrop raindrop = iter.next();
raindrop.translateX(-20f * Gdx.graphics.getDeltaTime());
if(raindrop.getX() < 0) {
spawnRaindrop();
iter.remove();
}
}
}
private void spawnRaindrop() {
stages = MathUtils.random(1, 3);
random = MathUtils.random(0, 3);
lastDropTime = TimeUtils.nanoTime();
SpriteRaindrop raindrop = new SpriteRaindrop(enemys[random],
30, 53,
800, 0);
raindrops.add(raindrop);
}
this is just an idea, but I think it can work, I hope you help

The variable random is global for class, once a new sprite spawns it sets the value to new random value and all of them are draw by:
batch.draw(enemys[random], raindrop.x - 10, raindrop.y);
You need to track this together with location per instance.

Related

LIBGDX horizontal and vertical parallax background

Im trying to do a little game in LibGdx, right now i have a spaceship that can move with a touchpad in every directions and the camera follows it.
Im tryng to accomplish a parallax background made of stars that moves depending of where the spaceship is going.
Here it is the code, Im giving you all the class just to be sure to not mess up, for im new with this programming code.
public class TouchPadTest extends OrthographicCamera implements ApplicationListener {
public static final int WIDTH=480;
public static final int HEIGHT=800;
private OrthographicCamera camera;
private Stage stage;
private SpriteBatch batch;
private Touchpad touchpad;
private TouchpadStyle touchpadStyle;
private Skin touchpadSkin;
private Drawable touchBackground;
private Drawable touchKnob;
private Texture blockTexture;
private Sprite blockSprite;
private float blockSpeed;
public void create() {
batch = new SpriteBatch();
//Create camera
float aspectRatio = (float) Gdx.graphics.getWidth() / (float) Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, TouchPadTest.WIDTH, TouchPadTest.HEIGHT);
//Create a touchpad skin
touchpadSkin = new Skin();
//Set background image
touchpadSkin.add("touchBackground", new Texture("data/touchBackground.png"));
//Set knob image
touchpadSkin.add("touchKnob", new Texture("data/touchKnob.png"));
//Create TouchPad Style
touchpadStyle = new TouchpadStyle();
//Create Drawable's from TouchPad skin
touchBackground = touchpadSkin.getDrawable("touchBackground");
touchKnob = touchpadSkin.getDrawable("touchKnob");
//Apply the Drawables to the TouchPad Style
touchpadStyle.background = touchBackground;
touchpadStyle.knob = touchKnob;
//Create new TouchPad with the created style
touchpad = new Touchpad(10, touchpadStyle);
//setBounds(x,y,width,height)
touchpad.setBounds(15, 15, 200, 200);
//Create a Stage and add TouchPad
stage = new Stage(new FitViewport(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()));
stage.addActor(touchpad);
Gdx.input.setInputProcessor(stage);
//Create block sprite
blockTexture = new Texture(Gdx.files.internal("data/shuttle2.png"));
blockSprite = new Sprite(blockTexture);
//Set position to centre of the screen
blockSprite.setPosition(Gdx.graphics.getWidth()/2-blockSprite.getWidth()/2, Gdx.graphics.getHeight()/2-blockSprite.getHeight()/2);
blockSpeed=5;
}
public void movePlayer(){
Vector2 v = new Vector2(touchpad.getKnobPercentX(), touchpad.getKnobPercentY());
float angle = v.angle();
if (touchpad.isTouched()){
blockSprite.setRotation(angle);
}
blockSprite.setX(blockSprite.getX() + touchpad.getKnobPercentX()*blockSpeed);
blockSprite.setY(blockSprite.getY() + touchpad.getKnobPercentY()*blockSpeed);
//Draw
camera.position.set(blockSprite.getX() + blockSprite.getWidth() / 2, blockSprite.getY() + blockSprite.getHeight() / 2, 0);
camera.update();
batch.setProjectionMatrix(camera.combined);
}
public void renderBackground() {
//---------------PARALLAX BACKGROUND---------------------//
}
public void dispose() {
}
public void render() {
Gdx.gl.glClearColor(0/255f,5/255f,15/255f,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//Move blockSprite with TouchPad
movePlayer();
batch.begin();
renderBackground();
blockSprite.draw(batch);
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void resize(int width, int height) {
}
}
For a better exemple, this is the kind of result that i want to achieve: https://www.youtube.com/watch?v=zA91SaOR-Io, if you can help me it will be amazing. Thank You.
This working example of a 3 layer parallax background was adapted from the LibGdx Parallax test and should give you an idea on how to implement a parallax effect. The three images used are all 1024x1024px.
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
public class Test extends ApplicationAdapter implements InputProcessor{
private SpriteBatch batch;
private ParallaxCamera camera;
private Texture bgClose;
private Texture bgMid;
private Texture bgFar;
final Vector3 curr = new Vector3();
final Vector3 last = new Vector3(-1, -1, -1);
final Vector3 delta = new Vector3();
#Override
public void create () {
bgClose = new Texture(Gdx.files.internal("starbg-close.png"));
bgMid = new Texture(Gdx.files.internal("starbg-mid.png"));
bgFar = new Texture(Gdx.files.internal("starbg-far.png"));
camera = new ParallaxCamera(1920,1080);
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
}
#Override
public void render () {
//clear screen
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// background layer, no parallax, centered around origin
batch.setProjectionMatrix(camera.calculateParallaxMatrix(0, 0));
batch.disableBlending();
batch.begin();
batch.draw(bgFar, -(int)(bgFar.getWidth() / 2), -(int)(bgFar.getHeight() / 2));
batch.end();
batch.enableBlending();
batch.setProjectionMatrix(camera.calculateParallaxMatrix(0.25f, 0.25f));
batch.begin();
for (int i = 0; i < 9; i++) {
batch.draw(bgMid, i * bgClose.getWidth() - 512, -512);
}
batch.end();
batch.setProjectionMatrix(camera.calculateParallaxMatrix(.5f, .5f));
batch.begin();
for (int i = 0; i < 9; i++) {
batch.draw(bgClose, i * bgClose.getWidth() - 512, -512);
}
batch.end();
}
//.. omitted empty methods ..//
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
last.set(-1, -1, -1);
return false;
}
#Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(curr.set(x, y, 0));
if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
camera.unproject(delta.set(last.x, last.y, 0));
delta.sub(curr);
camera.position.add(delta.x, delta.y, 0);
}
last.set(x, y, 0);
return false;
}
private class ParallaxCamera extends OrthographicCamera {
Matrix4 parallaxView = new Matrix4();
Matrix4 parallaxCombined = new Matrix4();
Vector3 tmp = new Vector3();
Vector3 tmp2 = new Vector3();
public ParallaxCamera (float viewportWidth, float viewportHeight) {
super(viewportWidth, viewportHeight);
}
public Matrix4 calculateParallaxMatrix (float parallaxX, float parallaxY) {
update();
tmp.set(position);
tmp.x *= parallaxX;
tmp.y *= parallaxY;
parallaxView.setToLookAt(tmp, tmp2.set(tmp).add(direction), up);
parallaxCombined.set(projection);
Matrix4.mul(parallaxCombined.val, parallaxView.val);
return parallaxCombined;
}
}
}

Libgdx problems with viewport/camera/rendering

I am having trouble for the last 2 days to figure out what is wrong with my application. I'm trying to build a game, a platformer where the player needs to go up, (somewhat like doodlejump). I have build my testmap in tmx format. I have been trying to start the camera and the viewport to show the left-bottom of the world, so the player can move to the right and also upward. But this seems to difficult for a beginning libgdx learner!
I am using a Playscreen, a HUD and a MainActivity:
PlayScreen
private MainActivity game;
private OrthographicCamera gamecam;
private Viewport gameport;
private HUD hud;
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private World world;
private Box2DDebugRenderer b2dr;
private Jack player;
public PlayScreen(MainActivity game){
// Initiates the game, camera, viewport and HUD
this.game = game;
gamecam = new OrthographicCamera();
hud = new HUD(game.batch);
gameport = new FitViewport(MainActivity.V_WIDTH, MainActivity.V_HEIGHT, gamecam);
// loading the map
mapLoader = new TmxMapLoader();
map = mapLoader.load("level1revised.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1 / MainActivity.PPM);
//initially set our gamecam to be centered correctly at the start of of map
gamecam.position.set(gameport.getWorldWidth() / 2, gameport.getWorldHeight() / 2, 0);
// Box2D world (graphics)
world = new World(new Vector2(0, -10), true);
b2dr = new Box2DDebugRenderer();
// New Jack
player = new Jack(world);
BodyDef bdef = new BodyDef();
PolygonShape shape = new PolygonShape();
FixtureDef fdef = new FixtureDef();
Body body;
// The ground as an object is defined
for(MapObject object: map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set((rect.getX() + rect.getWidth()/2)/MainActivity.PPM, (rect.getY() + rect.getHeight()/2) /MainActivity.PPM);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth()/2, rect.getHeight()/2);
fdef.shape = shape;
body.createFixture(fdef);
}
public void update(float dt){
handleInput(dt);
world.step(1 / 60f, 6, 2);
//gamecam.position.x = player.b2body.getPosition().x;
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void render(float delta) {
update(delta);
// Clear the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// render the map
renderer.render();
// render the box2d
b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamecam.viewportWidth = width;
gamecam.viewportHeight = height;
}
HUD & Mainactivity
public HUD(SpriteBatch sb){
worldTimer = 300;
timeCount = 0;
score = 0;
viewport = new FitViewport(MainActivity.V_WIDTH, MainActivity.V_HEIGHT, new OrthographicCamera());
stage = new Stage(viewport, sb);
Table table = new Table();
table.top();
table.setFillParent(true);
countdownlabel = new Label(String.format("%03d", worldTimer), new Label.LabelStyle(new BitmapFont(), Color.RED));
scoreLabel = new Label(String.format("%06d", score), new Label.LabelStyle(new BitmapFont(), Color.RED));
timeLabel = new Label("TIME", new Label.LabelStyle(new BitmapFont(), Color.RED));
levelLabel = new Label("level 1", new Label.LabelStyle(new BitmapFont(), Color.RED));
table.add(timeLabel).expandX().padTop(10);
table.add(levelLabel).expandX().padTop(10);
table.row();
table.add(scoreLabel).expandX().padTop(10);
stage.addActor(table);
}
public class MainActivity extends Game {
public SpriteBatch batch;
public static final int V_WIDTH = 720;
public static final int V_HEIGHT = 480;
public static final float PPM = 1;
public static final String TITLE = "Jack the Pirate";
#Override
public void create () {
batch = new SpriteBatch();
setScreen(new PlayScreen(this));
}
#Override
public void render () {
super.render();
}
}
I have no clue where to look anymore, been through the basics countless times :( My tmx tilemap is 14 tiles wide, and 70 tiles high. The tiles themselves are 16x16. My test device is a Samsung Galaxy S3, and i wanted to use it in portrait mode.
Any ideas where to look? Thanks in advance for help!

Scrollpane strange scaling in libgdx

The text drawn by font and drawn in List inside Scrollpane seem with different sizes. This is how I draw text:
font.draw(batch, "score", 500, 700);
And how I draw text in List inside ScrollPane:
tfBackground = new Texture(Gdx.files.internal("tfbackground.png"));
knob_scroll = new Texture(Gdx.files.internal("knob_scroll.png"));
scroll_horizontal = new Texture(Gdx.files.internal("scroll_horizontal.png"));
sps.background = new TextureRegionDrawable(new TextureRegion(tfBackground));
sps.vScroll = new TextureRegionDrawable(new TextureRegion(scroll_horizontal));
sps.vScrollKnob = new TextureRegionDrawable(new TextureRegion(knob_scroll));
listS = new List.ListStyle();
listS.font = font;
listS.fontColorSelected = Color.BLACK;
listS.fontColorUnselected = Color.GRAY;
listS.selection = new TextureRegionDrawable(new TextureRegion(tfBackground));
scoreList = new List<String>(listS);
items = new Array<String>();
res += "score 1, score 2, score 3, score 4, score 5, score 6, score 7, score 8, score 9, score 10";
String name_score[] = res.split(",");
for(String s: name_score)
{
items.add(s);
}
scoreList.setItems(items);
scoreList.pack();
scrollPane = new ScrollPane(scoreList, sps);
addActor(scrollPane);
And this is the weird(?) result:
It seems that scrollpane is scaling somehow. I don't want it the text inside scrollpane to be scaled.
This is the whole code:
public class ResultScreen extends AbstractScreen{
private OrthographicCamera camera;
private Viewport viewport;
private BitmapFont font;
private SpriteBatch batch;
private String res;
private float time = 10;
private Texture tfBackground, knob_scroll, scroll_horizontal;
private List<String> scoreList;
private ScrollPane scrollPane;
private List.ListStyle listS;
private ScrollPane.ScrollPaneStyle sps;
private Array<String> items;
public ResultScreen(float time, String res) {
this.time = time;
font = new BitmapFont(Gdx.files.internal("aw.fnt"));
font.setColor(Color.BLACK);
camera = new OrthographicCamera();
viewport = new StretchViewport(800, 1024, camera);
//viewport = new FitViewport(1240, 800, camera);
batch = new SpriteBatch();
camera.position.x = 400;
camera.position.y = 512;
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.res = res;
fillList();
}
#Override
public void buildStage() {
// TODO Auto-generated method stub
}
#Override
public void resize(int width, int height) {
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
#Override
public void render(float delta) {
super.render(delta);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
font.draw(batch, "score", 500, 700);
batch.end();
draw();
act();
}
private void fillList()
{
sps = new ScrollPane.ScrollPaneStyle();
tfBackground = new Texture(Gdx.files.internal("tfbackground.png"));
knob_scroll = new Texture(Gdx.files.internal("knob_scroll.png"));
scroll_horizontal = new Texture(Gdx.files.internal("scroll_horizontal.png"));
sps.background = new TextureRegionDrawable(new TextureRegion(tfBackground));
sps.vScroll = new TextureRegionDrawable(new TextureRegion(scroll_horizontal));
sps.vScrollKnob = new TextureRegionDrawable(new TextureRegion(knob_scroll));
listS = new List.ListStyle();
listS.font = font;
listS.fontColorSelected = Color.BLACK;
listS.fontColorUnselected = Color.GRAY;
listS.selection = new TextureRegionDrawable(new TextureRegion(tfBackground));
scoreList = new List<String>(listS);
items = new Array<String>();
res += "score 1, score 2, score 3, score 4, score 5, score 6, score 7, score 8, score 9, score 10";
String name_score[] = res.split(",");
for(String s: name_score)
{
items.add(s);
}
scoreList.setItems(items);
scoreList.pack();
scrollPane = new ScrollPane(scoreList, sps);
scrollPane.setWidth(300);
System.out.println(Gdx.graphics.getWidth());
addActor(scrollPane);
}
}
PS: Abstract screen extends Stage and implements Screen.
Your constructor doesn't call through to a superclass constructor, which would also need to call through to one of the Stage constructors to make sure your Stage is properly set up.
What's going on here is that you set up a camera and viewport (and SpriteBatch, although not part of the issue) that are used only for your font.draw and are distinct from what the Stage uses.
Your class needs to look something like this:
public class ResultScreen extends AbstractScreen{
private OrthographicCamera camera;
private Viewport viewport;
private BitmapFont font;
private Batch batch; //<------------changed
private String res;
private float time = 10;
private Texture tfBackground, knob_scroll, scroll_horizontal;
private List<String> scoreList;
private ScrollPane scrollPane;
private List.ListStyle listS;
private ScrollPane.ScrollPaneStyle sps;
private Array<String> items;
public ResultScreen(float time, String res) {
super(new StretchViewport(800, 1024)); //Call an AbstractScreen constructor that calls a Stage constructor
this.time = time;
font = new BitmapFont(Gdx.files.internal("aw.fnt"));
font.setColor(Color.BLACK);
camera = getCamera(); //<------------changed
viewport = getViewport(); //<------------changed
batch = getBatch(); //<------------changed
camera.position.x = 400;
camera.position.y = 512;
// unnecessary can remove because this is called in resize: viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.res = res;
fillList();
}
}
For example, AbstractScreen could have a constructor like this:
public AbstractScreen(Viewport viewport){
super(viewport);
}

libGDX does foreach create an object?

Im learning by these tutourials g3d: https://xoppa.github.io/blog/using-materials-with-libgdx/
Now I have heard that the foreach loop creates an object and thats bad to use in the render method.
Example:
private PerspectiveCamera cam;
private CameraInputController camController;
private Shader shader;
private Model model;
private Array<ModelInstance> instances = new Array<ModelInstance>();
private ModelBatch modelBatch;
#Override
public void show() {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(2f, 2f, 2f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
new Material(),
VertexAttributes.Usage.Position |
VertexAttributes.Usage.Normal |
VertexAttributes.Usage.TextureCoordinates);
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z <= 5; z+=2) {
instances.add(new ModelInstance(model, x, 0, z));
}
}
shader = new TestShader();
shader.init();
modelBatch = new ModelBatch();
}
#Override
public void render(float delta) {
camController.update();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
for (ModelInstance instance : instances) {
modelBatch.render(instance, shader);
}
modelBatch.end();
}
Is this true does it create an Object?
What would be a solution?
No, it does not create an Object. The for-each loop is simply a syntactical shortcut. See Does the Java foreach loop create a new object?

Rectangles are not colliding?

Player Class
public class Player extends Sprite implements InputProcessor {
public Vector2 velocity = new Vector2();
private float speed = 500;
public Rectangle rectangle;
public Player(Sprite sprite){
super(sprite);
this.rectangle = sprite.getBoundingRectangle();
}
public void draw(SpriteBatch spriteBatch){
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta) {
rectangle = new Rectangle(getX() + velocity.x * delta,0,rectangle.getWidth(),rectangle.getWidth());
setX(getX() + velocity.x * delta);
}
}
PlayScreen Class
public class PlayScreen implements Screen {
private Player player;
private OrthographicCamera camera;
private OrthogonalTiledMapRenderer renderer;
private TiledMap map;
private Rectangle rightRectangle, leftRectangle, playerRectangle;
//private ShapeRenderer shapeRenderer;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
renderer.getSpriteBatch().begin();
player.draw(renderer.getSpriteBatch());
renderer.getSpriteBatch().end();
//shapeRenderer.begin(ShapeType.Filled);
//shapeRenderer.setColor(0, 1, 0, 1);
//shapeRenderer.rect(
// player.getX() + player.velocity.x * delta, 0,
// player.rectangle.getWidth(), player.rectangle.getHeight());
//shapeRenderer.end();
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
}
#Override
public void show() {
camera = new OrthographicCamera();
map = new TiledMap();
renderer = new OrthogonalTiledMapRenderer(map);
//shapeRenderer = new ShapeRenderer();
player = new Player(new Sprite(new Texture("img/player.png")));
rightRectangle = new Rectangle(1280,0,0,720);
leftRectangle = new Rectangle(0,0,0,720);
boolean wallLeft = leftRectangle.overlaps(player.rectangle);
boolean wallRight = rightRectangle.overlaps(player.rectangle);
if(wallLeft){
System.out.println("wallLeft Overlap");
player.velocity.x = 0;
}
else if(wallRight){
System.out.println("wallRight Overlap");
player.velocity.x = 0;
}
player.setPosition(
Gdx.graphics.getWidth()/2f - player.getWidth()/2f,
Gdx.graphics.getHeight()/2f - player.getHeight()/2f
- Gdx.graphics.getHeight()/5f);
}
}
Doesn't seem to be colliding correctly. The rightRectangle and leftRectangle are my screen side bounds. When I use the shapeRenderer, it produces the ShapeRendered rectangle and it will follow my player around. However, I believe that my player.rectangle is not moving at all for some reason, resulting in it not colliding with my side bounds. Any help would be greatly appreciated!
rightRectangle = new Rectangle(1280,0,0,720);
leftRectangle = new Rectangle(0,0,0,720);
A Rectangle is defined as Rectangle(x, y, width, height). It looks like you are trying to define it incorrectly as Rectangle(x1, y1, x2, y2). In the above, you have created two rectangles of 0 width.

Categories

Resources