libGDX - how to remove existing spritebatch on screen? - java

So I've been looking through and experimenting some stuff but can't quite get how to remove pre-existing spriteBatch on screen.
so basically
I have initiated
batcher.begin();
(blah blah blah)
AssetLoader.font.draw(batcher, "Hey guys", x, y);
something like this...
now I wish to delete/remove/undraw this thing on screen...
how do I do that without using if statement because.. if I start using If statements everything is going to get sooo messy.
Thanks so much!

Its generally accepted practice in an OpenGL application to clear the screen every time and re-draw the entire screen.
So, to "erase" something, you just stop drawing it.
boolean wantToSeeThis = true;
...
void render() {
batcher.begin();
(blah blah blah)
if (wantToSeeThis) {
AssetLoader.font.draw(batcher, "Hey guys", x, y);
}
}
void hideIt() {
wantToSeeThis = false;
}

It is a bit unclear what you are asking. By default your screen gets cleared every frame with this line in the Render method.
gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
Then obviously we need statements of when we want to draw things. If you code your whole program in a single class this obviously gets messy quick. But Java is OOP which means you can add a classes with there own Draw/Render method and there own statements as to when they should be drawn. I suggest you start learning the basics of OOP.

Related

LibGdx RayCast box2d debug (visual on screen)

Can someone help me?
I want see the raycast in the game screen (for debugging..).
What is the best way to achieve that?
Please note that i use "box2d". and the way that i draw stuff to the screen is with animation..
So does it means that i need to create an "EdgeShape"? and then this is my debug line?
Please if there is any suggestions that you can give or ideas i really don't mind how to implement, all i want is a proper way to see the Raycast.
I could not found a good way to draw the Raycast, i saw someone that use batch.draw(); - but i guess that it won't work for me, because that way that my game work's is with box2ds shapes and animation? is that right?
Thanks so much!
world.rayCast(callback, enemy.getBody().getPosition(),
new Vector2(enemy.getBody().getPosition().x-500, enemy.getBody().getPosition().y));
}
RayCastCallback callback = new RayCastCallback() {
#Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
if(fixture.getBody().getUserData() == ModelType.PLAYER) {
System.out.println("hey!");
return 0;
}
return -1;
}
I debug it now with ShapeRendrer:
shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix());
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.line(rayStart,rayEnd);
shapeRenderer.setColor(Color.RED);
shapeRenderer.end();
I just add it to the same class, where my enemy is.
And i also taking care of the points (the Vector2):
world.rayCast(rayCastCallback, p1, p2);
To be updated, as my enemy moves.

Can someone explain me how rayCast works?

Im learning libgdx and one of the things that really confuses me its raycasting. I read a tutorial of how to use it and I understand it but I really want to know what's in the back. I searched for the source code of this method.
public void rayCast (final RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) { // FIXME pool RayCastCallback?
world.raycast(new org.jbox2d.callbacks.RayCastCallback() {
#Override
public float reportFixture (org.jbox2d.dynamics.Fixture f, Vec2 p, Vec2 n, float fraction) {
return callback.reportRayFixture(fixtures.get(f), point.set(p.x, p.y), normal.set(n.x, n.y), fraction);
}
}, this.point1.set(point1X, point1Y), this.point2.set(point2X, point2Y));
}
How we can see this method calls itself recursively and returns a call to reportRayFixture of the callback variable. The thing that really confused me it's from where the code select the Fixture, and how its checks every fixture. Can someone explain me really how its works.
This its the source code page https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/World.java
I will appreciate it!
Raycasting is when we draw an invisible line through space and see what it intersects with. A common use for this is to figure out what a player is clicking on- we draw a line from the camera in the direction that the player is clicking, and the first object our line touches is the line the player clicked on.
In Box2D, the RayCastCallback interface is used to allow you to write code that gets executed when your ray hits a Fixture (for example, you may want to ignore certain fixtures). I haven't used this personally, but I imagine you could use something like this in a shooter game to see if a wall-penetrating weapon could hit an object behind a wall (or something like that).
At a high level, what this lovely piece of code is doing is a little slight of hand- if you look at it really closely, what it's doing is taking in the libGDX RayCastCallback and wrapping it in a JBox2D RayCastCallback which has a slightly different API. It's more like it's overloading the method than calling it recursively.
What I don't know is why the author chose to create the Point1 and Point2 instance variables. I would think if you had multiple fixtures they would get overridden, so perhaps they are supposed to contain the last fixture hit by the ray? Even so, it looks like multiple raycasts would overwrite them.

Proper game structure

To preface, sorry for the semi-vague question. I have been searching for weeks to this question.
So I understand the necessities a game needs. (init, update, draw).
To be more specific, I'm using Java with Slick2D as a learning environment. Slick2D makes the set-up of the game pretty simple. I think I understand MVC structure, but my biggest problem right now is where do I write the player movement code?
I have the Player class which has all the fields of where it's at, what image/animation it needs to render, and right now, all of the controls. It doesn't feel right, though that could just be my own insecurities. I feel that the player movement controls should be in its own class, the collision detection in its own class, and the all the player would have is simply what defines it(coordinates, size, hit box, etc.).
I'm not entirely sure how to explain this, as every time I think about it, my mind races all over the place and I have a hard time "chunking" this information in my head.
If you need more information, please let me know. I'm just trying to find the "right" place for everything to make my code more manageable, readable, and possibly reusable.
(edited to show program flow[not runnable]) As it is, my flow is,
public class Game extends StateBasedGame{
//with main included, this sets up the window, fps, etc...
start "level 1" state...;
}
public class level1 extends BasicGameState{
public void init(){
initialize player, environment, etc...
}
public void update(){
player.update();
}
public void render(){
environment.render();
player.render();
}
}
public class Player{
All player variables
public Player(){
construct player with coords and starting image/animation
}
public void init(){
initializes all images/animations this player could potentially use
}
public void update(){
All environment based input controls go here, example;
if(this.isGrounded && input.keyIsDown(KEY_SPACE){
make character jump;
change animation;
}
}
public void render(){
draw image/animation;
}
}
Collision detection should be taken care of in the update method. If you mean movement from input, you should create a separate class for input. Store the position coordinates for a character in the character object. The Input class should then change these coordinates. If you are talking about an AI you should have a separate AI class that controls the movement.
Every game is different. The important part is that you understand the code and that it works. I recommend finding helpful online tutorials that show example code so you can begin to understand the workflow of creating a game.

Slick: can't load image in update loop

As you can see from the code below, I am trying to import "someimage.png". This is so in the render loop, I have the right image. I put the second line of code. Is this possible? If not what is an alternative. Thanks in advance.
public void update(GameContainer container, int delta) {
//if statement
Image x = new Image("someimage.png");
}
public void render() {
//draw image x
}
There is an "unhanded exception type SlickException".
It looks like the variable "x" is local to the update() function. If your render() function tries to call "x", maybe it's a different variable?
Check out this Slick tutorial here, it shows a basic game setup with image loading. Basically, you want the Images to be member variables of your game class, their values set in the init method, and the render method to draw the pictures. Although this setup will work fine for very simple games, you are probably better off using objects to represent the different things in your game. I hope this helps.

Working my way arround repaint() in Java

I'm planning to write a simple spaceshooter. I have read that the repaint() method is only a request, and it doesn't execute every time it's called. I believe I'm noticing the effects of this, as my spaceship tends to lag ever so slightly when I'm moving it. Currently I'm simply drawing my ship in a a JPanel's paintComponent() method, and keep calling repaint() on regular intervals (my panel's also Runnable). Seeing as repaint() may potentially screw me over, I'm trying to find a way to work arround it, however I've ran out of ideas. The code I have so far:
private void renderGraphics() {
if (MyImage == null) {
MyImage = new BufferedImage(getPreferredSize().width,
getPreferredSize().height, BufferedImage.TYPE_INT_RGB);
}
MyGraphics = MyImage.getGraphics();
MyGraphics.setColor(Color.BLACK);
MyGraphics.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
MyGraphics.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);
}
The idea was to create my own graphics, and then make the JPanel draw it, and keep calling this instead of repaint() in my run() method, however I have no idea how to do that. I'd appriciate any input on the matter.
There are multiple ways to approach this.
The best is probably to use BufferStrategy and draw to that, of which I have included a code snippet that should work for you.
You can take this one step further and abandon Swing altogether, just using Frame/BufferStrategy. There is a fully working example (from which the code snippet was taken and adapted) in my question here:
AWT custom rendering - capture smooth resizes and eliminate resize flicker
Anyway, here is an implementation BufferStrategy that you should be able to just drop in:
// you should be extending JFrame
public void addNotify() {
super.addNotify();
createBufferStrategy(2);
}
private synchronized void render() {
BufferStrategy strategy = getBufferStrategy();
if (strategy==null) return;
sizeChanged = false;
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
MyGraphics draw = strategy.getDrawGraphics();
draw.setColor(Color.BLACK);
draw.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
draw.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);
draw.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
any drawing will still be performed in the Swing Thread, so no matter what you try work around, it wont help.
Make sure you are not doing any lengthy calculations in the swing thread, this may be stopping repaint from being executed as soon as it needs to be executed
Separate all the logic into 2 parts. Static and Dynamic. (e.g. sea and moving ship. Ship changes shape/location on a static image of sea)
Draw static content in an image once and use the image in your paintComponent(). Call dynamic parts painting after the static image.
Use setClip() to restrict repainting areas.
Calling repaint without any arguments means that the whole panel is repainted.
If you need to repaint parts of the screen (the spaceship has moved to a different location) you should make shure that only those parts of the screen are repainted. The areas that stay the same should not be touched.
Repaint takes coordinates of a rectangle that should be repainted. When moving the ship you should know the old coordinates of the ship and the coordinates the ship should move to.
repaint( oldShipCoordinateX, oldShipCoordinateY, shipWidth, shipLength );
repaint( newShipCoordinateX, newShipCoordinateY, shipWidth, shipLength );
This is usually much faster than calling repaint() without arguments. However you have extra effort to remember the last position of the ship and must be able to calculate the new position of the ship.
See also: http://download.oracle.com/javase/tutorial/uiswing/painting/index.html - especially step 3
Just for code that you post here:
1/ if you want to display Image/ImageIcon, then the best and easiest way is to Use Labels
2/ as you mentioned Runnable{...}.start(); Swing is simple threaded and all output to GUI must be done on EDT; you have to look at Concurrency in Swing, result is that all output from BackGround Task(s) must be wrapped into invokeLater(), and if is there problem with perfomancie then into invokeAndWait()
3/ if you be switch (between JComponents)/add/delete/change Layout then you have to call revalidate() + repaint() as last lines in concrete code block
EDIT:
dirty hack would be paintImmediately()
I have read that the repaint() method is only a request, and it doesn't execute every time it's called
It consolidates multiple repaint() requests into one to be more efficient.
I believe I'm noticing the effects of this, as my spaceship tends to lag ever so slightly when I'm moving it.
Then post your SSCCE that demonstrates this problem. I suspect the problem is your code.
Regarding the solution you accepted, take a look at Charles last posting: Swing/JFrame vs AWT/Frame for rendering outside the EDT comparing Swing vs AWT solutions.

Categories