Well, I've been thinking about this for a little while now. I'm trying to make something go from a random point A so that it will always hit point B in a straight line. It's actually harder then I originally thought (*raises fist* Damn you math!). For some reason I had no trouble implementing a sinus, but making a angled line is something that i can't wrap my head around.
I can make it go 'roughly' in the right direction with a bit of a simple hack, but like with the sinus movement I want a predictable, dead-on function. So if any of you have some wisdom to share on this matter, I would really appreciate it.
This is the current 'hack' version (http://arboris.hell-on-earth.net/stuff/Coell%20Decka%20Test%201.00.rar) Do not mind to enormous amount of bullets you can fire, they're just there to proof different point.
Usually one doesn't need trigonometry functions unless something actually turns.
The important thing is to only use floats for the calculations, they're faster as ints anyway. Only at the last step (drawing stuff), the coords are converted to ints.
What you do is this: calculate the vector (x;y) from A to B, that's (b.x - a.x;b.y - a.y)
Then normalize it (change its length to 1.0), then multiply it with the movement speed.
Actually, to reduce rounding errors, it's best to multiply, then divide by length.
So say the vector is float x, float y:
float l = Maths.Sqrt(x*x+y*y); //length
float speed = 5.0;
x = (x*speed)/l; // shrink vector
y = (y*speed)/l;
(x;y) has now a length of speed and goes in the direction from a to b.
Just add it to the coordinates of whatever is moving every frame.
Thanks for explaining the shrink vector. Worked like a charm.
test version 1.01 (http://arboris.hell-on-earth.net/stuff/Coell%20Decka%20Test%201.01.rar)
One thing that has always confused me is that every time you explain this procedure to someone(me included), is that you always name this bit "1":
Quote from: Khris on Mon 09/11/2009 17:31:48
float l = Maths.Sqrt(x*x+y*y); //length
Wouldn't that just make things harder to understand?
it's l for length, not 1. And I found it perfectly understandable. This isn't the beginners section after all, so he doesn't need to give a step by step guide on how to implement it.
Quote from: Arboris on Tue 10/11/2009 12:23:33
it's l for length, not 1
*impales head on biro*
I actually thought about using 'len' instead due to the resemblence to '1' but thought it didn't matter since the code is for once fine to copy and paste directly.