Bazooka - shoot in mouse direction


To move a game element to the mouse pointer, to shoot in the mouse direction or to look in the mouse direction, these are all application cases that occur more often in games depending on the genre. So a not unimportant little math task in game development.

cosine, sinus, and arc tangent2

We will need these three friends to shoot with the bazooka in mouse direction. But don't worry, it won't be too complicated. So, how do we manage to turn our bazooka (attention: irony) in the direction of the mouse pointer?

, which is surprisingly well pixelated by me?

Look in mouse direction with atan2

Before we get to atan2 we need mouse coordinates that are relative to the game world. We don't get the desired result if we use global ones.

// Relative to the window. That's how it works. 
// But! Only as long as the window is not enlarged/reduced!
sf::RenderWindow app;
sf::Vector2f windowMouse= sf::Mouse::getPosition(app);

// Relative to the game world.
// This is how it works even if the window size is changed.
sf::Vector2f mouse = app.mapPixelToCoords(windowMouse);

Now atan2 comes into play to do the actual job.

float rad = atan2(mouse.y - bazooka.y, mouse.x - bazooka.x);

And we have the angle in RADIANT. It is important here that first the Y coordinates and in the second parameter the X coordinates are subtracted from each other!

Radiant and Degree

The reason why I wrote Radiant big and thick earlier is a simple one. Please pay attention to which unit your framework or engine expects as parameter. Since I'm not a math genius, I used to ignore that a lot in the past and have been pretty desperate to find bugs.

SFML 2.5

SFML 2.5 expects a value in Degree as parameter for setRotation. So we have to convert the return value received from atan2 to radiant to degree. This works as follows.

Vielleicht auch interessant
Firce - HTML5 Spiel programmieren (easy)
"Firce" - HTML5 Spiel programmieren (easy)

Anleitung: Schnell ein einfaches und cooles Spiel mit HTML5 entwickeln.

float deg = rad * 180 / 3.141;

3.141... is the constant PI. Now you only have to set the angle with setRotation and see there, the bazooka always looks in mouse direction.


Shoot in mouse direction

This task requires minimally more effort. In principle, we only need the angle in radians that we had already calculated using atan2. Now we use it for cos and sin respectively.

float dx = cos(rad);
float dy = sin(rad);

It is important that cosine and sine always expect a value in radians. The obtained values only have to be inserted into a move function and see there, the Bazooka ball flies in the mouse direction.

shot.move(dx * speed * frametime, dy * speed * frametime);

continuous (external)

Who wants to read more about trigonometry can read this article:

Leave a like or comment (~‾▿‾)~
Name Text