简体   繁体   中英

Stop two rectangles from intersecting

两个矩形

This little world contains a person (blue rectangle), and a tree (large green rectangle). The person can be controlled by pressing the up, down, left, right keys on the keyboard. The blue rectangle only moves when the keys are pressed. The blue rectangle must not get off the map (ie must not get out of the grey area), and must not overlap the green rectangle.

I am aware of the method to prevent the blue rectangle from getting off the grey area:

if (blueRect.rightEdge >= (canvas.width - 1)) {
    // Don't allow going further to the right
    // But allow going up, down, and to the left
}

// Check the same thing for the other sides of the grey area

What I am not sure is how to prevent the two rectangles from intersecting. 两个矩形

In the picture above, how do I "disable" going to the right (to prevent an intersection)? I would still like to be able to go up, down, and left.

What you are dealing with is called collision detection . I don't believe there is a simple answer that always applies.

However, in your case, because you have simple rectangles, you can check to see if any one of the four corners of the SMALLER rectangle is inside the LARGER rectangle.

If you don't know which is smaller, and which is larger, you could check in both directions (ie is rectangle A's corner inside rectangle B, and then if rectangle B's corner is inside rectangle A). Make sure you use >= and <= to catch that pesky boundary condition.

Perhaps something like this is appropriate (pseudocode):

nextLocation = translate(rectangleA, "up")
if (isIntersecting(rectangleB, nextLocation)) {
    error("collision!")
} else {
    rectangleA = nextLocation
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM