Collision detection in a Java game?

I am developing a game in which I have a problem of detecting collisions of moving images. The game has a spaceship and the number of asteroids (obstacles). I want to detect a collision between them. How can i do this?

+3
source share
4 answers

Collision detection is usually difficult for anything but rectangles.

The way I did this in the past is to provide both an image and a mask for each object. So, for example, an object such as the Jupiter 2 spaceship from Lost in Space will have the following image and mask:

     X            00000100000
  XXXXXXX         00111111100
 X       X        01111111110
X         X       11111111111
 X       X        01111111110
  XXXXXXX         00111111100
    XXX           00001110000

- , , - , . , 1 - .

:

  • , . , .
  • 1, .
  • 2, .
  • - 2 1.
  • 1 1 , .

" ", , . - .

, - :

....xx....
..xx..xx..
.x......x.
.x......x.
x........x
x........x
.x......x.
.x......x.
..xx..xx..
....xx.**y.....
       .y......
       yyyyyyyy
       .y......
       ..y.....

, , (. **y), . , , .


@kyoryu . , , ( ). , ( ) X Y , Z:

    YYYY                .Z.
    YYYY                .Z.
XXXXXXXXXXXX            .Z.
XXXXXXXXXXXX            ZZZ
XXXXXXXXXXXX            .Z.
XXXXXXXXXXXX

. , , . ( , ).

+14

, , , .

c^2 = a^2 + b^2

, , , , ? :

distX ^ 2 + distY ^ 2 <= (radius1 + radious2) ^ 2 == COLLISION!

distX distY - 1 + 2 , .

- , , , .

+1

. x, :

  • .

, , .

first.right < second.left

, .

first.left > second.right

, x.

y ( ), , y - , ! , 2- .

, , O (N ^ 2).

+1

X Y , , , x y. :

|-------
|   |
|   |
|   |
|_______|

`    |
    |
    |
    |
comming down



      |---------|
      |     |
      |     |
      |     |
      |---------|
Minus width and height to find out correct x and y


0
source

Source: https://habr.com/ru/post/1736943/


All Articles