libgdx overlap stop draw - java

I have written the following code. I would like to stop drawings once object one the collision has occurred. Unfortunately, it only stops drawing the object only when the collision is occurring and then starts drawing the object again.
To give an example of what I am trying to learn is: player collects coin, coin disappears. if the player misses coin, the coin still appears on screen.
The idea is to learn the basic concepts before I start putting things together. Copying code without understanding is no fun. Thanks in advance.
batcher.begin();
if (egg.collected) {
batcher.draw(AssetLoader.textureEgg, eggRect.x, eggRect.y, eggRect.width, eggRect.height);
}
batcher.end();
My egg class:
public class Egg {
private Rectangle egg;
private Vector2 location;
public Egg(float x, float y){
location = new Vector2(x, y);
egg = new Rectangle(location.x, location.y, 10, 15);
}
public void update(float delta) {
egg.x--;
if (egg.x < -20) {
egg.x = 137;
};
}
public boolean collected = false;
public Rectangle getEgg() {
return egg;
}
public boolean isCollected() {
return collected;
}
}
The result of the above code is: The game crashes with following errors.
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.mygdx.gameworld.GameRenderer.render(GameRenderer.java:60)
at com.mygdx.screens.GameScreen.render(GameScreen.java:32)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:214)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

Tenfour04 is right. Since collides is true when the two objects overlaps, it will stop drawing while they overlap and start to draw again. Save the return value to member variable.

Create a member variable in your Egg class to keep track of whether the egg has been collected:
public boolean collected = false;
If you want to practice good encapsulation, you could make this variable private and give it a getter and setter, but I'll keep it simple like this.
Then in what appears to be your game or screen class, you need to tell the egg when it's collected:
if (eggRect.overlaps(boundingRect))
egg.collected = true;
Now, you should only draw the egg if it is not collected:
batcher.begin();
if (!egg.collected){
batcher.draw(AssetLoader.textureEgg, eggRect.x, eggRect.y, eggRect.width, eggRect.height);
}
batcher.end();
By the way, it's kind of weird that your Egg class extends Rectangle, but you aren't using it as a Rectangle but rather as a container for some other Rectangle. You might as well remove "extends Rectangle".

Related

Java ArrayList update with points seems to replace all elements in said array with the most recent point

short description of what I am trying to do: I'm building a simple game where the user controls a vehicle and after some time more and more ghosts begin following the player, they follow the same trajectory as the player did with a delay.
To accomplish this I create an Array that contains the history of the player's location as a sequence of points. The problem, however, is that when I look at the data stored in this array I see that on all indices only the most recent location is stored.
First I create the array in a botManager class:
public class BotManager {
private ArrayList<Bots> bots;
private List<Point> history;
BotManager() {
history = new ArrayList<>();
bots = new ArrayList<>();
}
Then in the update method of the manager class I add the current location of the player to the array
public void update(Point currLoc) {
history.add(currLoc);
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}
A look at the update method in the main GameView class, in case I forgot something here
public void update() {
player.update(playerPoint);
botManager.update(playerPoint);
}
In the bots class' constructor I pass the history list (locationData) and determine its length to find out the delay in positioning. After which the following code handles the position of the bot.
#Override
public void update() {
loc = locationData.get(delay - 1);
this.rectangle = new Rect(loc.x - Constants.BOTSIZE/2, loc.y - Constants.BOTSIZE/2,
loc.x + Constants.BOTSIZE/2, loc.y + Constants.BOTSIZE/2);
}
To get back to the problem, whenever I check the contents of the history array, I find that it only contains one point on all indices, and its the most recent even when I moved the player, causing the ghost to always remain on top of me.
So my question here is, what am I doing wrong here?
Not clear from your posted code, but could it be, that you are just modifying the Point which you are adding instead renewing your object's Point objects?
Try
public void update(Point currLoc) {
history.add(new Point(currLoc)); // new Point object added here
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}

Block's bounding box's glitching strange way

I have something kind of
private AxisAlignedBB boundingBox = new AxisAlignedBB(-0.34D, 0D, -0.34D, 1.34D, 3.24D, 1.34D);
#Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos)
{
return boundingBox;
}
#Override
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos)
{
return boundingBox.offset(pos);
}
#Override
public boolean isFullCube(IBlockState state) {
return false;
}
#Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
in the class of my tile entity. And when i'm trying to walk through the middle of block, the collision bounding box works correct, but when i try to jump on the block, i get stuck in it, trying to fall through. Also i get stuck in the same block if i try to walk into the block from the corners or trying to stand on the whole construction: i fall until i reach the height of 2D and then glitches begin. Corners of the block act as if there was no bounding box for the corners. Is it possible to make block bounding boxes work correct?
The block and its bounding box.
Actual working (or partially working) area.
I would recommend using dummy blocks for this. When your block is placed, spawn dummy blocks in the required areas. When your block, or the dummy blocks, are broken, break the entire structure of dummies and true blocks.

Libgdx - didpose over and over?

hey am a beginner in Libgdx. i am a bit confused about disposing the stuff.
Texture brickTexture;
Array<Brick> bricks;
public Game {
brickTexture = new Texture("brick.png");
bricks = new Array<Brick>();
for (int i = 0; i < 10; i++) {
Brick brick = new Brick(i, brickTexture);
bricks.add(brick);
}
}
void dispose () {
brickTexture.dispose(); // brick texture loaded in this class
for (Brick brick : bricks) brick.brickTexture.dispose(); // disposing the public texture which was earlier passed on to the brick class
}
Should both of the lines be in the dispose method or only the first one ?
You only have to do this once. It's the same Texture object so when you dispose it on any reference no other object can use it anymore. It's disposed.
Also you might want to check out AssetManager class, which handles disposing stuff for you.
You are using "bricktexture" for every "Brick" in the ArrayList, so you are basically pointing to the same object so you should only dispose "bricktexture" once.
If you also want to "free" the array, probably you should call
bricks.clear();
Which will become empty (as with no elements inside).

libgdx Temporary sprite movement after being spawned

public class Player {
private Sprite enemy;
public Rectangle bounds;
private SpriteBatch batch;
private float deltaTime;
private float timer;
private ArrayList<Sprite> enemies;
private Iterator<Sprite> enemyIterator;
private ArrayList<Vector2> posCoordinate;
Sprite newEnemy;
public void create(){
batch=new SpriteBatch();
timer=0;
enemy=new Sprite(new Texture(Gdx.files.internal("spr_player.png")));
bounds=new Rectangle(200,700,82,80);
enemies=new ArrayList<Sprite>();
posCoordinate=new ArrayList<Vector2>();
newEnemy=Pools.obtain(Sprite.class);
}
public void update(){
deltaTime=Gdx.graphics.getDeltaTime();
enemyIterator=enemies.iterator();
timer+=1*deltaTime;
if(timer>=1f){
newEnemy(); //method called every second
timer-=1;
}
}
public void newEnemy(){
Vector2 position=Pools.obtain(Vector2.class); //vector2 is created for each enemy every second.
position.set(200,700);
posCoordinate.add(position);
newEnemy=Pools.obtain(Sprite.class); //enemy created every second
newEnemy.set(enemy);
enemies.add(newEnemy);
}
public void draw(SpriteBatch batch){
//this is where the enemy position is set and movement
for(Sprite enemy:enemies){
enemy.draw(batch);
}for(Vector2 position:posCoordinate){
newEnemy.setPosition(position.x,position.y);
position.y-=2;
}
}
}
newEnemy() method is being called every second that's why a new sprite is being rendered every second.
Basically what I'm trying to do is that when a new enemy is spawned, it must move downward until it goes outside the screen.But what is happening is that the enemy will only move for one second.
I think you've confused things by introducing the member variable newEnemy. You have a method that creates a new enemy and adds it to your enemies list, and after that, there should not be a reason to reference it separately from the list, so you should just allow the newEnemy reference to be discarded.
Therefore, you should remove the Sprite newEnemy line from your class, and just declare it within the newEnemy() method.
Also, there's no need for your list of Vector2's for positions, because the Sprite class already stores a position. You just need to move the individual sprites. So remove everything related to posCoordinate as well. Your newEnemy() method should just look like this:
private void newEnemy(){
Sprite newEnemy = Pools.obtain(Sprite.class);
newEnemy.set(enemy); //I recommend renaming your `enemy` variable to something like `prototypeEnemy` for clarity
newEnemy.setPosition(200, 700); //need to start it at correct location.
enemies.add(newEnemy);
}
Finally, in your draw method (which is the wrong place for updates) you're trying to move only the most recent enemy created, instead of moving all of them. Note that every iteration of the loop is affecting the same instance: newEnemy, which is only the last enemy you created.
Here's how I would revise your class.
1) The movement speed should be a constant, measured in world units per second, so declare something like this at the top of your class:
private static final float ENEMY_SPEED = -120f;
2) At the bottom of your update() method, you can add this to cause all of your enemies to move:
for (Sprite sprite : enemies){
sprite.translateY(deltaTime * ENEMY_SPEED);
}
3) Under that, you can add a check for when they are off screen, so you can remove them. The iterator instance must be used to avoid a ConcurrentModificationException.
Iterator<Sprite> enemyIterator = enemies.iterator();
while (enemyIterator.hasNext()){
Sprite sprite = enemyIterator.next();
if (sprite.getY() + sprite.getHeight() < screenBottom) //screenBottom is something you can calculate from your camera like camera.getPosition().y - camera.getHeight()/2
removeEnemy(sprite);
}
4) And to remove them, since you're using pooling, you should put them back in the pool when you finish with them
private void removeEnemy(Sprite sprite){
enemies.remove(sprite);
Pools.free(sprite);
}
5) In your draw method, remove the second for loop, now that we're handling the position update in the update method.

Removing spheres

I have finnaly managed to make my program detect collision between two balls that I have created in Java-3D; the player ball and the enemy ball. Now the problem is that I don't know how to make the player ball be removed when it collides with the enemy ball. I have tried some simple stuffs like objTrans.removeChild(sphere); and objRoot.removeChild(objTrans); (objTrans is my TransformGroup and objRoot is my BranchGroup), in both cases I get this error message
Exception in thread "AWT-EventQueue-0" javax.media.j3d.RestrictedAccessException: Group: only a BranchGroup node may be removed
I also tried objRoot.detach(); but then I get the error message:
Exception in thread "AWT-EventQueue-0" javax.media.j3d.CapabilityNotSetException: BranchGroup: no capability to detach
I don't know any other ways to make the ball be removed. Please Help.
I came across the same problem when designing a game myself. The solution that I found worked best was to store the objects that could possibly be destroyed in a list which I could iterate over and delete elements whenever necessary.
A simple code example. Each time you call updateModel (), a BranchGroup is removed, it is then updated with the new shape, and then added again
private BranchGroup mapGroup = null;
public void updateModel (....)
{
Shape3D shape;
// Update 3D primitives
if (mapGroup != null) // remove previous 3D model
object.removeChild (mapGroup);
shape = facesTexturedShape (....);
if (shape != null) // add new 3D model if non-null
{
mapGroup = new BranchGroup ();
mapGroup.setCapability (BranchGroup.ALLOW_DETACH);
mapGroup.addChild (shape);
object.addChild (mapGroup);
}
}

Categories