JavaScript中的圆碰撞 [英] Circle collision in JavaScript

查看:74
本文介绍了JavaScript中的圆碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学校来说,我需要用JavaScript编写一个程序,该程序说明圆是否发生了碰撞。

For school I need to make a program in JavaScript that says if circles had a collision.

它不需要以图形方式显示。

It doesn't need to be shown graphically.

我尝试了一下,但是我的代码似乎不起作用。我该如何解决?

I gave it a try, but my code doesn't seem to work. How can I fix it?

这是我生成的代码:

function collision (p1x, p1y, r1, p2x, p2y, r2) {
    var a;
    var x;
    var y;

    a = r1 + r2;
    x = p1x - p2x;
    y = p1y - p2y;

    if (a > (x*x) + (y*y)) {
        return true;
    } else {
        return false;
    }
}
var collision = collision(5, 500, 10, 1000, 1500, 1500);
alert(collision);


推荐答案

您的支票应为 (a> Math.sqrt((x * x)+(y * y)))
http://cgp.wikidot.com/circle-to-circle-collision-detection

完整的代码是

function collision(p1x, p1y, r1, p2x, p2y, r2) {
  var a;
  var x;
  var y;

  a = r1 + r2;
  x = p1x - p2x;
  y = p1y - p2y;

  if (a > Math.sqrt((x * x) + (y * y))) {
    return true;
  } else {
    return false;
  }
}
var collision = collision(5, 500, 10, 1000, 1500, 1500);
console.log(collision);

,而对于较少的计算实现(使用ES7语法作为代码段),请使用

and for a less computational implementation (using ES7 syntax for the snippet) use

const checkCollision = (p1x, p1y, r1, p2x, p2y, r2) => ((r1 + r2) ** 2 > (p1x - p2x) ** 2 + (p1y - p2y) ** 2)

var collision = checkCollision(5, 500, 10, 1000, 1500, 1500);
console.log(collision);

如Darek Rossman在< a href = https://stackoverflow.com/questions/8331243/circle-collision-in-javascript/8331460#8331460>他的回答。

as Darek Rossman shows in his answer.

这篇关于JavaScript中的圆碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆