I'm currently developing a 3D space shooter game using ThreeJs and facing some challenges with collisions. While I've come across several examples online on how to detect collisions, none seem to solve my specific issue.
The problem arises when the ship collides with a planet and stops moving. However, if the player rotates the ship after the collision and then tries moving forward again, the ship ends up getting "sucked" into the planet!
Check out my demo here: Controls: W,A,S,D to rotate the ship up, left, down, right, respectively. Controls: Up, Down, Left, Right to move and turn.
Below is the specific code snippet that handles collision detection:
function CollisionDetected()
{
if (!shipSphere)
{
return false;
}
var moveDistance = 100 * delta; // 100 pixels per second
var originPoint = shipSphere.position.clone();
if (shipSphere)
{
shipSphere.position.x = ship.position.x;
shipSphere.position.y = ship.position.y;
shipSphere.position.z = ship.position.z;
shipSphere.rotation.x = ship.rotation.x;
shipSphere.rotation.y = ship.rotation.y;
shipSphere.rotation.z = ship.rotation.z;
}
for (var vertexIndex = 0; vertexIndex < shipSphere.geometry.vertices.length; vertexIndex++)
{
var localVertex = shipSphere.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(shipSphere.matrix);
var directionVector = globalVertex.sub(shipSphere.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
var collisionResults = ray.intersectObjects(collidableMeshList);
if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length())
{
if (keyboard.pressed("up"))
{
ship.translateX(-moveDistance*2);
}
else if (keyboard.pressed("down"))
{
ship.translateX(moveDistance*2);
}
}
}
}