# Cubes are separating from each other

        public void spawnCube() {
cubes = new Array < Rectangle > ();
for (int i = 0; i < 3; i++) {
Rectangle cube = new Rectangle();
cube.x = xpos;
cube.y = ypos;
cube.width = width;
cube.height = height;
xpos += 28;
if (Gdx.input.justTouched()) {
score++;
}
}
}

public void moveCube() {
Iterator < Rectangle > iter = cubes.iterator();
while (iter.hasNext()) {
Rectangle cube = iter.next();
cube.x += speed * Gdx.graphics.getDeltaTime();
if (cube.x + cube.width > 800 || cube.x < 0)
speed = -speed;
}
}


The first method generates 3 cubes, the second one moves them from right to left and back. Cube size 15w 30h. Screen size 800w 400h.

The problem I have is that after 2 or 3 cycles of the cubes going from right to left, the cube on the left gets seperated from the other two. It seems that the other two cubes are pushing the first one out of place. How to prevent that from happening?

• 2 things : first: are you dealing with the collision with your boxes in any way? I can see some problems with your boxes overlaping at some point. Second : you are doing speed += 10 which is not what you want to do if the speed is negative Jan 17, 2017 at 16:37
• @realUser404 i removed that bit, I added that for testing and yes they are colliding, if there anyway to use static objects, that don't collide? that cannot overlay each other? Jan 17, 2017 at 16:42
• The reason they are overlaying is that they are not moving at the same speed at each step. Let's say you are moving to the left and your first box is the left one, if it reaches the border the direction will change but the left box' direction was left when the 2 other boxes' direction will be right which indeed causes the the cube on the left gets seperated from the other two problem Jan 17, 2017 at 16:52

All cubes hare the same speed, so when you update the first with a new position and detect the collision and negate the speed the cubes that are processed after the first one will move in the opposite direction of the first for one frame. That could cause the behaviour you are describing. One way to fix it can be to update all positions first and then calculate a new speed. You can also try having individual speeds per cube.
Let's say you are moving to the left and your first box to move is the left one, if it reaches the border the direction will change but the left box' direction was left when the 2 other boxes' direction will be right which indeed causes the the cube on the left gets seperated from the other two problem