Die AABB -Kollision zwischen Kreis und Rechteck übersät
Posted: 02 Jun 2025, 20:08
Ich bin ziemlich neu in JavaScript und ich habe versucht, ein kleines Spiel aufzubauen, um neue Konzepte zu lernen. Ein Problem, auf das ich begegnet bin, ist, dass Projektile im Spiel oft eine höhere Geschwindigkeit haben als die Breite der Objekte, mit denen sie kollidieren sollten, und so durch die Kollision auf den Kollision in jedem Rahmen vorbeikommen. Mein aktueller Code nimmt ein Rechteck und einen Kreis zusammen, zusammen mit ihren x jeder Y -Geschwindigkeit und erhält ihre relative Geschwindigkeit. Es wird dann den Bereich des Rechtecks im x und y um das 2 -fache des Radius des Kreises aufblasen.
Code: Select all
function sweptAABB(pointx, pointy, velx, vely, deltaTime, rectx, recty, rectw, recth){
//pointx and pointy are the circle's center, velx and vely are the relative velocities
//how far the "point" (this is the circle, but it's a point since we're expanding our rectangle to account for it's radius) will move during the frame:
const movementX = velx*(deltaTime);
const movementY = vely*(deltaTime)
const invMoveX = movementX !== 0 ? 1 / movementX : Infinity;
const invMoveY = movementY !== 0 ? 1 / movementY : Infinity;
//times that the point would enter/exit the rectangle
const tEnterXY = {x: (rectx-pointx)*invMoveX, y:(recty - pointy) * invMoveY}
const tExitXY = {x: (rectx+rectw-pointx)*invMoveX, y:(recty+recth - pointy) * invMoveY};
//the earliest posible enter/exit times
const enterTime = Math.max(Math.min(tEnterXY.x, tExitXY.x), Math.min(tEnterXY.y, tExitXY.y));
const exitTime = Math.min(Math.max(tEnterXY.x, tExitXY.x), Math.max(tEnterXY.y, tExitXY.y));
return enterTime = 0 && enterTime