Drawing triangles given user input - c#

So I'm trying to make a Program that will draw a triangle given some user input. The variables that the user provides are angleA, angleB, andleC, and the corresponding sides. The code I have set up to find the three points of the angle is as follows.
double angle_A = double.Parse(angleA.Text);
double angle_B = double.Parse(angleB.Text);
double angle_C = double.Parse(angleC.Text);
double side_A = double.Parse(sideA.Text);
double side_B = double.Parse(sideB.Text);
double side_C = double.Parse(sideC.Text);
double triangleHeight = Area * 2 / (double.Parse(sideB.Text));
double height = canvas.Height;
double width = canvas.Width;
int aX, aY, bX, bY, cX, cY;
aY = Convert.ToInt32(canvas.Height - triangleHeight / 2);
if (angle_A <= 90 && angle_C <= 90)
{
aX = Convert.ToInt32((width - side_B) / 2);
}
else if (angle_A > 90)
{
double extraLength = Math.Sqrt(Math.Pow(side_C, 2) - Math.Pow(triangleHeight, 2));
aX = Convert.ToInt32(width - ((width - (side_B + extraLength)) / 2) + side_B);
}
else if (angle_C > 90)
{
double extraLength = Math.Sqrt(Math.Pow(side_A, 2) - Math.Pow(triangleHeight, 2));
aX = Convert.ToInt32((width - side_B + extraLength) / 2);
}
else
{
aX = 0;
MessageBox.Show("ERROR: No such triangle exists", "ERROR:");
}
cX = aX + Convert.ToInt32(side_B);
cY = aY;
bX = Convert.ToInt32(side_A * Math.Cos(Math.PI * angle_C / 180) + cX);
bY = Convert.ToInt32(side_A * Math.Sin(Math.PI * angle_C / 180) - cY);
Point pointA = new Point(aX, aY);
Point pointB = new Point(bX, bY);
Point pointC = new Point(cX, cY);
Point[] points = new Point[3] { pointA, pointB, pointC };
return points;
This returns the three points that the paint method should use to draw the triangle. However, when I insert the values, the triangle it draws looks nothing like the triangle I have described with the user input. Any thoughts on why this is? Thanks in advance.
P.S. The error is not in my code, as it gives me no errors and does not crash. It is strictly a math error that I have not been able to locate.

I imagine the triangle ABC with corners A and C along the base line with A to the left and C to the right, and B somewhere above them. Side A is the side opposite corner A, and so on.
As Damien_the_Unbeliever says, you should only allow input of, say, side B, side C and angle of corner A. Validate that A is not over 180 degrees. Start off with A at the origin, so we know straight away that xA = 0, yA = 0, xC = length of side B, yC=0, xB = side C * cos A, and yB = side C * sin A. I believe this works even if A is over 90 degrees, you do get a negative value for xB but don't worry, continue anyway!
Now all you have to do is centre the triangle on the canvas. I don't understand where you are getting Area from. It makes no sense to calculate the triangle's height from its area. The triangle height is yB, you can calculate the offset you need to centre it vertically as you know, so long as yB <= height. Add the same y offset to all the points.
The horizontal offset is a bit more complicated! If xB is negative, I would add an offset to all the x values to bring xB to 0, this positions your triangle at the left side of the canvas, and its width is given by the new xC. If xB is non-negative, the width is the maximum of xC or xB. Then you can calculate the x offset from the width as you know.
I have had time to do some of the code, for example values; this will draw a triangle but not yet centre it:
int sideB = 100;
int sideC = 143;
int angleA = 28;
double angleARadians = Math.PI * angleA / 180.0;
int[] xs = new int[3];
int[] ys = new int[3];
//1st corner is at the origin
xs[0] = 0; ys[0] = 0;
//Then the third corner is along the x axis from there to the length of side B
xs[2] = sideB; ys[2] = 0;
// The second corner is up a bit above the x axis. x could be negative.
// Note, when you draw it, the y axis extends downwards, so a positive y value will be drawn below the x axis.
xs[1] = (int)Math.Round(sideC * Math.Cos(angleARadians));
ys[1] = (int)Math.Round(sideC * Math.Sin(angleARadians));
//If Bx is negative, move all the points over until it's 0
if (xs[1] < 0)
{
int zeroX = xs[1] * -1;
for (int i = 0; i < 3; i++)
{
xs[i] += zeroX;
}
}
// Now centre the triangle on the canvas.
// Firstly find the width of the triangle. Point B could be to the left of A, or between A and C, or to the right of C.
// So the left most point of the triangle is the minimum of A or B, and the right most point is the maximum of B or C.
int minX = Math.Min(xs[0],xs[1]);
int maxX = Math.Max(xs[2], xs[1]);
//The height of the triangle is yB.
int offsetX = (panCanvas.Width - (maxX - minX)) / 2;
int offsetY = (panCanvas.Height - ys[1]) / 2;
//offset all the points by the same amount, to centre the triangle.
for (int i = 0; i < 3; i++)
{
xs[i] += offsetX;
ys[i] += offsetY;
}

Given the three sides of a triangle a, b, and c the coordinates of the vertices are
P=[0,0]
Q=[a,0]
R=[(a^2+c^2-b^2)/(2*a), sqrt(c^2*(2*(a^2+b^2)-c^2)-(a+b)^2*(a-b)^2)/(4*a^2))]
Example, a=6, b=4 and c=8
P=[0,0]
Q=[6,0]
R=[7,√15]

Related

Find an index for a given Point coordinate from an array of Points

Given an Point array and an arbitrary x,y coordinate, find the index for _points that is closest to the given coordinate.
PointD[] _points
//create a list of x,y coordinates:
for (int i = 0; i < _numberOfArcSegments + 1; i++)
{
double x1 = _orbitEllipseSemiMaj * Math.Sin(angle) - _focalDistance; //we add the focal distance so the focal point is "center"
double y1 = _orbitEllipseSemiMinor * Math.Cos(angle);
//rotates the points to allow for the LongditudeOfPeriapsis.
double x2 = (x1 * Math.Cos(_orbitAngleRadians)) - (y1 * Math.Sin(_orbitAngleRadians));
double y2 = (x1 * Math.Sin(_orbitAngleRadians)) + (y1 * Math.Cos(_orbitAngleRadians));
angle += _segmentArcSweepRadians;
_points[i] = new PointD() { x = x2, y = y2 };
}
I'm drawing an ellipse which represents an orbit. I'm first creating the point array above, then when I draw it, I (attempt) to find the point closest to where the orbiting body is.
To do this I've been attempting to calculate the angle from the center of the ellipse to the body:
public void Update()
{
//adjust so moons get the right positions (body position - focal point position)
Vector4 pos = _bodyPositionDB.AbsolutePosition - _positionDB.AbsolutePosition;
//adjust for focal point
pos.X += _focalDistance;
//rotate to the LonditudeOfPeriapsis.
double x2 = (pos.X * Math.Cos(-_orbitAngleRadians)) - (pos.Y * Math.Sin(-_orbitAngleRadians));
double y2 = (pos.X * Math.Sin(-_orbitAngleRadians)) + (pos.Y * Math.Cos(-_orbitAngleRadians));
_ellipseStartArcAngleRadians = (float)(Math.Atan2(y2, x2)); //Atan2 returns a value between -180 and 180;
}
then:
double unAdjustedIndex = (_ellipseStartArcAngleRadians / _segmentArcSweepRadians);
while (unAdjustedIndex < 0)
{
unAdjustedIndex += (2 * Math.PI);
}
int index = (int)unAdjustedIndex;
The ellipse draws fine, (the point array is correct and all is good once adjusted for viewscreen and camera offsets and zoom)
But does not start at the correct point (I'm decreasing the alpha in the color so the resulting ellipse fades away the further it gets from the body)
I've spend days trying to figure out what I'm doing wrong here and tried a dozen different things trying to figure out where my math is wrong, but I'm not seeing it.
I assume that _points should be an array of PointD;
This is the shortest way to get the closest point to your array (calcdistance should be a simple function that calculate the euclidean distance):
PointD p = _points.OrderBy(p => CalcDistance(p, gievnPoint)).First();

C# - generating points along a fraction of a circles circumference

I have the below algorithm which generates a number of points along the circumference of a circle for collision events in my program. (This works perfectly as far as I can tell).
bool Collision_True = false;
for (int Angle = 0; Angle <= 359; Angle += 5)
{
int X = (CentreX + (Radius * Math.Cos(Angle));
int Y = (CentreY + (Radius * Math.Sin(Angle));
Point point = new Point(X, Y);
if (Collision_True == false)
{
Collision_True = Player_Collisions(point);
}
}
return Collision_True;
However I want to change this so it only generates points on the bottom third of the circle, I tried changing the values in the for loop as follows:
for (int Angle = 120; Angle <= 240; Angle += 5)
{
...
}
But the points generated are still around the complete circumference of the circle instead of just the bottom third.
Any ideas? Thanks.
You need to convert to radians
for (int angleDegrees = 120; angleDegrees <= 240; angleDegrees += 5)
{
double angleRadians = angleDegrees / 180 * Math.PI;
int X = (CentreX + (Radius * Math.Cos(angleRadians));
int Y = (CentreY + (Radius * Math.Sin(angleRadians));
...

Drawing the X and y axis for a curved Line in C# Form

i i am relative new to c# and is trying to draw a curved line in c#. I would like to ask that is there any possible way to create an X and Y axis in order to show the coordinates of each point of the curved line.
Please do help me on this matter as i am stuck on how to execute it.
protected override void OnPaint(PaintEventArgs e)
{
float a = 1, b = 5, c = 1;
double x1, x2, x3,x4,x5,x6, y1, y2, y3,y4,y5, delta;
delta = (b * b) - (4 * a * c);
x1=0;
y1 = a * (x1 * x1) + (b * (x1)) + c;
x2 = 3;
y2 = a * (x2 * x2) + (b * (x2)) + c;
x3 = - 3;
y3 = a * (x3 * x3) + (b * (x3)) + c;
x4 = 5;
y4 = a * (x4 * x4) + (b * (x4)) + c;
x5 = -10;
y5 = a * (x5 * x5) + (b * (x5)) + c;
int cx1 = Convert.ToInt32(x1);
int cx2 = Convert.ToInt32(x2);
int cx3 = Convert.ToInt32(x3);
int cy1 = Convert.ToInt32(y1);
int cy2 = Convert.ToInt32(y2);
int cy3 = Convert.ToInt32(y3);
int cx4 = Convert.ToInt32(x4);
int cy4 = Convert.ToInt32(y4);
int cx5 = Convert.ToInt32(x5);
int cy5 = Convert.ToInt32(y5);
Graphics g = e.Graphics;
int deltaX = 100;
int deltaY = 100;
g.TranslateTransform(deltaX, deltaY);
float factor = 2.5f;
Matrix m = new Matrix();
m.Scale(factor, factor);
g.MultiplyTransform(m);
Pen aPen = new Pen(Color.Blue, 1);
Point point1 = new Point(cx1, cy1);
Point point2 = new Point(cx2, cy2);
Point point3 = new Point(cx3, cy3);
Point point4 = new Point(cx4, cy4);
Point point5 = new Point(cx5, cy5);
Point[] Points = { point5, point3, point1,point2,point4 };
g.DrawCurve(aPen, Points);
Maybe I misunderstand you, but it sounds like you want to make your GDI+ graphics scale with the window size (i.e. you want to scale the X and Y axis with the size of the window), right?
This is pretty simple, you just have to decide how big of a space you want to present in the window -- i.e. if you want to make the axis go from 0,0 on the top left, to 512x512 on the bottom right, then you would just need to scale the X axis by a factor of 512/width, and the Y axis by a factor of 512/height.
So you would do that by performing a ScaleTransform on your Graphics object. You'll need to use your Form's ClientSize to get the width and height. (The regular Form's .Width, and .Height properties, include all the borders and title bars, padding pixels, etc. -- so it's no good for this calculation.)
Then you will need to force an Invalidation during the form's Resize event (it will work without this, when you make the window smaller, but when you make it bigger, this will be required, or else it will only redraw the edges).
Another thing worth considering is turning on the form's DoubleBuffered property, the redraw will be much smoother.
So, let's assume you want to work in a virtual space of 512x512 "pixels" where 0 ,0 is always the top left, and 512,512 is the bottom right. You could add this code to the top of your OnPaint event handler:
float scaleX = 512f / ((float)this.ClientSize.Width);
float scaleY = 512f / ((float)this.ClientSize.Height);
e.Graphics.ScaleTransform(scaleX, scaleY);
Then add a handler for the Form's Resize event and add something like this:
this.Invalidate(true);
That should do the trick.

Iterate through N points that are perpendicular to another line

I have 1 line with 2 known points:
PointF p2_1 = new PointF();
p2_1.X = 100; // x1
p2_1.Y = 150; // y1
PointF p2_2 = new PointF();
p2_2.X = 800; // x2
p2_2.Y = 500; // y2
float dx = p2_2.X - p2_1.X;
float dy = p2_2.Y- p2_1.Y;
float slope = dy / dx; // slope m
float intercept = p2_1.Y - slope * p2_1.X; // intercept c
// y = mx + c
I'd like to iterate through 10 pixels to the left (or right) to 1 line (at x1, y1).
The red dots are the ones that I'd like process. Example:
for (int i = 10; i > 0; i--)
{
// start with distant coordinates
PointF new_point = new Point(); // (grab x,y, coords accordingly)
// repeat until I'm at (x1, y1)
}
How do I iterate through these coords?
A perpendicular vector will be of the form:
[-dy dx] where [dx dy] is your current vector. Once you have the perpendicular vector, you can normalize it (unit length), then iterate by a set amount:
float perp_dx = -dy / Math.sqrt(dy*dy+dx*dx); //normalized
float perp_dy = dx /Math.sqrt(dy*dy+dx*dx); //normalized
for(int i =0; /*logic here*/){
float new_x = perp_dx * i + start_x;
float new_y = perp_dy * i + start_y;
}
The line perpendicular to a given line has slope equal to the negative inverse of the slope of the given line.
The slope of the given line is (y2-y1) / (x2-x1)
So the red line has slope = - 1 / [(y2-y1) / (x2-x1)]
So each ith point on this line has coordinates (xi, yi) where
(yi - y1) / (xi - x1) = - 1 / (y2-y1) / x2-x1)
and is a multiple of one pixel fixed distance away from (x1, y1), i.e., where
(yi-y1) * (yi-y1) + (xi-x1) * (xi-x1) = i * i
what I would do is calculate what this increment vector (dx, dy) is for or between each point on the red line, and then just keep adding that increment in a loop that iterates 10 times.

Shorten a line by a number of pixels

I'm drawing a custom diagram of business objects using .NET GDI+. Among other things, the diagram consists of several lines that are connecting the objects.
In a particular scenario, I need to shorten a line by a specific number of pixels, let's say 10 pixels, i.e. find the point on the line that lies 10 pixels before the end point of the line.
Imagine a circle with radius r = 10 pixels, and a line with start point (x1, y1) and end point (x2, y2). The circle is centered at the end point of the line, as in the following illustration.
How do I calculate the point marked with a red circle, i.e. the intersection between circle and line? This would give me the new end point of the line, shortening it by 10 pixels.
Solution
Thank you for your answers from which I was able to put together the following procedure. I named it LengthenLine, since I find it more natural to pass a negative number of pixels if I want the line shortened.
Specifically, I was trying to put together a function that could draw a line with rounded corners, which can be found here.
public void LengthenLine(PointF startPoint, ref PointF endPoint, float pixelCount)
{
if (startPoint.Equals(endPoint))
return; // not a line
double dx = endPoint.X - startPoint.X;
double dy = endPoint.Y - startPoint.Y;
if (dx == 0)
{
// vertical line:
if (endPoint.Y < startPoint.Y)
endPoint.Y -= pixelCount;
else
endPoint.Y += pixelCount;
}
else if (dy == 0)
{
// horizontal line:
if (endPoint.X < startPoint.X)
endPoint.X -= pixelCount;
else
endPoint.X += pixelCount;
}
else
{
// non-horizontal, non-vertical line:
double length = Math.Sqrt(dx * dx + dy * dy);
double scale = (length + pixelCount) / length;
dx *= scale;
dy *= scale;
endPoint.X = startPoint.X + Convert.ToSingle(dx);
endPoint.Y = startPoint.Y + Convert.ToSingle(dy);
}
}
Find the direction vector, i.e. let the position vectors be (using floats) B = (x2, y2) and A = (x1, y1), then AB = B - A. Normalize that vector by dividing by its length ( Math.Sqrt(xx + yy) ). Then multiply the direction vector AB by the original length minus the circle's radius, and add back to the lines starting position:
double dx = x2 - x1;
double dy = y2 - y1;
double length = Math.Sqrt(dx * dx + dy * dy);
if (length > 0)
{
dx /= length;
dy /= length;
}
dx *= length - radius;
dy *= length - radius;
int x3 = (int)(x1 + dx);
int y3 = (int)(y1 + dy);
Edit: Fixed the code, aaand fixed the initial explanation (thought you wanted the line to go out from the circle's center to its perimeter :P)
I'm not sure why you even had to introduce the circle. For a line stretching from (x2,y2) to (x1,y1), you can calculate any point on that line as:
(x2+p*(x1-x2),y2+p*(y1-y2))
where p is the percentage along the line you wish to go.
To calculate the percentage, you just need:
p = r/L
So in your case, (x3,y3) can be calculated as:
(x2+(10/L)*(x1-x2),y2+(10/L)*(y1-y2))
For example, if you have the two points (x2=1,y2=5) and (x1=-6,y1=22), they have a length of sqrt(72 + 172 or 18.38477631 and 10 divided by that is 0.543928293. Putting all those figures into the equation above:
(x2 + (10/l) * (x1-x2) , y2 + (10/l) * (y1-y2))
= (1 + 0.543928293 * (-6- 1) , 5 + 0.543928293 * (22- 5))
= (1 + 0.543928293 * -7 , 5 + 0.543928293 * 17 )
= (x3=-2.807498053,y3=14.24678098)
The distance between (x3,y3) and (x1,y1) is sqrt(3.1925019472 + 7.7532190152) or 8.384776311, a difference of 10 to within one part in a thousand million, and that's only because of rounding errors on my calculator.
You can use similar triangles. For the main triangle, d is the hypotenuses and the extension of r is the vertical line that meets the right angle. Inside the circle you will have a smaller triangle with a hypotenuses of length r.
r/d = (x2-a0)/(x2-x1) = (y2-b0)/(y2-y1)
a0 = x2 + (x2-x1)r/d
b0 = y2 + (y2-y1)r/d

Categories

Resources