Character "shoots" toward where the worldMouseX and worldMouseY is

Hello! I have a student who is creating a game. He has a sprite who rotates to face the direction of the worldMouseX and worldMouseY. He wants a “laser” to shoot in the direction he is facing, but we can’t figure out how to do this. Suggestions?

Greetings @jacqueline.matsko,

I personally have faced a problem like this before and I believe I have found a solution to this problem.
(This involves math).


If you wanna find the direction, use the function atan2. (I will show an example)

var dir = atan2(World.mouseY-player.y,World.mouseX-player.x);

World.mouseY and World.mouseX are the targets.

If you wanna make it move at that direction, you can use
bullet.setSpeedAndDirection(speed, dir)
(If you are curious what to put for speed, you just put a number).


If you also do not know how to make a bullet, I will also explain of how to make a bullet.

#1. Make a group for the bullets (optional if you don’t have multiple screens in your game)
var lasers = createGroup(); //remember these variable names i will show you are optional, you can name them whatever

#2. Create an event where the player does a certain action, it will perform it.

if (keyWentDown("space")) { //im using space as an example. you can do whatever
 
}

#3. Create a sprite in the event

if (keyWentDown("space")) {
 var laser = createSprite(player.x, player.y);
  laser.setAnimation("something_laser_i_dont_know");
 //customize the sprite if you would like
}

#4. Add the laser to the group that you made

if (keyWentDown("space")) {
 var laser = createSprite(player.x, player.y);
  laser.setAnimation("something_laser_i_dont_know");
  //customize the sprite if you would like and remember to make it move
  lasers.add(laser);
}

#5. In the draw function, put:
drawSprites(lasers);


I hope this has helped you!

1 Like