Discord
Login
Community
DARK THEME

How To Code Bullet Direction?

I'm currently working on a top-down project that utilizes a crosshair mechanic, controlled by the mouse when it comes to aiming. I'm not entirely sure how to program the bullet going in the direction of the crosshair when the left mouse button is clicked. Could anyone suggest a solution or an example that might clarify this for me?

Sine and cosine! I'd recommend looking into basic trigonometry so you can understand it, but if you want to get the angle to the mouse (in degrees), you can do (playerY is the y position of your player, and playerX is the x position)

bulletAngle = atan2d(mouse.y-playerY, mouse.x-playerX)

and then in update (bulletAngle is defined above when you shoot (not in update, that will cause the bullet to always turn to mouse) and bulletSpeed is how fast you want the bullet to move)

bulletX += cosd(bulletAngle)*bulletSpeed
bulletY += sind(bulletAngle)*bulletSpeed

Thank you for your help! I'm trying to implement this into my code but I feel I might be putting "bulletAngle = atan2d(mouse.y-playerY, mouse.x-playerX)" in the wrong part of my code OR I'm utilizing it wrong.

This is what it looks like in my code: ballAngle = atan2d(mouse.y-hero.y,mouse.x-hero.x) //I have an object known as hero with attribute of 'x' and 'y.' This snippet of code is in its own source and not within any function. Furthermore I've placed the second snippet within my "shoot" function which is called within my 'update' function in my main source.

It seems to not work as I wish it to. What could I be doing wrong?

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community