I'm new to Java and coding. I'm trying to create a tower building game using Box2d for Processing. The premise is to build up a tower that has to resist a shot from a cannon. The tougher the tower, the higher the points.

To build the tower, you need to drag and drop blocks that will (eventually, once I've dealt with this part) form joints between them, to allow a tower to be built.

My problem comes when choosing options to build from. This is a screenshot of the game screen:

enter image description here

The intention is to click and drag on the screen for a block to appear, and cycle through orientations using keys to pick what you want while the mouse button is held down, while the object is selected. The mouse button is released, and the object can fall into place with its desired orientation.

The way I've found that works is to have an integer represent a state, and, when a key is pressed, the integer changes and the block's orientation changes with it. This is the code I've placed within the class to make this happen:

void changeOrientation()
  Vec2 pos = box2d.getBodyPixelCoord(body);

  if (currentBuildingBlockOption == 0)
  body.setTransform(pos, 0);

  if (currentBuildingBlockOption == 1)
  body.setTransform(pos, 90);

  if (currentBuildingBlockOption == 2)
  body.setTransform(pos, -45);

  if (currentBuildingBlockOption == 3)
  body.setTransform(pos, 45);

The code outside the class that I'm trying to call in the draw() function is this:

void updateBlockChoice()

{ if (buildingBlocks.size()>0) { BuildingBlock currentBlock = buildingBlocks.get(buildingBlocks.size()-1);

  if (mousePressed==true)


I think the error has to do with the fixed rotation, as I've seen on some other questions, although I'm pretty stumped. I'm also not sure if my method of going about it is the best way to do it. If anyone else has any better solutions, please do let me know.

Thanks for the help!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.