I am drawing a circle of _radius = 50 pixels in the center of the form:
g.FillEllipse(Brushes.Red, this.ClientRectangle.Width / 2 - _radius / 2, this.ClientRectangle.Height / 2 - _radius / 2, _radius, _radius);
Now I want to check if the user clicked in the form.
if (e.Button == MouseButtons.Left)
{
int w = this.ClientRectangle.Width;
int h = this.ClientRectangle.Height;
double distance = Math.Sqrt((w/2 - e.Location.X) ^ 2 + (h/2 - e.Location.Y) ^ 2);
....
if (distance <_radius)
return true;
else
return false;
}
Now I am ending up with wrong values. For instance if I click on the edge of the circle I at times get distance of ~10 or NaN at times. What am I doing wrong here?
You're performing integer division, which is coarser than floating-point division.
^ is not the "power-to" operator, it's the bitwise XOR operator, which is probably not what you want. Use Math.Pow or x*x instead.
You can simplify the last statement by simply doing return distance < _radius.
Try this:
Single w = this.ClientRectangle.Width;
Single h = this.ClientRectangle.Height;
Single distanceX = w / 2f - e.Location.X;
Single distanceY = h / 2f - e.Location.Y;
Single distance = Math.Sqrt( distanceX * distanceX + distanceY * distanceY );
return distance < this._radius;
(This code does not change any assumptions about the location of the circle).
Related
The title for this post was quite hard to think of, so if you can think of a more descriptive title please tell me. Anyway, my problem is quite specific and requires some simple maths knowledge. I am writing a C# WinForms application which is a bit like the old 'xeyes' Linux application. It basically is a set of eyes which follow around your mouse cursor. This may sound easy at first, however can get rather complicated if you're a perfectionist like me :P. This is my code so far (only the paint method, that is called on an interval of 16).
int lx = 35;
int ly = 50;
int rx;
int ry;
int wx = Location.X + Width / 2;
int wy = Location.Y + Height / 2;
Rectangle bounds = Screen.FromControl(this).Bounds;
// Calculate X
float tempX = (mx - wx) / (float)(bounds.Width / 2);
// Calculate Y
float tempY = (my - wy) / (float)(bounds.Height / 2);
// Draw eyes
e.Graphics.FillEllipse(Brushes.LightGray, 10, 10, 70, 100);
e.Graphics.FillEllipse(Brushes.LightGray, 90, 10, 70, 100);
// Draw pupils (this only draws the left one)
e.Graphics.FillEllipse(Brushes.Black, lx += (int)(25 * tempX), ly += (int)(40 * tempY), 20, 20);
Now this does work at a basic level, however sometimes this can happen if the user puts the cursor at 0,0.
Now my question is how to fix this? What would the IF statement be to check where the mouse pointer is, and then reduce the pupil X depending on that?
Thanks.
Edit: This is where I get the mouse positions (my and mx):
private void timer_Tick(object sender, EventArgs e)
{
mx = Cursor.Position.X;
my = Cursor.Position.Y;
Invalidate();
}
The timer is started in the eyes_Load event and the interval is 16.
Edit 2: Final solution: http://pastebin.com/fT5HfiQR
Modelling the eyeball as the following ellipse:
Its equation is:
And that of the line joining its center and the cursor:
(don't worry about the singularity)
We can then solve to get the intersection point:
Where
Now you can calculate the distance to the eyeball's edge, by dividing the distance from the center to the cursor by sigma. What remains is just interpolating to cap the position of the pupil:
The if statement you want is then
(N.B. for math-mo's out there the above was a slight simplification, which assumes your ellipse is not too narrow; the exact solution is non-analytical)
EDIT: my tests in VB.NET:
EDIT 2: C# port
PointF Bound(double xc, double yc, double w, double h, double xm, double ym, double r)
{
double dx = xm - xc, dy = ym - yc;
if (Math.Abs(dx) > 0.001 && Math.Abs(dy) > 0.001)
{
double dx2 = dx * dx, dy2 = dy * dy;
double sig = 1.0 / Math.Sqrt(dx2 / (w * w * 0.25) + dy2 / (h * h * 0.25));
double d = Math.Sqrt(dx2 + dy2), e = d * sig;
if (d > e - r)
{
double ratio = (e - r) / d;
return new PointF((float)(xc + dx * ratio),
(float)(yc + dy * ratio));
}
}
return new PointF((float)xm, (float)ym);
}
xc, yc: Center coordinates of the ellipse
w, h: Width and height of the ellipse
xm, ym: Mouse coordinates
r: Radius of the circle you wanna constrain (the pupil)
Returns: The point where you wanna place the center of the circle
EDIT 3: Many thanks to Quinchilion for the following optimization (gawd damn this smacked me hard in the face)
PointF Bound(double xc, double yc, double w, double h, double xm, double ym, double r)
{
double x = (xm - xc) / (w - r);
double y = (ym - yc) / (h - r);
double dot = x*x + y*y;
if (dot > 1) {
double mag = 1.0 / Math.Sqrt(dot);
x *= mag; y *= mag;
}
return new PointF((float)(x * (w - r) + xc), (float)(y * (h - r) + yc));
}
Currently my software uses the HitTest() method of a chart object in MSCharts but as I scale this up to more and more data points on my chart combined with other factors this can have a massive performance hit.
I was wondering if there any alternatives that you know of to provide the same functionality ( get the X Coordinate on the chart for the cursor position ) but without the performance hit as hit testing seems to be a very brute force way of obtaining my answer.
My chart is created from the class System.Windows.Forms.DataVisualization.Charting.Chart
Edit for clarity: I need to find the position of a line on my chart to use it for other calculations.
Had the same performance issue with a mousewheel event.
Here is my solution:
To get the axes values of the current mouse position:
double posX = Math.Round(currentArea.AxisX.PixelPositionToValue(e.X));
double posY = Math.Round(currentArea.AxisY.PixelPositionToValue(e.Y));
Taken from Showing Mouse Axis Coordinates on Chart Control with a little change to get it more accurate.
But you should check before, that the mouse is in a ChartArea, else it will throw you an Exception.
To get the ChatElement on which the mouse points:
// Gets the ChartArea that the mouse points
private ChartArea mouseinChartArea(Chart source, Point e)
{
double relativeX = (double)e.X * 100 / source.Width;
double relativeY = (double)e.Y * 100 / source.Height;
foreach (ChartArea ca in source.ChartAreas)
{
if (relativeX > ca.Position.X && relativeX < ca.Position.Right &&
relativeY > ca.Position.Y && relativeY < ca.Position.Bottom)
return ca;
}
return null;
}
// for my purpose, returns an axis. But you can return anything
private Axis findAxisforZooming(Chart source, Point e)
{
ChartArea currentArea = mouseinChartArea(source, new Point(e.X, e.Y)); // Check if inside
if (currentArea == null)
return null;
double axisXfontSize = currentArea.AxisX.LabelAutoFitMinFontSize + ((double)source.Width / SystemInformation.PrimaryMonitorSize.Width)
* (currentArea.AxisX.LabelAutoFitMaxFontSize - currentArea.AxisX.LabelAutoFitMinFontSize);
double axisYfontSize = currentArea.AxisY.LabelAutoFitMinFontSize + ((double)source.Height / SystemInformation.PrimaryMonitorSize.Height)
* (currentArea.AxisY.LabelAutoFitMaxFontSize - currentArea.AxisY.LabelAutoFitMinFontSize);
double axisYfontHeightSize = (axisYfontSize - currentArea.AxisY.LabelStyle.Font.Size) + currentArea.AxisY.LabelStyle.Font.Height;
Graphics g = this.CreateGraphics();
if (currentArea.AxisX.LabelStyle.Font.Unit == GraphicsUnit.Point)
axisXfontSize = axisXfontSize * g.DpiX / 72;
if (currentArea.AxisY.LabelStyle.Font.Unit == GraphicsUnit.Point)
axisYfontHeightSize = axisYfontHeightSize * g.DpiX / 72;
g.Dispose();
// Replacing the SystemInformation.PrimaryMonitorSize with the source.Width / Height will give the accurate TickMarks size.
// But it doens't count for the gab between the tickMarks and the axis lables (so by replacing, it give a good proximity with the gab)
int axisYTickMarks = (int)Math.Round(currentArea.AxisY.MajorTickMark.Size / 100 * SystemInformation.PrimaryMonitorSize.Width); // source.Width;
int axisXTickMarks = (int)Math.Round(currentArea.AxisX.MajorTickMark.Size / 100 * SystemInformation.PrimaryMonitorSize.Height); // source.Height;
int leftInnerPlot = (int)Math.Round(currentArea.Position.X / 100 * source.Width +
currentArea.InnerPlotPosition.X / 100 * currentArea.Position.Width / 100 * source.Width);
int rightInnerPlot = (int)Math.Round(currentArea.Position.X / 100 * this.chart1.Width +
currentArea.InnerPlotPosition.Right / 100 * currentArea.Position.Width / 100 * source.Width);
int topInnerPlot = (int)Math.Round(currentArea.Position.Y / 100 * this.chart1.Height +
currentArea.InnerPlotPosition.Y / 100 * currentArea.Position.Height / 100 * source.Height);
int bottomInnerPlot = (int)Math.Round(currentArea.Position.Y / 100 * source.Height +
currentArea.InnerPlotPosition.Bottom / 100 * currentArea.Position.Height / 100 * source.Height);
// Now you got the boundaries of every important ChartElement.
// Only left to check if the mouse is within your desire ChartElement,
// like the following:
bottomInnerPlot += axisXTickMarks + (int)Math.Round(axisXfontSize); // Include AxisX
if (e.X > leftInnerPlot && e.X < rightInnerPlot &&
e.Y > topInnerPlot && e.Y < bottomInnerPlot) // return AxisX if inside the InnerPlot area or on AxisX
return currentArea.AxisX;
else if (e.X > (leftInnerPlot - axisYTickMarks - (int)Math.Round(axisYfontHeightSize)) && e.X < rightInnerPlot &&
e.Y > topInnerPlot && e.Y < bottomInnerPlot) // return AxisY if on AxisY only
return currentArea.AxisY;
return null;
}
As it can be seen, the code is longer than HitTest(). But the run time is shorter.
I'm looking for a bit of math help. I have a game were a 2D heightmap is generated and then stretched over a sphere using a length/direction formula. Now I need to know how to calculate the height between 2 points on my heightmap.
What I know:
The array that holds the heightmap
The angle in radians to my object
how many points there are on the heightmap
My problem look somewhat like so:
image
more images
The red and blue lines are the 2 heightmap points, and the light blue is where I'd like to calculate the height at.
Here's my current code to do it, but it doesn't work to well.
public double getheight(double angle)
{
//find out angle between 2 heightmap point
double offset = MathHelper.TwoPi / (heightmap.Length - 1);
//total brainfart attempt
double lowerAngle = offset * angle;
double upperAngle = offset * angle + offset;
//find heights
double height1 = heightmap[(int)lowerAngle];
double height2 = heightmap[(int)upperAngle];
//find offset angle
double u = angle - lowerAngle / (upperAngle - lowerAngle);
//return the height
return height1 + (height1 - height2) * u;
}
from my vegetation code, this seems to work okay, but is to rough to use for units and such, as they jump up/down as they move, due to it using only 1 heightmap point.
double[] hMap = planet.getHeightMap();
double i = hMap.Length / (Math.PI * 2);
this.height = hMap[(int)(angle * i)];
EDIT: example at end based on additional question info
Sounds to me like a linear interpolation - if you look at it from a 2d point of view, you've got two points:
(x1, y1) = point one on heightmap
(x2, y2) = point two on heightmap
and one point somewhere between (x1,x2) at an unknown height:
pu = (xu, yu)
A generic formula for LERP is:
pu = p0 + (p1 - p0) * u
where:
p0 = first value
p1 = second value
u = % where your unknown point lies between (p0,p1)
Here, we'll say p0 == y2 and p1 == y1. Now we need to determine "how far" the unknown point is between x1 and x2 - if you know the angles to the two heightmap points, this is easy:
u = ang(xu) - ang(x1) / (ang(x2) - ang(x1))
Alternatively, you could project your angle out to Max(y1,y2) and get the "unknown x pos" that way, then calculate the above.
So, let's try a contrived example:
p1 = point one in map = (1,2) therefore ang(p1) ~ 57 degrees
p2 = point two in map = (2,4) therefore ang(p2) ~ 114 degrees
note that here, the "x axis" is along the surface of the sphere, and the "y-axis" is the distance away from the center.
pu = object location = py #angle 100 degrees ~ 1.74 radians
px = (1.74 rad - 1 rad ) / (2 rad - 1 rad) = 0.74 / 1.0 = 0.74 => 74%
py = y0 + (y1 - y0) * u
= 2 + (4 - 2) * 0.74
= 2.96
Hopefully I didn't drop or misplace a sign there somewhere... :)
Ok, your example code - I've tweaked it a bit, here's what I've come up with:
First, let's define some helpers of my own:
public static class MathHelper
{
public const double TwoPi = Math.PI * 2.0;
public static double DegToRad(double deg)
{
return (TwoPi / 360.0) * deg;
}
public static double RadToDeg(double rad)
{
return (360.0 / TwoPi) * rad;
}
// given an upper/lower bounds, "clamp" the value into that
// range, wrapping over to lower if higher than upper, and
// vice versa
public static int WrapClamp(int value, int lower, int upper)
{
return value > upper ? value - upper - 1
: value < lower ? upper - value - 1
: value;
}
}
Our Test setup:
void Main()
{
var random = new Random();
// "sea level"
var baseDiameter = 10;
// very chaotic heightmap
heightmap = Enumerable
.Range(0, 360)
.Select(_ => random.NextDouble() * baseDiameter)
.ToArray();
// let's walk by half degrees, since that's roughly how many points we have
for(double i=0;i<360;i+=0.5)
{
var angleInDegrees = i;
var angleInRads = MathHelper.DegToRad(i);
Console.WriteLine("Height at angle {0}°({1} rad):{2} (using getheight:{3})",
angleInDegrees,
angleInRads,
heightmap[(int)angleInDegrees],
getheight(angleInRads));
}
}
double[] heightmap;
And our "getheight" method:
// assume: input angle is in radians
public double getheight(double angle)
{
//find out angle between 2 heightmap point
double dTheta = MathHelper.TwoPi / (heightmap.Length);
// our "offset" will be how many dThetas we are
double offset = angle / dTheta;
// Figure out two reference points in heightmap
// THESE MAY BE THE SAME POINT, if angle ends up
// landing on a heightmap index!
int lowerAngle = (int)offset;
int upperAngle = (int)Math.Round(
offset,
0,
MidpointRounding.AwayFromZero);
// find closest heightmap points to angle, wrapping
// around if we go under 0 or over max
int closestPointIndex = MathHelper.WrapClamp(
lowerAngle,
0,
heightmap.Length-1);
int nextPointIndex = MathHelper.WrapClamp(
upperAngle,
0,
heightmap.Length-1);
//find heights
double height1 = heightmap[closestPointIndex];
double height2 = heightmap[nextPointIndex];
// percent is (distance from angle to closest angle) / (angle "step" per heightmap point)
double percent = (angle - (closestPointIndex * dTheta)) / dTheta;
// find lerp height = firstvalue + (diff between values) * percent
double lerp = Math.Abs(height1 + (height2 - height1) * percent);
// Show what we're doing
Console.WriteLine("Delta ang:{0:f3}, Offset={1:f3} => compare indices:[{2}, {3}]",
dTheta,
offset,
closestPointIndex,
nextPointIndex);
Console.WriteLine("Lerping {0:p} between heights {1:f4} and {2:f4} - lerped height:{3:f4}",
percent,
height1,
height2,
lerp);
return lerp;
}
I want to know how to get an angle of a line A-B from horizontal axis X. Other questions in SO do that only between two lines. I'm aware I can always draw second line A-C and calculate but I'm wondering if there's a faster method.
EDIT: I'm very sure I'm not doing a premature optimization.
You can use atan for that.
angle = atan((By-Ay)/(Bx-Ax))
private double Angulo(int x1, int y1, int x2, int y2)
{
double degrees;
// Avoid divide by zero run values.
if (x2 - x1 == 0)
{
if (y2 > y1)
degrees = 90;
else
degrees = 270;
}
else
{
// Calculate angle from offset.
double riseoverrun = (double)(y2 - y1) / (double)(x2 - x1);
double radians = Math.Atan(riseoverrun);
degrees = radians * ((double)180 / Math.PI);
// Handle quadrant specific transformations.
if ((x2 - x1) < 0 || (y2 - y1) < 0)
degrees += 180;
if ((x2 - x1) > 0 && (y2 - y1) < 0)
degrees -= 180;
if (degrees < 0)
degrees += 360;
}
return degrees;
}
If you need all four quadrants, Atan2 is more suitable than Atan.
public static int GetAngleBetweenPoints(PointF pt1, PointF pt2)
{
float dx = pt2.X - pt1.X;
float dy = pt2.Y - pt1.Y;
int deg = Convert.ToInt32(Math.Atan2(dy, dx) * (180 / Math.PI));
if (deg < 0) { deg += 360; }
return deg;
}
If
The angle is small,
you can live with small inaccuracies, and
You can use the angle in radians and not degrees,
then there is a fast solution: Under these conditions, you can assume that tan(a) = a = atan(a), and hence just omit the atan() call.
You could also use arccosine, if your line is in the form [r_x,r_y], where r_x is the change in x and r_y is the change in y.
angle = arccos( r_x/( r_x*r_x + r_y*r_y ) )
It's slightly more opaque, but it's basically the dot product law:
angle = arccos (r . v)
Where r and v are both unit vectors (vectors of length 1). In our case, v is the vector [1,0], and r is
[r_x,r_y] / (r_x^2+r_y^2)
in order to make it a unit vector.
The x-axis is actually a line with equation
y = 0
so you could use the solution you have already.
How can I tell if a point belongs to a certain line?
Examples are appreciated, if possible.
In the simplest form, just plug the coordinates into the line equation and check for equality.
Given:
Point p (X=4, Y=5)
Line l (Slope=1, YIntersect=1)
Plug in X and Y:
Y = Slope * X + YIntersect
=> 5 = 1 * 4 + 1
=> 5 = 5
So yes, the point is on the line.
If your lines are represented in (X1,Y1),(X2,Y2) form, then you can calculate slope with:
Slope = (y1 - y2) / (x1-x2)
And then get the Y-Intersect with this:
YIntersect = - Slope * X1 + Y1;
Edit: I fixed the Y-Intersect (which has been X1 / Y1 ...)
You'll have to check that x1 - x2 is not 0. If it is, then checking if the point is on the line is a simple matter of checking if the Y value in your point is equal to either x1 or x2. Also, check that the X of the point is not 'x1' or 'x2'.
I just wrote an function which handles a few extra requirements since I use this check in a drawing application:
Fuzziness - There must be some room for error since the function is used to select lines by clicking on them.
The line got an EndPoint and a StartPoint, no infinite lines.
Must handle straight vertical and horizontal lines, (x2 - x1) == 0 causes division by zero in the other answers.
private const double SELECTION_FUZZINESS = 3;
internal override bool ContainsPoint(Point point)
{
LineGeometry lineGeo = geometry as LineGeometry;
Point leftPoint;
Point rightPoint;
// Normalize start/end to left right to make the offset calc simpler.
if (lineGeo.StartPoint.X <= lineGeo.EndPoint.X)
{
leftPoint = lineGeo.StartPoint;
rightPoint = lineGeo.EndPoint;
}
else
{
leftPoint = lineGeo.EndPoint;
rightPoint = lineGeo.StartPoint;
}
// If point is out of bounds, no need to do further checks.
if (point.X + SELECTION_FUZZINESS < leftPoint.X || rightPoint.X < point.X - SELECTION_FUZZINESS)
return false;
else if (point.Y + SELECTION_FUZZINESS < Math.Min(leftPoint.Y, rightPoint.Y) || Math.Max(leftPoint.Y, rightPoint.Y) < point.Y - SELECTION_FUZZINESS)
return false;
double deltaX = rightPoint.X - leftPoint.X;
double deltaY = rightPoint.Y - leftPoint.Y;
// If the line is straight, the earlier boundary check is enough to determine that the point is on the line.
// Also prevents division by zero exceptions.
if (deltaX == 0 || deltaY == 0)
return true;
double slope = deltaY / deltaX;
double offset = leftPoint.Y - leftPoint.X * slope;
double calculatedY = point.X * slope + offset;
// Check calculated Y matches the points Y coord with some easing.
bool lineContains = point.Y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= point.Y + SELECTION_FUZZINESS;
return lineContains;
}
The best way to determine if a point R = (rx, ry) lies on the line connecting points P = (px, py) and Q = (qx, qy) is to check whether the determinant of the matrix
{{qx - px, qy - py}, {rx - px, ry - py}},
namely (qx - px) * (ry - py) - (qy - py) * (rx - px) is close to 0. This solution has several related advantages over the others posted: first, it requires no special case for vertical lines, second, it doesn't divide (usually a slow operation), third, it doesn't trigger bad floating-point behavior when the line is almost, but not quite vertical.
Given two points on the line L0 and L1 and the point to test P.
(L1 - L0) * (P - L0)
n = (P - L0) - --------------------- (L1 - L0)
(L1 - L0) * (L1 - L0)
The norm of the vector n is the distance of the point P from the line through L0 and L1. If this distance is zero or small enough (in the case of rounding errors), the point lies on the line.
The symbol * represents the dot product.
Example
P = (5, 5)
L0 = (0, 10)
L1 = (20, -10)
L1 - L0 = (20, -20)
P - L0 = (5, -5)
(20, -20) * (5, -5)
n = (5, -5) - --------------------- (20, -20)
(20, -20) * (20, -20)
200
= (5, -5) - --- (20, -20)
800
= (5, -5) - (5, -5)
= (0, 0)
I think Mr.Patrick McDonald put the nearly correct answer and this is the correction of his answer:
public bool IsOnLine(Point endPoint1, Point endPoint2, Point checkPoint)
{
return (((double)checkPoint.Y - endPoint1.Y)) / ((double)(checkPoint.X - endPoint1.X))
== ((double)(endPoint2.Y - endPoint1.Y)) / ((double)(endPoint2.X - endPoint1.X));
}
and of course there are many other correct answers especially Mr.Josh but i found this is the best one.
Thankx for evryone.
y = m * x + c
This is the equation of a line. x & y are the co-ordinates. Each line is characterized by its slope (m ) and where it intersects the y-axis (c).
So given m & c for a line, you can determine if the point (x1, y1) is on the line by checking if the equation holds for x = x1 and y = y1
A 2D line is generally represented using an equation in two variables x and y here is a well known equation
Now imagine your GDI+ line is drawn from (0,0) to (100, 100) then the value of m=(0-100)/(0-100) = 1 thus the equation for your line is y-0=1*(x-0) => y=x
Now that we have an equation for the line in question its easy to test if a point belongs to this line. A given point (x3, y3) belongs to this line if it satisfies the line equation when you substitute x=x3 and y=y3. For example the point (10, 10) belongs to this line since 10=10 but (10,12) does not belong to this line since 12 != 10.
NOTE: For a vertical line the value of the slope (m) is infinite but for this special case you may use the equation for a vertical line directly x=c where c = x1 = x2.
Though I have to say I am not sure if this is the most efficient way of doing this. I will try and find a more efficient way when I have some more time on hand.
Hope this helps.
If you have a line defined by its endpoints
PointF pt1, pt2;
and you have a point that you want to check
PointF checkPoint;
then you could define a function as follows:
bool IsOnLine(PointF endPoint1, PointF endPoint2, PointF checkPoint)
{
return (checkPoint.Y - endPoint1.Y) / (endPoint2.Y - endPoint1.Y)
== (checkPoint.X - endPoint1.X) / (endPoint2.X - endPoint1.X);
}
and call it as follows:
if (IsOnLine(pt1, pt2, checkPoint) {
// Is on line
}
You will need to check for division by zero though.
Equation of the line is:
y = mx + c
So a point(a,b) is on this line if it satisfies this equation i.e. b = ma + c
As an alternative to the slope/y-intercept method, I chose this approach using Math.Atan2:
// as an extension method
public static bool Intersects(this Vector2 v, LineSegment s) {
// check from line segment start perspective
var reference = Math.Atan2(s.Start.Y - s.End.Y, s.Start.X - s.End.X);
var aTanTest = Math.Atan2(s.Start.Y - v.Y, s.Start.X - v.X);
// check from line segment end perspective
if (reference == aTanTest) {
reference = Math.Atan2(s.End.Y - s.Start.Y, s.End.X - s.Start.X);
aTanTest = Math.Atan2(s.End.Y - v.Y, s.End.X - v.X);
}
return reference == aTanTest;
}
The first check reference determines the arcTan from the start point of the line segment to it's end-point.
Then from the start point perspective, we determine the arcTan to the vector v.
If those values are equal, we check from the perspective of the end-point.
Simple and handles horizontal, vertical and all else in between.