这就像用篮子抓物体一样。 (第一个对象的底部和第二个对象的顶部)。这是我的代码的示例,但是它正在检测所有方面。
this.hitPocket = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
更新: 嗨,肯尼思·米切尔·德·莱昂(Kenneth Mitchell De Leon),我尝试了您的解决方案,将半径更改为高度和宽度,然后它起作用了。我现在的问题是篮筐可以移动或拖动以接住球。 (很抱歉,我提到的太晚了)因此,当我将篮筐拖入球中时,即使它没有穿过篮筐的顶部,它仍然可以接住球。
function hasContact(basket, ball){
const hoop = {
topLeft: {x:basket.x+10, y: basket.y},
topRight: {x: basket.x+basket.width-10,
y: basket.y}
//not necessary if your only concern is the top panel
// botLeft: {x: basket.position.x,
// y: basket.position.y+basket.height},
// botRight: {x:basket.position.x+basket.width,
// y:basket.position.y+basket.height}
}
//determine if ball is in between top left or top right of the basket in x axis
if(ball.x > hoop.topLeft.x && ball.x+ball.width < hoop.topRight.x
//determine if the ball is in contact with top panel of basket in y axis
&& ball.y-basket.y < ball.height/2 && basket.y - ball.y < ball.height/2){
return true;
}
return false;
}
答案 0 :(得分:0)
//point = {x: value, y: value} - assuming this is point object
function hasContact(point1, point2, ball){
//determine if ball is in between point1 and point2 in x axis
if(ball.position.x-ball.radius > point1.x && ball.position.x+ball.radius < point2.x
//determine if the ball is in contact in y axis
&& ball.position.y-point1.y < ball.radius && point1.y - ball.position.y < ball.radius){
return true;
}
return false;
}
//position 1 is top left
//position 2 is top right
if(hasContact(position1, position2, circle)
//use same x coords in position 1 and 2
//then add y coordinates with the ball/image height-n
//position 3 is bottom left - just low enough but not more than image/ball height
//position 5 is bottom right
&& hasContact(position3, position4, circle)){
//shot is made - do something here....
}
我假设像篮球...
如果整球位于水平线的左右边缘之间,则此方法将返回true,您可以自行调整以将其设置为如果球的任何部分与该线接触则返回true。但是,它无法检测到球是否已从一个点传递到另一个点(即从上到下);
一些信息会更有用... 您打算使用哪种碰撞检测?
我编辑了该功能。只需在间隙不超过图像/球高的地方使用两次即可。