Java中的球体绘图 [英] Sphere Drawing in Java
问题描述
出于某种原因,当我尝试通过检查点的半径来制作Java中的球体时,它给了我一个立方体而不是球体。
For some reason, when I try to make a sphere in Java by checking the radius of points, it gives me a cube instead of a sphere. Is the problem with my code or my formula?
for(double X = 0; X < diameter; X++ )
{
//mcspace.logger.info("X = " + Double.toString(X));
for(double Y = 0; Y < diameter; Y++ )
{
//mcspace.logger.info("Y = " + Double.toString(Y));
for(double Z = 0; Z < diameter; Z++ )
{
//mcspace.logger.info("Z = " + Double.toString(Z));
int radius = diameter / 2;
double cX = X;
double cZ = Z;
double cY = Y;
if (X > radius){cX -= radius;}
if (Y > radius){cY -= radius;}
if (Z > radius){cZ -= radius;}
double Cr = Math.sqrt(Math.sqrt(Math.pow(cX,2) + Math.pow(cY,2)) + Math.pow(cZ,2));
if(Cr <= radius)
{
SetInShere(X,Y,Z);
// This is just a function that is in my code but the problem is that almost all the points are in the sphere, I almost always get a cube instead of a sphere...
}
}
}
}
推荐答案
<假设你的球体的原点是(0,0,0),我认为你有一个额外的平方根。
Assuming that your sphere's origin is (0,0,0), I think you have an extra square root in there.
另外,乘以X * X是几个时间快于 Math.pow(X,2)
...
Also, multiplying X*X is several times faster than Math.pow(X,2)
…
我还会移动半径计算循环,并使其成为一个 double
,就像其他的一样,以防舍入误差来咬你。
I would also move the radius computation outside of the loop, and make it a double
like the rest, just in case the rounding errors would come to bite you.
(你可以用 X + = foo
来替换 X ++
增量,使这个版本可以用更小或更大的步骤工作, )
(You could replace the X++
increments with X += foo
to make this version work with smaller or larger steps, as well.)
double radius = diameter / 2;
for(double X = -radius; X < radius; X++ )
for(double Y = -radius; Y < radius; Y++ )
for(double Z = -radius; Z < radius; Z++ )
if(Math.sqrt((X * X) + (Y * Y) + (Z * Z)) <= radius)
SetInShere(X,Y,Z);
这篇关于Java中的球体绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!