Brandon Eleuterio

Articles

Learning Rust – Part 4: Drawing a Sphere

Brandon Eleuterio

In the last post, we drew a blue and white blended rectangle. In this post, we’re continuing our focus on foundational steps by adding a sphere to that rectangle.

A Sphere!

Red sphere

Admittedly, it sort of resembles the flag of Japan, but it’s actually great progress. Drawing a single object with our ray tracer demonstrates how we can color pixels in a pattern.

Simple Code

Using the ray_color function built in the last post, we add an ‘if’ statement to check each ray to see if it intersects with where we want our sphere to appear.

if hit_sphere(&Point3::new(0.0, 0.0, -1.0), 0.5, r) {
    return Color::new(1.0, 0.0, 0.0);
}

The hit_sphere function checks to see if a ray intersects with a sphere with a given center at 0, 0, -1 and a given radius of 0.5.

Next Stop

Now that we have a sphere, we’ll start looking at concepts like lighting and shading to bring our sphere into the 3D realm. We’ll also add support for drawing multiple spheres. Check out my code on Github and the online book I’m following, Ray Tracing in One Weekend.

Tags:

Leave a Reply

Your email address will not be published.

Back to top