In this post, I will talk about collision detection and handling.
There are plenty of useful resources on collision detection:
- http://www.dyn4j.org/2010/01/sat/
- http://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169
- http://www.metanetsoftware.com/technique/tutorialA.html
- https://github.com/rjdlee/Tanks/blob/master/src/common/collision/collision.js (my own code)
I did not find so much on collision handling. Once you've detected a collision between two convex shapes, you need to figure out what to do with the objects. Should they push each other around? Should their velocities cancel out?
In Tanks, I used two methods. If a tank collides when moving forwards or backwards, it should slide along the other surface. If a tank collides when turning, it should seemingly push off the other surface.
When detecting collisions, it is important to find the exact surface your object is colliding on. To find the surface, find the surface with the least overlap.
After that, simply project the velocity of the moving object onto that surface's vector. If the moving object is colliding with more than one surface, you can project its velocity multiple times.
One thing to note is when trying to move away from a surface, if the moving object is detected as colliding, its velocity may continually be projected on the surface and the object will not be able to move away. This can be solved by ensuring the object is no longer colliding with the surface after detection or determining its direction relative to the surface.
When a tank rotates, find how much it overlaps the surface and the surface it is colliding with. And move away using the normal of the surface multiplied by the length of the overlap.
var displacementVector = {
x: overlap * surface.y,
y: overlap * surface.x
};
if ( surface.x < 0 )
displacementVector.y = -displacementVector.y;
if ( surface.y < 0 )
displacementVector.x = -displacementVector.x;
this.move( displacementVector.x, displacementVector.y );
I apologize if this was not clear, I did plan for these posts to be much better thought out, but I'm trying to free up my time for other things.
Other Parts
1. Matrices
Comments