This structure is used for points as well as vectors eg: MyData point_a Here MyData is a structure that allows two components: x and y. Unfortunately I don't know java but I can provide you a c++ example: struct MyData //That would be public class in java I beleive
Projectile intersection vector 2d code#
In the code you would use the same data structure. That's a win :)ĮDIT2: For consistence and clarity, I used the word vector and position but these "concepts" are the same: a point has an X and Y component as well as a vector. ) nor confusing conversions with radians. This code will move your projectile 10 units (let's say pixels) towards your mouse.ĮDIT: Note that with this method you don't need to use trigonometry to compute the normalized vector that means that neither you have precision loss (floats, pi. The point of it ? Moving your projectile towards a point with a fixed 'speed', like this: projectile.pos += u * 10 This procedure is normalizing where you just get the direction of a vector and completely ignore its length (sometimes called 'magnitude').Īdding this vector u to your position will move your object 1 unit away from its current position. how do we get this direction ? Well, it's easy, the formula is u = V/length(V) The idea here is to get a direction from your projectile (point A) to your mouse or whatever object (point B).
It will instantly move the projectile to the mouse because - well - you're asking to move the projectile to the mouse. If you have something like this V = mouse.pos - projectile.pos However, this vector is pretty much useless because the length of it is the length of the line between A and B. Since B and A have two components, we can translate this into V = (xB-xA, yB-yA) To get the vector between A and B, you have to do the following formula: V = B - A.
Let's assume that you have two given points A = (x1, y1) and B = (x2, y2). You need to learn a little bit more about vectors but I'm going to explain it anyways.įirst of all, let's say that your 'game unit' is in pixels and that points (coordinates) and vectors have two components x and y.