Jump to content
  • Advertisement
Sign in to follow this  

Collision between sphere and terrain mesh

This topic is 2338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to implement collision between a sphere, which is the camera, and the mesh, so that I can make a first person game. My problem is that sometimes, I go through some planes.
I tried implementing a variable which tells me if I stand on the ground or not, applying gravity only if I'm not on the ground. It sort of worked, but I didn't think it was really correct.
So, now that I'm applying gravity all the time, it's more buggy. Here's some code:

In the main loop:

gravity += .05;
camera.speed.y -= gravity;
spheremodel(camera.pos, camera.radius, camera.speed, map);
camera.pos += camera.speed;

The spheremodel method:

void spheremodel(Vec3f &pos, float radius, Vec3f &speed, model model){
for (int f = 0; f < (signed)model.faces.size(); f++) {
face face = model.faces[f];
float dist1 = (pos - face.vertices[0]).dot(face.normal);
float dist2 = (pos + speed - face.vertices[0]).dot(face.normal);
float dist = 0;
if((dist1 > 0 and dist2 < 0) or (dist1 < 0 and dist2 > 0))
dist = abs(dist1 - dist2);
else dist = abs(dist1);
if (pointinpolygon(pos - face.normal * dist, face)) {
pos += face.normal * (radius - dist);

The pointinpolygon method:

bool pointinpolygon(Vec3f point, face face) {
Vec3f a, b, p, q;
a = face.vertices[face.np-1] - point;
b = face.vertices[0] - point;
p = a.cross(b);
int i;
for(i = 0; i < face.np - 1; i++) {
a = face.vertices - point;
b = face.vertices[i+1] - point;
q = a.cross(b);
if(p.dot(q) < 0) return false;
return true;

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!