There have been many posts where other people have asked the same question! People usually say to just use the arcade-sprite-util extension, which has a “get angle between (sprite) and (sprite)” and a “set (sprite) velocity at angle () and speed ()”, which can be combined to make a projectile shoot from one sprite towards another.
Use the “Set (sprite) to projectile from (the enemy sprite) with velocity…” block in the Sprites tab to create projectiles that will get destroyed when they hit walls and stuff.
If you wanted to make the math yourself, it would be like this…
Math explanation!
(player is the player sprite, and enemy is the sprite shooting at the player)
In order to find the correct values of velocity x and y that will send the projectile in the direction of the player, we could just set the velocity to be the difference between the player position and the enemy position, aka “velocityX = player x - enemy x” and same for Y, but this will make the projectile move faster when the player is farther away.
To fix this, we need to “normalize” the values, which just means that we need to make the overall speed of the projectile the same every time.
First you need the distance between the player and the enemy:
Let distance = Square root of ( (enemy x - player x)^2 + (enemy y - player y)^2 )
(“^2” means “to the power of 2”, in other words you square the values)
Then you need to divide the distance you want the projectile to travel by the actual distance:
Let norm = (speed you want) / distance
This “distance” will control the speed of the projectile, so you will probably want to mess around with the value until the speed “feels right”.
Lastly you need to “normalize” the x and y velocities by multiplying those x and y distances:
VelocityX = (player x - enemy x) * norm
And velocity Y is the same but with player y and enemy y
You can make VelocityX and Y into variables, or just stick the math blocks right into the “set sprite to projectile from enemy with velocity…” block.
Honestly, it would be easier to use Sprite Util