如何仅检测一侧两个物体之间的碰撞?

问题描述 投票:0回答:1

这就像用篮子抓住一个物体。 (第一个对象的底部和第二个对象的顶部)。这是我的代码示例,但它检测所有方面。

        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;
      }

更新:嗨肯尼斯米切尔德莱昂,我尝试了你的解决方案,并将半径改为高度和宽度,它工作。我现在的问题是篮子可移动或可拖动以接球。 (对不起,我提到的很晚)所以当我把篮子拖到球上时,即使它没有穿过篮筐的顶部,它仍能抓住球。

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;
}
javascript html html5 web canvas
1个回答
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。但是它不会检测球是否已从一个点传递到另一个点(即从上到下);

一些信息会更有用......你的目标是什么样的碰撞检测?

  • 线和盒子?
  • 线和线?
  • 线和圆? //我假设这个,我会根据更多信息编辑我的答案。

我编辑了这个功能。只需使用两次,间隙不超过图像/球高。

© www.soinside.com 2019 - 2024. All rights reserved.