javascript - 如何获得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();
我想知道两个球之间的距离......怎么做?
解决方案
在你的班级 Ball 中使用它:
Distance(ball) {
var distance = Math.pow(this.x - ball.x, 2) + Math.pow(this.y - ball.y, 2);
return Math.sqrt(distance);
}
推荐阅读
- django - Django 过滤器集和多个值
- python - openmdao 可以跨 Matlab ExternalCodeComp 计算偏导数而不显式定义它们吗?
- html - 在 Vue.js + TypeScript 中更改图像源属性
- wordpress - 最近从 calendars.icloud.com 读取失败...为什么?
- python - 如何使用参数调用存储为变量的函数 - Python 3
- postgresql - AWS 链接数据库并在多个数据库上运行查询
- r - 从 R 以编程方式启动 BAPI?
- javascript - 我可以在 if/else 条件语句中引用之前定义的函数吗?
- kotlin - 如何在任何条件下使用 assertThat?
- sql - 更新 SQL 表中数据选择中的列并保存