我正在尝试编写一个代码来在XNA中绘制一个椭圆。假设我们有以下参数:
如何使用上述参数绘制椭圆。
这是函数
public VertexPositionColor Set2dEllipse(int x, int y, int z, Color color)
{
VertexPositionColor vertices= new VertexPositionColor[100];
for(int i= 0;i<100;i++)
{
double angle = (i / 100 * Math.PI * 2);
vertices[i].Position = New Vector3((x + (Math.Cos(angle)) * size.Width), (y + Math.Sin(angle) * size.Height), z);
vertices[i].Color = color;
}
}
答案 0 :(得分:2)
我修改了从here获取的代码以满足您的要求。
public void CreateEllipse(int a, int b, int h, int k, float theta)
{
VertexPositionColor[] vertices = new VertexPositionColor[vertexCount];
//Drawing an Ellipse with its major axis parallel to the x-axis. Rotation can be applied to change this.
Vector3 position;
const float max = MathHelper.Pi;
//2 * max since we're moving from -Pi to +Pi in the loop.
float step = 2 * max / (float)vertexCount;
int i = 0;
//Optional Axis and angle rotation for the ellipse (See later notes):
//Vector3 axis = new Vector3(0, 0, -1);
float angle = MathHelper.ToRadians(theta);
for (float t = -max; t <= max; t += step)
{
//Formula shamelessly taken from wikipedia
position = new Vector3(h + a * (float)Math.Cos((double)t), k + b * (float)Math.Sin((double)t), 0f);
//Optional Rotation for the Ellipse:
//position = Vector3.Transform(position, Matrix.CreateFromAxisAngle(axis, angle));
vertices[i] = new VertexPositionColor(position, Color.DarkOrange);
i++;
}
//Optional Rotation for the Ellipse:
position = Vector3.Transform(position, Matrix.CreateFromAxisAngle(axis, angle));
//then add the first vector again so it's a complete loop (sounds familiar)
position = new Vector3(h + a * (float)Math.Cos((double)-max), k + b * (float)Math.Sin((double)-max), 0f);
vertices[vertexCount - 1] = new VertexPositionColor(position, Color.DarkOrange);
vertexBuffer = new VertexBuffer(device, vertexCount * VertexPositionColor.SizeInBytes,
BufferUsage.WriteOnly);
vertexBuffer.SetData<VertexPositionColor>(vertices);
}
答案 1 :(得分:0)
您可以单独根据x或y找出椭圆的方程。然后递增/递减x或y以基于方向获得另一个坐标。这就是我为圆圈所做的事情
this.x+=1.5*Gdx.graphics.getDeltaTime() * direction;
if(direction==1)
{
if(this.x>=(centerx+radius))
{
direction=-1;
}
}
else
{
if(this.x<=(centerx-radius))
{
direction=1;
}
}
this.y=( (float) Math.sqrt(Math.abs(((radius*radius)- ( (this.x -centerx )* (this.x -centerx )) )) )*direction + centery ) ;
PS:代码在java中用于libgdx。你可以相应调整