Public Group

# Need help with all speed in Pong game in C#

This topic is 3645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi I've created a simple 2d pong game in C#. However, i'm having a little problem with calculating the ball speed.. when a ball is created it is positioned in the middle of the window and then the direction is random. Code for the ball creation is here: protected void createBall() { ball = new Ball(2.0f, createBallDirection()); ball.ballTexture = Content.Load<Texture2D>("ball"); ball.ballPosition = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2); } createBallDirection() returns a Vector2 where X and Y are random numbers between -5 and 5. In my game loop I calculate the new position like this: ball.ballPosition += ball.ballSpeed * ball.ballDirection; ball.ballPosition is a Vector2 and ball.ballSpeed is a float. The problem is then that the ball speed varies based on the direction.. f.eks. if the direction vector is (2,-2) the ball will move a bit slowly, but if the direction vector is (5,1) it moves faster across the screen.. So I need help on thinking this one out.. I simply cannot get it to move equally fast at all directions.. Thank you in advance

##### Share on other sites
You need to normalize the ball's direction vector.

mag = sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z))

direction.x = direction.x / mag
direction.y = direction.y / mag
direction.z = direction.z / mag

I also suggest multiplying the ball's movement by the time since the last update, so that the framerate of your application doesn't affect the speed of the ball either.

##### Share on other sites
Thank you, it worked perfectly :)

Forgot to mention that I use the XNA framework so the framerate is already fixed. :)

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634051
• Total Posts
3015244
×