Jump to content
  • Advertisement
Sign in to follow this  
Herter

Need help with all speed in Pong game in C#

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Thank you, it worked perfectly :)

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!