I am currently working on a game using javascript and processing.js and I am having trouble trying to figure out how to move stuff diagonally. In this game, there is an object in the center that shoots other objects around it. Now I have no problem moving the bullet only vertically or only horizontally, however I am having difficulty implementing a diagonal motion for the bullet algorithm.
In terms of attempts, I tried putting on my math thinking cap and used the y=mx+b formula for motion along a straight line, but this is what my code ends up looking like:
ellipse(shuriken.xPos, shuriken.yPos, shuriken.width, shuriken.height); //this is what I want to move diagonally
if(abs(shuriken.slope) > 0.65) {
if(shuriken.targetY < shuriken.OrigYPos) {
shuriken.yPos -= 4;
} else {
shuriken.yPos += 4;
}
shuriken.xPos = (shuriken.yPos - shuriken.intercept)/shuriken.slope;
} else {
if(shuriken.targetX < shuriken.OrigXPos) {
shuriken.xPos -= 4;
} else {
shuriken.xPos += 4;
}
shuriken.yPos = shuriken.slope * shuriken.xPos + shuriken.intercept;
}
The above code is very bad and hacky as the speed varies with the slope of the line.
I tried implementing a trigonometry relationship but still in vain.
Any help/advice will be greatly appreciated!
Think of it this way: you want the shuriken to move
spixels. If the motion is horizontal, it should movespixels horizontally; if vertical,spixels vertically. However, if it’s anything else, it will be a combination of pixels horizontally/vertically. What’s the correct combination? Well, what shape do you get if you projectsdistance in any direction from a given point? That’s right, a circle with radiuss. Let’s represent the direction in terms of an angle,a. So we have this picture:How do we get the
xand they? If you notice, we have a triangle. If you recall your trigonometry, this is precisely what the sine, cosine, and tangent functions are for. I learned their definitions via the mnemonic SOHCAHTOA. That is: Sin (a) = Opposite/Hypotenuse, Cos(a) = Adjacent/Hypotenuse, Tan(a) = Opposite/Adjacent. In this case, opposite of angleaisy, and adjacent of angleaisx. Thus we have:Solving for
xandy:So, given the angle
a, and that you want to move your shurikenspixels, you want to move its * cos(a)horizontally ands * sin(a)vertically.Just be sure you pass
ain radians, not degrees, to javascript’sMath.sinandMath.cosfunctions:This may be why your trigonometric solution didn’t work as this has bitten me a bunch in the past.