在canvas HTML5中检测对象相对于另一个对象的位置

detect object place relatively to another object in canvas HTML5

本文关键字:一个对象 位置 相对于 对象 canvas HTML5 检测      更新时间:2023-09-26

我正在HTML5javascript中开发一个简单的游戏。游戏就这么简单:

  • 游戏应该指示玩家将某些物体放入画布上的位置,例如:把苹果放在盒子里,或者,把盒子旁边的苹果。

  • 当玩家拖动对象并将其放置在帆布

  • 比赛应该评估他的动作,并决定他是否将正确的物体是否在正确的地方。

    我的问题是:如何根据另一个对象测试用户放置对象的位置?即:我怎么知道用户把物体放在盒子旁边、盒子下面甚至盒子里面?

我脑海中浮现的唯一想法是:

  • 在画布中绘制透明的Image()并将其边界用作放置区域
  • 或者在玩家应该放置物体的地方创建一个<div>,每当物体与该区域碰撞时,我都应该测试用户的动作。但是,我无法在画布中创建<div>,也无法成功创建透明的Image()。有什么想法吗

使用每个对象的x、y、宽度和高度来检查它们是否重叠:

function getOverlapArea(aX, aY, aW, aH, bX, bY, bW, bH) {
    var overlapX = Math.max(0, Math.min(aX + aW, bX + bW) - Math.max(aX, bX));
    var overlapY = Math.max(0, Math.min(aY + aH, bY + bH) - Math.max(aY, bY));
    return overlapX * overlapY;
}
var apple = { x: 100, y: 100, width: 100, height: 100 };
var box = { x: 200, y: 200, width: 100, height: 100 };
var overlap = getOverlapArea(apple.x, apple.y, apple.width, apple.height, box.x, box.y, box.width, box.height);
if(overlap > 0) {
    // do something
}

我使用了imcg对碰撞的答案,并对其进行了一点修改,以涵盖onRight和onLeft的情况,如下所示:

var overlap = getOverlapArea(shape1.x, shape1.y, shape1.w, shape1.h, shape2.x, shape2.y, shape2.w, shape2.h);
    if(overlap >0)
    {
        console.log("overlapping");
    }
    else {
    var toTheLeft = getOverlapToLeftArea(shape1.x, shape1.y, shape1.w, shape1.h, shape2.x, shape2.y, shape2.w, shape2.h);
        if (toTheLeft > 0) {
        console.log("to the left");
        } 
        else {
                var toTheRight = getOverlapToRightArea(shape1.x, shape1.y, shape1.w, shape1.h, shape2.x, shape2.y, shape2.w, shape2.h);
            if (toTheRight > 0) {
                console.log("to the right");
            }
            else
            {
                console.log("nothing");
            }
    }

在上面的第一个if语句中,我检查了重叠,就像imcg回答的那样。

在下面的函数(getOverlapToLeftArea)中,我将+20 px添加到x中,假设如果shape1与shape2的距离超过20 px,则认为它太远,但如果shape2与shape1的距离为20px或更小,则shape1在shape2左侧。

function getOverlapToLeftArea(aX, aY, aW, aH, bX, bY, bW, bH) {
    var overlapX = Math.max(0, Math.min(aX + aW + 20, bX + bW) - Math.max(aX + 20 , bX));
    var overlapY = Math.max(0, Math.min(aY + aH, bY + bH) - Math.max(aY, bY));
    return overlapX * overlapY;
}

getOverlapToLeftArea也有同样的概念,只是我从x中减去-20 px如下:

function getOverlapToRightArea(aX, aY, aW, aH, bX, bY, bW, bH) {
    var overlapX = Math.max(0, Math.min(aX + aW - 20, bX + bW) - Math.max(aX - 20 , bX));
    var overlapY = Math.max(0, Math.min(aY + aH, bY + bH) - Math.max(aY, bY));
    return overlapX * overlapY;
}

这对我来说很有魅力。如果我想检查形状1是否在上方/下方形状2,我必须从y//strong>中添加/减去20px

谢谢你imcg:),我希望我的回答能帮助到大家。