Sphere Drawing in Java

2019-05-29 08:04发布

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...
                    }
                }
         }
}

2条回答
三岁会撩人
2楼-- · 2019-05-29 08:36

The more optimal solution will be:

 int r2=radius*radius;
 for(int X = -radius; X <= radius; X++ ){
    int x2=X*X;
    for(int Y = -radius; Y <= radius; Y++ ){
        int y2=Y*Y;
        for(int Z = -radius; Z <= radius; Z++ )
            if(x2 + y2 + (Z * Z) <= r2)
                SetInShere(X,Y,Z);
    }
 }
查看更多
老娘就宠你
3楼-- · 2019-05-29 08:38

Assuming that your sphere's origin is (0,0,0), I think you have an extra square root in there.

Also, multiplying X*X is several times faster than Math.pow(X,2)

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.

(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);
查看更多
登录 后发表回答