I'm working on a school project in Processing, and I'm running into a bit of a problem. I have a bulletList
array to that's looped in my draw()
class, with Bullet
objects that are initialized when the spacebar is pressed.
if(key==' '){
float currentPlayerX=playerX;
float currentPlayerY=playerY;
float currentMouseX=mouseX;
float currentMouseY=mouseY;
bullets.add(new
Bullet(currentPlayerX,currentPlayerY,currentMouseX,currentMouseY));
}
//in the draw method()
for(Bullet b: bullets){
b.shoot();
}
class Bullet{
float bulletX;
float bulletY;
float rise;
float run;
Bullet(float pX, float pY,float mX,float mY){
//I get the slope from the mouse position when the bullet was instantiated
to the bullet position (which starts at the player position and is
incremented out by the slope as shoot() is called
rise=(mY-pY)/12;
run=(mX-pX)/12;
bulletX=pX;
bulletY=pY;
}
void shoot(){
fill(255,0,0);
rect(bulletX,bulletY,7,7);
bulletX+=run;
bulletY+=rise;
}
}
Essentially, the trajectory of the Bullet
is determined when the bullet
object is first created, the end goal being: move the mouse to the desired direction, press the space bar, and watch the bullet go. The problem is the velocity is never constant. When the mouse is far away from the Player
object, the speed is fine, but as the rise
and run
gets smaller as the mouse moves closer, the Bullet
speed becomes really small. I actually ended up messing around with the rise
and run
floats, and dividing them by 12, because at their initial value the Bullet
wasn't visible.
I've heard the PVectors
are a good way to have velocity in games, but we never covered them in my class and I don't really know where to start. I've also tried dividing & multiplying by a constant to try to get a constant speed, but I'm basically shooting in the dark here. Any help is much appreciated, and please ask if you have any questions about how my code works; I'm happy to clarify.
What you're looking for is some basic trigonometry. Basically I'd break your problem down into smaller steps:
Step one: Get the angle between the source of the bullet and the mouse. Google "get angle between two points" for a ton of resources.
Step two: Convert the angle to a unit vector which is an x/y pair that you can think of as a heading. Google "convert angle to unit vector" for a ton of resources.
Step three: Multiply those x and y values of that unit vector by some speed to get the amount you should move the bullet each frame.
The PVector
class does offer some of this functionality. Check out the reference for a list of useful functions.
If you're still stuck, please narrow your problem down to a MCVE. This can be as simple as one circle that follows the mouse. Good luck!