javascript - 如何解决弹性碰撞?

标签 javascript typescript game-physics

我一直在做一个弹性碰撞演示​​,但似乎不太正确。 circle1 对象似乎从 circle2 对象,但如果它们从另一侧碰撞,则通过 circle2。

如何修改这种弹性碰撞使其更准确?

这里是一个链接 CodePen现场演示。

ma​​in.ts

class DemoCanvas {
    canvasWidth: number = 500;
    canvasHeight: number = 500;
    canvas: HTMLCanvasElement = document.createElement('canvas');
    constructor() {
        this.canvas.width = this.canvasWidth;
        this.canvas.height = this.canvasHeight;
        this.canvas.style.border = '1px solid black';
        this.canvas.style.position = 'absolute';
        this.canvas.style.left = '50%';
        this.canvas.style.top = '50%';
        this.canvas.style.transform = 'translate(-50%, -50%)';
        document.body.appendChild(this.canvas);
    }

    clear() {
        this.canvas.getContext('2d').clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    getContext(): CanvasRenderingContext2D {
        return this.canvas.getContext('2d');
    }

    getWidth(): number {
        return this.canvasWidth;
    }

    getHeight(): number {
        return this.canvasHeight;
    }

    getTop(): number {
        return this.canvas.getBoundingClientRect().top;
    }

    getRight(): number {
        return this.canvas.getBoundingClientRect().right;
    }

    getBottom(): number {
        return this.canvas.getBoundingClientRect().bottom;
    }    

    getLeft(): number {
        return this.canvas.getBoundingClientRect().left;
    }
}

class Circle {
    x: number;
    y: number;
    dx: number;
    dy: number;
    xVelocity: number;
    yVelocity: number;
    radius: number;
    color: string;
    canvas: DemoCanvas;
    context: CanvasRenderingContext2D;

    constructor(x: number, y: number, xVelocity: number, yVelocity: number, color: string, gameCanvas: DemoCanvas) {
        this.radius = 20;
        this.x = x;
        this.y = y;
        this.xVelocity = xVelocity;
        this.yVelocity = yVelocity;
        this.color = color;
        this.canvas = gameCanvas;
        this.context = this.canvas.getContext();
    }

    public draw(): void {
        this.context.fillStyle = this.color;
        this.context.beginPath();
        this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
        this.context.fill();
    }

    public move(): void {
        this.x += this.xVelocity;
        this.y += this.yVelocity;
    }

    checkWallCollision(gameCanvas: DemoCanvas): void {
        let top = 0;
        let right = 500;
        let bottom = 500;
        let left = 0;

        if(this.y < top + this.radius) {
            this.y = top + this.radius;
            this.yVelocity *= -1;
        }

        if(this.x > right - this.radius) {
            this.x = right - this.radius;
            this.xVelocity *= -1;
        }

        if(this.y > bottom - this.radius) {
            this.y = bottom - this.radius;
            this.yVelocity *= -1;
        }

        if(this.x < left + this.radius) {
            this.x = left + this.radius;
            this.xVelocity *= -1;
        }
    }
}

let demoCanvas = new DemoCanvas();
let circle1: Circle = new Circle(250, 250, 5, 5, "#F77", demoCanvas);
let circle2: Circle = new Circle(250, 540, 5, 5, "#7FF", demoCanvas);


function detectCollisions():void {

    if (circle1.x + circle1.radius + circle2.radius > circle2.x 
        && circle1.x < circle2.x + circle1.radius + circle2.radius
        && circle1.y + circle1.radius + circle2.radius > circle2.y 
        && circle1.y < circle2.y + circle1.radius + circle2.radius) {
            if (distanceTo() < circle1.radius + circle2.radius) {
                calculateNewVelocities();
            }
    }
}

function distanceTo():Number {
    var distance = Math.sqrt(((circle1.x - circle2.x) * (circle1.x - circle2.x)) + ((circle1.y - circle2.y) * (circle1.y - circle2.y)));
    if (distance < 0) { 
        distance = distance * -1; 
    }
    return distance;
}

function calculateNewVelocities():void {
    var mass1 = circle1.radius;
    var mass2 = circle2.radius;
    var velX1 = circle1.xVelocity;
    var velX2 = circle2.xVelocity;
    var velY1 = circle1.yVelocity;
    var velY2 = circle2.yVelocity;

    var newVelX1 = (velX1 * (mass1 - mass2) + (2 * mass2 * velX2)) / (mass1 + mass2);
    var newVelY1 = (velY1 * (mass1 - mass2) + (2 * mass2 * velY2)) / (mass1 + mass2);

    circle1.xVelocity = newVelX1;
    circle1.yVelocity = newVelY1;

    circle1.x = circle1.x + newVelX1;
    circle1.y = circle1.y + newVelY1;
}

addEventListener('mousemove', function(e) {
    let mouseX = e.clientX - demoCanvas.getLeft();
    let mouseY = e.clientY - demoCanvas.getTop();
    circle2.x = mouseX;
    circle2.y = mouseY;
});

function loop() {
    demoCanvas.clear();
    circle1.draw();
    circle2.draw();
    circle1.move();
    circle1.checkWallCollision(demoCanvas);
    circle2.checkWallCollision(demoCanvas);
    detectCollisions();
    requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

最佳答案

嗯,我不确定你从哪里得到你的公式来更新 circle1 的速度当它与 circle2 碰撞时, 但是 the correct formula取决于两个圆的相对位置(不仅是它们之间的距离,还包括接触 Angular )。

如果我们假设 circle2将是静止的(或者质量如此之大以至于 circle1 不会影响它的运动),那么 calculateNewVelocities() 中的代码应该看起来像这样:

  var xd = circle1.x - circle2.x; // x displacement between circles
  var yd = circle1.y - circle2.y; // y displacement between circles
  var dsq = xd*xd + yd*yd; // square of distance between circles

  var DV = 2*(velX1*xd + velY1*yd)/dsq; // velocity change factor
  // EDIT
  // fix to prevent orbiting... if circle1 is already rebounding, 
  // leave it alone
  if (DV > 0) {
    DV=0;
  }

  // velocity change is in the opposite direction of 
  // the displacement between circles
  var newVelX1 = velX1 - DV * xd; 
  var newVelY1 = velY1 - DV * yd;

当碰撞来自外部时,这应该会给你一些模糊合理的东西。如果您发现圆圈重叠,这可能会导致 circle1轨道 circle2或类似的疯狂事情,所以您可能想对其进行调整以防止此类事情发生。

编辑:我认为我之前提到的“轨道”问题是碰撞后圆圈继续重叠的结果,快速连续触发多次碰撞。解决方法是不修改 circle1 的速度如果它已经离开 circle2 的中心.这样只有第一次碰撞有任何影响,随后检测到的碰撞将被忽略,直到 circle1。正在走向circle2再次。

无论如何,这只是一个建议。希望你能找到你要找的东西。祝你好运。

关于javascript - 如何解决弹性碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498808/

相关文章:

javascript - 具有动态绑定(bind)内容的自调用函数作用域

javascript - 如何指示弹出窗口已被 Safari 阻止?

javascript - 计算近似值SVG 椭圆长度? (用Javascript计算近似椭圆周长)

typescript - 在 typescript 中使用 SES 发送电子邮件

angular - 在以 Angular 调用之前等待数组完成填充

javascript - d3.js 使用 python websocket 数据实时更新 svg 行

jquery - dts-gen引用错误: jQuery is not defined

java - 这个平台滚动代码到底做了什么?

c++ - 多维边界框碰撞检测

c++ - 在基本 C++ 引擎中使用一致速度计算速度