I'm trying to rotate polygon randomly using timer. I got to draw regular polygons and rotate it to one direction. But I'm not sure about how to rotate polygon to random direction using angle or timer interval.
My Code is below:
int sides = 5;
Graphics g = e.Graphics;
nPoints = CalculateVertices(sides, radius, angle, center);
g.DrawPolygon(navypen, nPoints);
g.FillPolygon(BlueBrush, nPoints);
Point center = new Point(ClientSize.Width / 2, ClientSize.Height / 2);
for(int i = 0; i < sides; i++) {
g.DrawLine(new Pen(Color.Navy), center.X, center.Y, nPoints[i].X, nPoints[i].Y);
}
private PointF[] CalculateVertices(int sides, int radius, float startingAngle, Point center)
{
if (sides < 3) {
sides = 3;
}
List<PointF> points = new List<PointF>();
float step = 360.0f / sides;
float angle = startingAngle; //starting angle
for (double i = startingAngle; i < startingAngle + 360.0; i += step) //go in a circle
{
points.Add(DegreesToXY(angle, radius, center));
angle += step;
}
return points.ToArray();
}
private PointF DegreesToXY(float degrees, float radius, Point origin)
{
PointF xy = new PointF();
double radians = degrees * Math.PI / 180.0;
xy.X = (int)(Math.Cos(radians) * radius + origin.X);
xy.Y = (int)(Math.Sin(-radians) * radius + origin.Y);
return xy;
}
private void timer2_Tick(object sender, EventArgs e){
angle += 1;
angle_tri -= 1;
Invalidate();
}
答案 0 :(得分:3)
这是一个绘制以不同速度旋转的点列表的示例,包括角度和时间......:
首先是几个变量:
Random rnd = new Random();
float angle = 0f;
List<Point> points = new List<Point>();
然后Tick
具有不同的速度和不同的角度:
private void timer1_Tick(object sender, EventArgs e)
{
angle += rnd.Next(0, 33)/ 10f;
timer1.Interval = rnd.Next(100) + 15;
pictureBox5.Invalidate();
}
以下是Paint
的{{1}}事件,PictureBox
,因此不会闪烁..:
DoubleBuffered
请注意,由于奇怪的速度变化,这不是很顺利;你必须找到更好的算法,而不仅仅是随机性。