go2d-gamesbulletphysics

How do I get my bullets move in the direction of the mouse cursor with always the same speed?


I got a problem with a game of mine. It is a top down shooter and if I am pressing the mouse a bullet should shoot in the direction of where the mouse was. The problem is that with my attempt the bullet would be faster when the distance between player and mouse is bigger and slower when the distance is smaller. I want that speed to be constant no matter what.

This is what my logic looks like so far:

In the constructor I give the bullet a xDir and a yDir: b.xDir = (float64(mouseX) - b.x) b.yDir = (float64(mouseY) - b.y)

Then in the update function I multiply it with deltaTime and the bullets movementSpeed and add it to the corresponding position axis: b.x += b.movementSpeed * dt * b.xDir b.y += b.movementSpeed * dt * b.yDir

With that logic the bullet speed is depending on the distance between mouse and player. I would appreciate an answer which would not mess with the speed but would still go in the direction of the mouse click.

Thanks in advance :)


Solution

  • The problem is that your b.xDir and b.yDir values are directly calculated from the distance, so the farther the mouse click from the player, the higher the values will be. When they are multiplied by dt, it makes them move faster.

    What you need is to normalize your vector, so you only have a direction and not a magnitude carried over from the original click distance. You probably want to use a vector library, but if you're going to do it by scratch, it would look like this:

    magnitude := math.Sqrt(b.XDir * b.xDir + y.xDir * y.xDir)
    b.xDir /= magnitude
    b.yDir /= magnitude
    

    At that point the value of your variables is purely a direction, and multiplying by speed and dt will have the expected effects.