Hey all,
I’m working on a game that involves magnets on both poles, that can either attract or repulse a ship. The degree of attraction/repulsion is based on the size (quote-unquote mass) of the magnets. The magnets also have a field that has less and less of an effect on the ship the further the ship gets from the magnet. The size of this field is also based on the “mass” of the magnet.
Here’s the code for how I move the ship (the majority of it anyway):
if(upKeyDown){
vy += Math.cos((ship.rotation*Math.PI)/180) * shipSpeed;
vx += Math.sin((ship.rotation*Math.PI)/180) * shipSpeed;
}else{
vx *= friction;
vy *= friction;
}
if(leftKeyDown){
ship.rotation -= rotateSpeed;
}
if(rightKeyDown){
ship.rotation += rotateSpeed;
}
if(downKeyDown){
trace("down");
}
ship.x += vx;
ship.y -= vy;
if (ship.x > stage.stageWidth){
ship.x = 0;
}else if (ship.x < 0){
ship.x = stage.stageWidth;
}
if (ship.y > stage.stageHeight){
ship.y = 0;
}else if (ship.y < 0){
ship.y = stage.stageHeight;
}
I think I can get ahold of the physics formulas behind magnets easily enough, but my issue is figuring out how to apply them to the ship. I found this formula in a video tutorial:
for(var i:Number = 0; i < numMagnets; i++){
dx = ship.x - magnet.x;
dy = ship.y - magnet.y;
trace("dx: "+dx+", dy: "+dy);
mag = dx * dx + dy * dy + 1;
trace("mag: "+mag);
fx -= coef * dx / mag;
fy -= coef * dy / mag;
}
But applying it doesn’t seem to work right. It grabs my ship and tucks it in the upper left corner. I traced dx and dy and found this is because it puts the ship far into the negatives, which of course I don’t allow due to my Pac-man effect of warping the ship to the opposite side of the screen should it go beyond its bounds.
Is that more or less the right bit of code? What is it that needs to be fixed? Any help or insight is appreciated!