0

I am totally stumped on this one. I'm using C++ and SFML 1.6 for a game I'm developing, and I have no bloody idea. How do I make projectiles (like bullets)? I just don't understand it. It could be my lack of sleep but I don't know.

So my question is how do I create a Sprite that moves in a definite direction based on where the mouse is? (Think of a top down shooter with mouse aiming)

nvoigt
  • 61,531
  • 23
  • 73
  • 116
Lemmons
  • 1,598
  • 4
  • 21
  • 30

2 Answers2

2

Easiest solution: If the mouse is at Mx,My and the ship is at Sx,Sy then calculate the direction from the ship to the mouse: Dx=Sx-Mx Dy=Sy-My

Now normalise D (this means scale it so that it's length is one):

DLen=sqrt(Dx*Dx + Dy*Dy)
Dx/=DLen;
Dy/=DLen;

Now Dx is the distance you want to move the bullet on the x axis in order to get bullet speed of 1.

Thus each frame you move the bullet like so (position of bullet: Bx,By Speed of bullet: Bs [in pixels per millisec] Frame time Ft[in millisec])

Bx=Bx+Dx*Bs*Ft
By=By+Dy*Bs*Ft

This give you a bullet that moves towards the mouse position at a speed independent of the direction of the mouse or framerate of the game.

EDIT: As @MSalters says you need to check for the DLen==0 case when the mouse is directly above the ship to avoid division by zero errors on the normalise

Elemental
  • 7,079
  • 2
  • 25
  • 29
  • 1
    Of course, when `Mx==Sx && My==Sy`, you'll shoot yourself in the foot. – MSalters Jan 31 '11 at 11:40
  • Okay this makes sense but: Arrrrgghhh. Maths. Thanks though. – Lemmons Feb 01 '11 at 04:57
  • 1
    If you can get a 2-d vector library then this stuff becomes half as much math and code – Elemental Feb 01 '11 at 07:34
  • 1
    I'd like to underline @Elemental's comment here. Using more high-level vector algebra will massively simplify game development. In C++, there are [many vector algebra libraries available](http://stackoverflow.com/q/1380371/5427663). There is also [Thor](http://www.bromeon.ch/libraries/thor/v2.0/doc/_vector_algebra2_d_8hpp.html) which allows you to work with SFML's vector types directly. – TheOperator Oct 10 '15 at 10:22
0

One way to do it is to make the bullet face the mouse and then move it across the x and y axis by using trigonometry to find the hypotinuse from the angle. I don't think i explained this very well, so here the code to make a sprite move from its rotation:

void sMove(sf::Sprite& input,float toMove, int rotation){
bool negY = false;
bool negX = false;
int newRot = rotation;
if (rotation <= 90){
    negY = true;
}
else if (rotation <= 180){
    //newRot -= 90;
    negY = true;
}
else if (rotation <= 360){
    newRot -= 270;
    negY = true;
    negX = true;
}
float y = toMove*cos(newRot*PI/180);
float x = toMove*sin(newRot*PI/180);
if (negY){
    y = y*-1;
}
if (negX){
    x = x*-1
}
input.move(x, y);
}
aedo
  • 1
  • 1