• Create Account

## Moving a game object up and down in Java

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

21 replies to this topic

### #21stitchs  Members

1361
Like
0Likes
Like

Posted 19 January 2013 - 01:38 PM

I used a similar approach to what BeerNutts suggested, in that I check for the sign of the speed against 0, and execute code as appropriate. Below is what happens when the auto-moving ball collides with a paddle, but the same can be applied to your boundsY scenario.

void Ball::OnPaddleCollision(sf::Rect<float> &paddleArea)
{
// Check ball moving left.
if(speed2D_.x < 0)
{
// drag the ball out of the left paddle
+ this->dimensions_.x);
}
// Else speed must be greater than 0, travelling right.
else
{
// drag the ball out of the right paddle
- this->dimensions_.x);
}
// Do everything else the same regardless of which paddle hit.
// Negate the sign of the speed, this will always occur so duplicated
// code does not need to be handled in the if-else.
speed *= -1;

return;
}

...

// Then in the Game.cpp, the ball will always move in this
// basic example. So always add the speed on, and the direction
// will change based in the sign of the speed variable.
ballObject.x += speed;

I always move the ball, but in my example, if a collision has occured (which is what you are wanting to do when the monster goes past a bound point), I drag it away from the point of collision, so that it doesn't count as a collision on the next frame. In the same method, I reverse the speed, so that as soon as collision has occurred with that wall, it will never happen again as it now moves in reverse.

To explain the movement more, this is how the movement method works.

Pos.X += Speed

Pos.x = Pos.x(200) + Speed(30)

Once it collides with the right paddle, then the speed is negated: Speed(-30)

Pos.x = Pos.x(200) + Speed(-30), this equates to Pos.x -= Speed.

Because of the way that addition works, if you increment a number by a negative number, then it effectively subtracts that number, meaning you don't cause any unnecessary duplication of code.

Sorry if this seems a bit garbled, I write this off the top off my head, if you need any more explanation please ask as I am happy to correct any obscurities.

Regards,

Stitchs.

### #22warnexus  Prime Members

1535
Like
0Likes
Like

Posted 25 January 2013 - 10:02 PM

After a week of struggling, I finally got the monster to move up and down.   It was only possible because of everyone's feedback on the thread. I want to say Thanks!

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.