Ask coding questions

← Back to all posts
How do I get the bullet to come out of the player and twords the direction of the clicked area JS
h
okalisl

I have been working on a game and have been trying to get shooting working. It has been all working except for making a bullet shoot in the direction of the clicked area. Anyone know how to fix this?

Answered by SixBeeps [earned 5 cycles]
View Answer
Voters
okalisl
Comments
hotnewtop
SixBeeps

Yay I get to talk about math for once.

Here we have a (B)ullet, and a (C)ursor.

We can make a right triangle out of this. Lets name the important sides X and Y.

If we want the bullet to move to the cursor, we can just move it by (X, Y). But that's not what we want.

Instead, we can move it in the same direction as the hypotenuse, but make the actual distance it travels smaller. Then, we can keep doing that every frame, and it'll look like it's moving towards the cursor!

But how do we do that? Well, first we want to scale the hypotenuse down to a size of 1. To do that, we can divide the size of each part of the triangle by the size of the hypotenuse. When we do that, the proportions stay the same, but the hypotenuse goes to 1 (since you're dividing it by itself).

Then you can scale (multiply) that to something manageable. Really that's up to taste.

Right now, your code isn't structured to handle bullet-specific variables. We can change that though. Change your code to look something like

Then we can assign the proper movement deltas after we make

Then when you update the bullet, move it by (b.dx, b.dy). You should also multiply by dt() to make sure the velocity is consistent.

ch1ck3n

@SixBeeps +1 lemme copy paste for my math homework

okalisl

Thanks so much for the explanation @SixBeeps. One thing-- there is an error. Did I place it correctly?

SixBeeps

@okalisl The code for calculating dx and dy should be right after you create the bullet, not in the update.

okalisl

Alright @SixBeeps. It still seems funny though. Is it still wrong?