# T5 Adding a Sphere

Now we are going to show colour based on if we hit a sphere

#### Add a function before ray\_color to calcuate the intersection of a ray with a sphere

```cpp
bool hit_sphere(const point3& center, double radius, const ray& r) {
    vec3 oc = center - r.origin();
    auto a = dot(r.direction(), r.direction());
    auto b = -2.0 * dot(r.direction(), oc);
    auto c = dot(oc, oc) - radius*radius;
    auto discriminant = b*b - 4*a*c;
    return (discriminant >= 0);
}
```

#### Revise ray\_color to show color based on hits

```cpp
color ray_color(const ray& r) {
    if (hit_sphere(point3(0,0,-1), 0.5, r))
        return color(0, 1, 0);

    vec3 unit_direction = unit_vector(r.direction());
    auto a = 0.5*(unit_direction.y() + 1.0);
    return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0);
}
```

#### Build and Run Your Program

```
./ray01.exe > image3.ppm
```

If successful, you should be able to see

<figure><img src="https://3464970502-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3JUKGJZ67JX02QZdPhsy%2Fuploads%2Fq3LgcdwkX3G9lWJAMaQN%2Ffe0a3d4e-1918-461f-8130-d7559e05777a.png?alt=media&#x26;token=ee72687c-e9c9-4331-81e4-9bf2076b1afd" alt="" width="318"><figcaption></figcaption></figure>
