// A versatile version of class Point with Rotation and internal methods
// for rectangular and polar coordinates.
using System;
public class Point {
public enum PointRepresentation {Polar, Rectangular}
private double r, a;
public Point(double x, double y){
r = RadiusGivenXy(x,y);
a = AngleGivenXy(x,y);
}
public Point(double par1, double par2, PointRepresentation pr){
if (pr == PointRepresentation.Polar){
r = par1; a = par2;
}
else {
r = RadiusGivenXy(par1,par2);
a = AngleGivenXy(par1,par2);
}
}
public double X {
get {return XGivenRadiusAngle(r,a);}
}
public double Y {
get {return YGivenRadiusAngle(r,a);}
}
public double Radius {
get {return r;}
}
public double Angle{
get {return a;}
}
public void Move(double dx, double dy){
double x, y;
x = XGivenRadiusAngle(r,a); y = YGivenRadiusAngle(r,a);
r = RadiusGivenXy(x+dx, y+dy);
a = AngleGivenXy(x+dx, y+dy);
}
public void Rotate(double angle){
a += angle;
}
public override string ToString(){
return "(" + XGivenRadiusAngle(r,a) + "," + YGivenRadiusAngle(r,a) + ")";
}
private static double RadiusGivenXy(double x, double y){
return Math.Sqrt(x * x + y * y);
}
private static double AngleGivenXy(double x, double y){
return Math.Atan2(y,x);
}
private static double XGivenRadiusAngle(double r, double a){
return r * Math.Cos(a);
}
private static double YGivenRadiusAngle(double r, double a){
return r * Math.Sin(a);
}
} | |
Polar data representation.
Radius (r) and angle(a).
A somewhat strange constructor.
A factory method would be better.
Calculated access to x-coordinate of the point
via the property X.
Calculated access to y-coordinate of the point
via the property Y.
Trivial access to radius of the point
via the property Radius
Trivial access to angle of the point
via the property Angle
Mutates the position of point by adding
dx to x-coordinate and adding dy to
y-coordinate. Converts internally to
rectangular coordinates, adds dx and dy,
and converts back!
It is easy to rotate the point
because the point is represented
in polar coordinates.
RECTANGULAR <-> POLAR CONVERSION METHODS:
Calucates radius given x and y
Calucates angle given x and y
Calculates x given r and a
Calcuates y given r and a
|