# 2D (vector?) question

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

## Recommended Posts

What should happen: (Using OpenGL, Dev-C++) Player character is at location px, py on a 2D plane. Mouse cursor is at location mx, my on that same plane. The player clicks the mouse, and the player character shoots a fireball from px, py to mx, my at some universal velocity. How I'm currently handling it: Start with an initial constant x and y velocity for the fireball which is currently either negative or positive 50. Add the difference from (px, py) - (mx, my). Using this method, the fireball correctly flies towards where the mouse cursor clicked. The problem: The speed of the fireball varies depending on how far mx, my is from px, py. I need the fireball to shoot at a universal speed. The solution: Someone on this messageboard tells me the correct equation/method to calculate the x/y velocity for the fireball so that it flies at a constant speed of my choosing. Har har. Honestly I'd spend an hour Googling this but I wouldn't know what to Google. I also haven't been able to find any programs that use this system AND offer source code.

##### Share on other sites

1. Calculate the vector difference between the two points: vd = (px, py) - (mx, my). You already do that [smile].

2. Turn this vector into a unit vector by diving by its distance: vd = vd / |vd|. Make sure you check for divide by zero.

3. Multiply the unit vector by the velocity of the fireball to get your speed: vf = k vd, where k = constant velocity of the fireball (50).

Hopefully that will do what you want it to.

##### Share on other sites
Quote:
 Original post by ScottNCSUHar har.Honestly I'd spend an hour Googling this but I wouldn't know what to Google. I also haven't been able to find any programs that use this system AND offer source code.

Did you try looking in a maths book? Vector algebra to be precise. Then you can learn to generalise the issue to other cases.

Alternatively Trapper Zoid offers a solution.

##### Share on other sites
Fireball is working great, thanks Trapper Zoid. Now to tackle 2D collision detection for OpenGL.

##### Share on other sites
If you only want collision approximation you can do that with a quick bounding box class (structure) and 1 function :-)

• ### What is your GameDev Story?

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

• 9
• 13
• 9
• 9
• 15
• ### Forum Statistics

• Total Topics
634073
• Total Posts
3015343
×