Задать вопрос
Triborg-333
@Triborg-333

Как сделать грамотное столкновение объектов?

  • Вопрос задан
  • 184 просмотра
Подписаться 1 Простой Комментировать
Решения вопроса 2
hzzzzl
@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])
  }
}
Ответ написан
Комментировать
0xD34F
@0xD34F Куратор тега JavaScript
const { position, cell_radius, food_size, food } = this;
const isIntersects = (a, b) =>
  (a.x - b.x) ** 2 + (a.y - b.y) ** 2 <= (cell_radius + food_size) ** 2;

food.reduceRight((_, n, i, a) => isIntersects(n, position) && a.splice(i, 1), null);

// или

food.splice(0, food.length, ...food.filter(n => !isIntersects(n, position)));

// или

food.length -= food.reduce((acc, n, i, a) => (
  a[i - acc] = n,
  acc + isIntersects(n, position)
), 0);
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы