T
T
Triborg-3332019-09-13 11:33:35
JavaScript
Triborg-333, 2019-09-13 11:33:35

How to make a competent collision of objects?

5d7b54562a933548948126.png
Game
https://codepen.io/CrystaZZ/pen/jONKZBd

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-09-13
@Triborg-333

const { position: { x, y }, cell_radius, food_size, food } = this;
for (let i = food.length; i--; ) {
  if ((food[i].x - x) ** 2 + (food[i].y - y) ** 2 <= (cell_radius + food_size) ** 2) {
    food.splice(i, 1);
  }
}

H
hzzzzl, 2019-09-13
@hzzzzl

for (var i = 0; i < this.food.length; i++) {
  const {x: x1, y: y1} = this.position
  const r1 = this.cell_radius
  const {x: x2, y: y2} = this.food[i]
  const r2 = this.food_size

  const distance = Math.sqrt( (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) )
  const intersects = distance <= r1 + r2

  if(intersects) {
    console.log('I EAT', this.food[i])
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question