-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sphere.cpp
42 lines (35 loc) · 1.19 KB
/
Sphere.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "Sphere.h"
Collision Sphere::collide(const Ray& _ray) const {
float A = glm::dot(_ray.m_direction, _ray.m_direction);
float B = glm::dot(2*_ray.m_direction, (_ray.m_origin - m_center));
float C = glm::dot((_ray.m_origin - m_center), (_ray.m_origin - m_center)) - glm::pow(m_radius, 2.f);
//both formulas use the discriminant
float t1 = (-B+glm::sqrt(glm::pow(B, 2.f) - 4*A*C))/(2.f*A);
float t2 = (-B-glm::sqrt(glm::pow(B, 2.f) - 4*A*C))/(2.f*A);
glm::vec3 x;//point of collision on sphere
glm::vec3 n;//normal from collision point on sphere
//we need .001
if(t1<t2 && t1>0.001){
x = _ray.at(t1);
n = (x - m_center)/m_radius;
Collision hit1(x, n, &m_material, t1);
return hit1;
}else if(t2<t1 && t2>0.001){
x = _ray.at(t2);
n = (x - m_center)/m_radius;
Collision hit2(x, n, &m_material, t2);
return hit2;
}else if(t1<t2 && t2>0.001){
x = _ray.at(t2);
n = (x - m_center)/m_radius;
Collision hit2(x, n, &m_material, t2);
return hit2;
}else if(t2<t1 && t1>0.001){
x = _ray.at(t1);
n = (x - m_center)/m_radius;
Collision hit1(x, n, &m_material, t1);
return hit1;
}
return Collision();
//return hit or miss
}