This site requires JavaScript, please enable it in your browser!
Greenfoot back
gijsdevries
gijsdevries wrote ...

2023/3/21

I need the bullet to follow my mouse

gijsdevries gijsdevries

2023/3/21

#
I made a game where I need a bullet to follow the mouse. It all works fine but the bullet keeps following the coordinates of the mouse but i need the bullet to go in the direction of the coordinates of the mouse when the shot was fired. Any suggestions?
danpost danpost

2023/3/22

#
gijsdevries wrote...
I made a game where I need a bullet to follow the mouse. It all works fine but the bullet keeps following the coordinates of the mouse but i need the bullet to go in the direction of the coordinates of the mouse when the shot was fired. Any suggestions?
When creating a bullet, place it at the click point and rotate it towards its source point. Then move it to (set its location at) the source point and turn it 180 degrees.
gijsdevries gijsdevries

2023/3/22

#
danpost wrote...
gijsdevries wrote...
I made a game where I need a bullet to follow the mouse. It all works fine but the bullet keeps following the coordinates of the mouse but i need the bullet to go in the direction of the coordinates of the mouse when the shot was fired. Any suggestions?
When creating a bullet, place it at the click point and rotate it towards its source point. Then move it to (set its location at) the source point and turn it 180 degrees.
Could you maybe give an example? right now I have this. The bullet only spawns at the coordinates of the mouse (a kogel means a bullet).
getWorld().addObject(kogel, mouseinfo.getX(), mouseinfo.getY());
kogel.setRotation(getRotation());
danpost danpost

2023/3/23

#
gijsdevries wrote...
Could you maybe give an example? right now I have this. The bullet only spawns at the coordinates of the mouse (a kogel means a bullet). << Code Omitted >>
I think all you need do is:
getWorld().addObject(kogel, getX(), getY());
kogel.turnTowards(mouseinfo.getX(), mouseinfo.getY());
Note that if your bullet moves too slow (less than maybe 5 pixels per move), the aiming will not be accurate -- maybe so inaccurate that it looks totally off. For the extreme example, if moving only 1 pixel per move, the movement will either be horizontal or vertical; no other angles will be possible unless you use a smooth moving engine (QActor or SmoothMover subclass of Actor). However, even moving at quite fast speeds, the aiming may be still slightly off without a smooth moving engine.
You need to login to post a reply.