Search code examples
vectortransformationcubejava-3d

Java3D: I'm trying to place 4 cubes next to each other. Why do I get only one cube?


I'm basically trying to create a shape via Java3D and only one cube appears on the screen. I want to put the cubes in a line or a column, but I just can't figure out what I'm doing wrong. Obviously this is only part of the code, only the method to create cubes.

private void createCubes() {

                Cuboid box = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box2 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box3 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box4 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);


                Vector3f vector = new Vector3f(0f, .3f, 0f);




                TransformGroup tg = new TransformGroup();
                Transform3D transform = new Transform3D();
                transform.setTranslation(vector);

                tg.addChild(box);
                tg.setTransform(transform);
                tg.addChild(box2);
                tg.setTransform(transform);
                tg.addChild(box3);
                tg.setTransform(transform);
                tg.addChild(box4);
                tg.setTransform(transform);






                rootGroup.addChild(tg);

Solution

  • Why do you think your code should put the cubes in a row/column? They all have the same coordinates, sizes, transforms and belong to the same transform group... You have to create a new transform and transform group for each box you want placed separately.

    Something like this should do the trick for 4 boxes:

    TransformGroup getNewBox(float hpos) {
      Cuboid box = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
      TransformGroup tg = new TransformGroup();
      Transform3D transform = new Transform3D();
      Vector3f vector = new Vector3f(0f, hposf, 0f);
      transform.setTranslation(vector);
      tg.addChild(box);
      tg.setTransform(transform);
      return tg;
    }
    
    {
      rootGroup.addChild(getNewBox(0f);
      rootGroup.addChild(getNewBox(0.3f);
      rootGroup.addChild(getNewBox(0.6f);
      rootGroup.addChild(getNewBox(0.9f);
    }