Reputation: 1233
This is an extraordinarily simple question but I can't find the answer so I'm bracing myself for the ridicule.
Given a vector:
(in this case going from 2,3 to 9,9) I want to start at 2,3 and travel up the vector a distance of length l.
How do I calculate the new point (x,y)? Thanks!
Here's the code (after implementing Dmitry's equation):
double MetersMoved = ((Dinosaurs[i].Speed * 1000) / (60 * 60)) * TimeStepInSecs;
double fi = Math.Atan2((Dinosaurs[i].Goal.Y - Dinosaurs[i].Head.Y),(Dinosaurs[i].Goal.X - Dinosaurs[i].Head.X));
Dinosaurs[i].Head.X = Dinosaurs[i].Head.X + MetersMoved * Math.Cos(fi);
Dinosaurs[i].Head.Y = Dinosaurs[i].Head.Y + MetersMoved * Math.Sin(fi);
The dinosaurs are aligning themselves on the correct vector but not advancing (one should be moving 2 pixels and the other about 7).
Dmitry's answer is correct.
Upvotes: 1
Views: 7192
Reputation: 1653
You can find the length of the current segment and calculate the proportion of which you want to expand (or contract) the segment.
(2,3) to (9,9)
(9-2)^2 + (9-3)^2 = (c)^2
7^2 + 6^2 = (c)^2
define a such that (a^2)(c)^2 = l^2
(a^2)(7^2 + 6^2) = (a^2)(c)^2 = l^2
(7a)^2 + (6a)^2 = (ca)^2 = l^2 => l = ca => a = l/c
You can then extend the x and y coordinate acordingly
(2+7*l/c, 3+6*l/c) is your new endpoint.
Point p1 = new Point(2.0, 3.0);
Point p2 = new Point(9.0, 9.0);
double l = 25.0;
Point vector = new Point(p2.X - p1.X, p2.Y - p1.Y);
double c = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y);
double a = l / c;
Point p3 = new Point(p1.X + vector.X * a, p1.Y + vector.Y * a);
//Writes "25"
Console.WriteLine(Math.Sqrt((p3.X - p1.X) * (p3.X - p1.X) + (p3.Y - p1.Y) * (p3.Y - p1.Y)));
Point
is just a struct I to hold a double X and double Y.
Upvotes: 3
Reputation: 186668
The solution (trigonometry) could be like this:
// Origin point (2, 3)
Double origin_x = 2.0;
Double origin_y = 3.0;
// Point you are moving toward
Double to_x = 9.0;
Double to_y = 9.0;
// Let's travel 10 units
Double distance = 10.0;
Double fi = Math.Atan2(to_y - origin_y, to_x - origin_x);
// Your final point
Double final_x = origin_x + distance * Math.Cos(fi);
Double final_y = origin_y + distance * Math.Sin(fi);
Upvotes: 1