2
$\begingroup$

I know there is a pretty simply way to check if a 2D point is inside a circle, I wanted to know how to do there same but in the 3rd dimension. The variables are the point's X, Y, Z and the sphere's 3D point and radius.

Let's say we know that X and Y is inside the circle, can we rotate it 90 degrees and pretend the Z is the X or Y again and use the same algorithm?

I will check in 2 for loops for X and Y if each point is inside circle, I will use the X and Y to plot the pixel and the Z to determine the colour.

EDIT:

Thanks for the answer, I didn't realize I could just include the Z into the algorithm I was talking about. In case you were interested here is the code, it works great! It's in F#.

open System.IO
open System.Drawing

type Vector = { X: int; Y: int; Z: int }

type Sphere = { Center: Vector; Radius: int }

let intersect v s =
    let x0, y0, z0 = float(v.X), float(v.Y), float(v.Z)
    let x1, y1, z1 = float(s.Center.X), float(s.Center.Y), float(s.Center.Z)
    sqrt(pown(x0 - x1) 2 + pown(y0 - y1) 2 + pown(z0 - z1) 2) < float(s.Radius)

let sphere = { Center = { X = 127; Y = 127; Z = 127 }; Radius = 127 }

let bitmap = new Bitmap(256, 256)

for x in 0 .. 255 do
    for y in 0 .. 255 do
        for z in 0 .. 255 do
            if intersect { X = x; Y = y; Z = z } sphere then
                bitmap.SetPixel(x, y, Color.FromArgb(z, 0, 0, 255))

bitmap.Save(Path.Combine(__SOURCE_DIRECTORY__, "bitmap.png"))
$\endgroup$

2 Answers 2

8
$\begingroup$

Rather than using two 2D tests to check (which is incorrect – points passing both tests are only guaranteed to lie inside a mouhefanggai/Steinmetz solid which strictly encloses the sphere), a simple extension of the 2D test will work. Let the sphere's centre coordinates be $(c_x,c_y,c_z)$ and its radius be $r$, then point $(x,y,z)$ is in the sphere iff $(x-c_x)^2+(y-c_y)^2+(z-c_z)^2<r^2$.

$\endgroup$
3
  • $\begingroup$ Does the R needs to be pow of 2 too? $\endgroup$
    – Fck
    Feb 18, 2019 at 23:27
  • $\begingroup$ @Alanay $r$ may be any number, as long as it's positive. $\endgroup$ Feb 18, 2019 at 23:28
  • $\begingroup$ Thanks! I update the post so you can see my working code. =) $\endgroup$
    – Fck
    Feb 18, 2019 at 23:42
5
$\begingroup$

If a point $M$ of cartesian coordinates $x_0,y_0,z_0$ is inside a circle of center $x_c,y_c,z_c$ of radius $R$, it means that $\sqrt{(x_0-x_c)^2+(y_0-y_c)^2 + (z_0-z_c)^2} \leq R$.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .