Aaron Aaron - 1 year ago 65
Java Question

Issue in moving an object across the screen

can someone enlighten me.

I am doing a game were a ball needs to automatically be created and move across the screen from one corner to the other.

I was able to create balls and move them from the bottom right corner to the top left and vice versa, but I can't figure out how to do it from the bottom left corner to the top right.

Attached is some of the code and a graph of my logic.Logic of how the balls will move

case 1: // From one side to the other, in two axes

switch (subScenario) {
case 0: // Bottom right corner to top left corner.
posX = panelWidth;
posY = panelHeight;
directionX = (rnd.nextInt(2) + 1)*-1;
directionY = directionX;
case 1: // Top left corner to bottom right
posX = 0;
posY = 0;
directionX = (rnd.nextInt(2) + 1)*1;
directionY = directionX;
case 2: // Bottom left corner to top right corner
posX = 0;
posY = panelHeight;
directionX = directionY;
directionY = (rnd.nextInt(2) + 1)*-1;

Answer Source

If you want to move left to right, as in case 2, directionX must be positive. Therefore:

directionX = (rnd.nextInt(2) + 1)*1;

directionY should be negative, so:

directionY = directionX*-1;

Also, remember to put break after each case so that they all don't activate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download