Skip to main content
gamedev.net
🔒 Locked 🎮 Unity

Targeting for shooting

Started by bd36 3 replies 1.1k views
Original Post
bd36
bd36
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?
blewisjr
blewisjr
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.
alvaro
alvaro
You don't need angles at all. Using vector notation:
diff = target - object;
bullet_velocity = bullet_speed * diff / length(diff)
bd36
bd36
Thanks alvaro that worked great. I just had to multiple the y component by -1 because positive y is down instead up like usual.
BeerNutts
BeerNutts
If you want an example, I do this exact thing in my old blog post here:
http://2dgamemaking.blogspot.com/2011/10/bullets-added.html

Look at the

SmashPcBullet::

SmashPcBullet

() constrcutor in the middle of the post, I do this:


cpFloat Angle = pPlayerBody->a;

mpBody->p = pPlayerBody->p;
mpBody->v.x=cos( Angle)*mBulletDetails.Speed;
mpBody->v.y=sin( Angle)*mBulletDetails.Speed;

cpBodySetAngle(mpBody, Angle);

It's using chipmunk physics objects, but it gets the angle the player is facing in radians, then calculates the x and y velocites (v.x and v.y) based on the Angle and Speed of the bullet.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.