首页 > 解决方案 > 如何获得2个球/物体之间的距离?

问题描述

我正在用球做游戏:

class Ball {

    constructor(x, y, vx, vy, radius, r, g, b) {
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.radius = radius; 
        this.r = r;
        this.g = g;
        this.b = b;

    }

    Draw() {
        this.x = this.x + this.vx*frametime;
        this.y = this.y + this.vy*frametime;
        context.fillStyle = "rgb(" + this.r + ", " + this.g + ", " + this.b + ")"
        context.beginPath();
        context.arc(this.x, this.y, this.radius, 0, Math.PI*2);
        context.closePath();
        context.fill();

我想知道两个球之间的距离......怎么做?

标签: javascript

解决方案


在你的班级 Ball 中使用它:

Distance(ball) {
  var distance = Math.pow(this.x - ball.x, 2) + Math.pow(this.y - ball.y, 2);
  return Math.sqrt(distance);
}

推荐阅读