Public Group

Targeting for shooting

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

Recommended Posts

Hello for my game I have a sprite that rotates to face a target. Currently the sprite rotates and follows the target as it should. However now I am trying to get the sprite to fire a bullet in the direction it is facing. Im fairly certain I have the right idea but am just missing something in the trigonometry.
 int targetX, targetY; targetX = front.getX(); targetY = front.getY(); rotation = atan2((targetY-y),(targetX-x)); rotation = rotation * (180/3.14159265); sprite.setRotation(1*rotation); fireRate.update(); if(fireRate.check2()) { bullets->push_back(Bullet(x,y,bulletSpeed*cos(rotation),bulletSpeed*sin(rotation),100)); }
I find the angle to rotate by taking the arctan of the differences in x and y between the sprite and the target. I am thinking that once I have this angle I should be able to take the cosine of that same angle and multiple it by the speed to get the x velocity of the bullet and sine for the y. The bullets shoot off at angles sometimes but in all sorts of directions. I think it has to do with the differences in domain between arctan and sine and cosine. So things end up being 180 degree off what they should or something. Any ideas?

Share on other sites
The sine and cosine of your ships angle will give you the vector the bullet needs to travel on aka the hypotenuse of the triangle you multiply the speed to the x and y components to move along the vector. Sorry I can't go into more detail I am at work and posting from my phone.

Share on other sites
You don't need angles at all. Using vector notation:
diff = target - object; bullet_velocity = bullet_speed * diff / length(diff)

Share on other sites
Thanks alvaro that worked great. I just had to multiple the y component by -1 because positive y is down instead up like usual.

Share on other sites
If you want an example, I do this exact thing in my old blog post here:

Look at the

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 19
• 36
• 9
• 16
• 75