Turn body box2d invisible on click or press
As you can see in the picture, I have a box2d world with some bodies. I also have an inputproccessor, but I cannot show that the boxes disappear when I click on them.
Basically I want my mouse clicks to touch to check if it intersects with the body / box. If so, I want this body to disappear. Can anyone point me in the right direction? I tried to create a scene and turn the bodies into buttons to make the onClickListen work, but it turned out to be messy and didn't work.
source to share
Ok, I managed to solve this on my own. This is the code I wrote in my inputproccessor class. You need to declare hitBody at the top of the class as btw body which is not shown below.
Vector3 testPoint = new Vector3();
QueryCallback callback = new QueryCallback() {
@Override
public boolean reportFixture(Fixture fixture) {
if(fixture.testPoint(testPoint.x,testPoint.y)){
hitBody = fixture.getBody();
return false;
}else{
return true;
}
}
};
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
GameRender.cam.unproject(testPoint.set(screenX,screenY,0));
hitBody = null;
GameWorld.physicsWorld.QueryAABB(callback, testPoint.x - 0.0001f,
testPoint.y - 0.0001f,
testPoint.x + 0.0001f,
testPoint.y + 0.0001f);
for(DynamicBox b:GameWorld.BoxList){
if(hitBody == b.boxerino){
System.out.println("click detected");
b.shouldRemove = true;
}
}
return false;
}
There is a boolean which I believe is true if the body is clicked. (b.shouldRemove = true) After that I go to my update loop and remove the body as well as the body of the factory from the array.ist class
public void update(float delta){
physicsWorld.step(delta, 2, 2);
for(int i=0;i<BoxList.size();i++){
DynamicBox b = BoxList.get(i);
if(b.shouldRemove==true){
physicsWorld.destroyBody(b.boxerino);
BoxList.remove(i);
}
}
}
source to share