Moving a game object up and down in Java

Started by
20 comments, last by Nicholas Kong 11 years, 2 months ago

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
		SetXPosition(paddleArea.Right
			+ this->dimensions_.x);
	}
	// Else speed must be greater than 0, travelling right.
	else
	{
                // drag the ball out of the right paddle
		SetXPosition(paddleArea.Left
			- 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.

Advertisement

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

This topic is closed to new replies.

Advertisement