3

Мне надо, чтобы, когда шарик попадёт внутрь квадрата, он двигался внутри, постоянно отскакивая от стен квадрата. Вот набросок моего кода:

let canvas = document.getElementById('canvas');
let c = canvas.getContext('2d');
let rect = new Image();
let ball = new Image();
rect.onload = function() {
  c.drawImage(this, 0, 0, 50, 50);
};
ball.onload = function() {
  c.drawImage(this, 250, 250, 20, 20);
};
rect.src = "https://www.proza.ru/pics/2011/11/09/230.jpg";
ball.src = "https://st.depositphotos.com/1000459/2436/i/450/depositphotos_24366251-stock-photo-soccer-ball.jpg";

class RouletteGame {
  constructor() {
    this.rects = [];
    this.start = false;
  }

  drawImage(i) {
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.drawImage(this.rects[0].object, this.rects[0].x1, this.rects[0].y1, this.rects[0].width, this.rects[0].width);
    c.drawImage(this.rects[10].object, this.rects[10].x1, this.rects[10].y1, this.rects[10].width, this.rects[10].width);
  }

  ballMove(i, operation = 'minus') {
    //Движение по эллипсу
    if (operation === 'plus') {
      this.rects[i].x1 = this.rects[i].x + ((this.rects[i].radius) * Math.sin(this.rects[i].angle)) * Math.sin(0) + (1.4 * (this.rects[i].radius - 5) * Math.cos(this.rects[i].angle)) * Math.cos(0);
    } else {
      this.rects[i].x1 = this.rects[i].x + ((this.rects[i].radius) * Math.sin(this.rects[i].angle)) * Math.sin(0) - (1.4 * (this.rects[i].radius - 5) * Math.cos(this.rects[i].angle)) * Math.cos(0);
    }

    this.rects[i].y1 = this.rects[i].y + (1.2 * (this.rects[i].radius - 15) * Math.cos(this.rects[i].angle)) * Math.sin(0) + (1.2 * (this.rects[i].radius - 15) * Math.sin(this.rects[i].angle)) * Math.cos(0);
    this.rects[i].angle += 0.008;
    this.drawImage();
  }

  create() {
    this.rects.push({
      object: rect,
      angle: 0,
      x: 250,
      y: 225,
      x1: 0,
      x2: 0,
      width: 50,
      radius: 100
    });


    this.rects[10] = {
      object: ball,
      angle: 0,
      x: 250,
      y: 225,
      x1: 250,
      x2: 250,
      dx: 1,
      dy: 1,
      width: 15,
      radius: 150
    };
  }

  update() {

    //Проверяем, что шарик внутри квадрата
    if (this.rects[10].x1 > this.rects[0].x1 && this.rects[10].x1 + this.rects[10].width < this.rects[0].x1 + this.rects[0].width && this.rects[10].y1 > this.rects[0].y1 && this.rects[10].y1 + this.rects[10].width < this.rects[0].y1 + this.rects[0].width) {
      this.start = true;
    }

    this.ballMove(0)

    if (this.start) {
      //Меняем направление движения по x
      if (this.rects[10].x1 <= this.rects[0].x1 || this.rects[10].x1 >= this.rects[0].object.x1 + this.rects[0].width) {
        this.rects[10].dx = -this.rects[10].dx;
      }
      //Меняем направление движения по y
      if (this.rects[10].y1 - 5 <= this.rects[0].y1 || this.rects[10].y1 + 5 >= this.rects[0].y1 + this.rects[0].width) {
        this.rects[10].dy = -this.rects[10].dy;
      }

      this.rects[10].x1 += this.rects[10].dx;
      this.rects[10].y1 += this.rects[10].dy;
    } else {
      this.ballMove(10, 'plus');

      if (this.rects[10].radius > 90) {
        this.rects[10].radius -= 0.2;
      }

    }
  }
}

const roulette = new RouletteGame();
new Promise(resolve => {
    setTimeout(() => {
      roulette.create(); //Создаём объекты
      resolve();
    }, 1000)
  })
  .then(function() {
    setInterval(() => {
      roulette.update(); //Обновляем холст
    }, 20)
  });
canvas {
  border: 1px solid black;
}
<canvas id="canvas" width="800" height="800"></canvas>

1) Ошибка 1: шарик попадает внутрь и как будто сталкивается с невидимой стеной - она не позволяет пройти ему дальше;

2) Рано или поздно шарик выскакивает из квадрата.

Как можно решить данную проблему?

2
  • Если у вас шарик застревает в стенке, то при столкновении со стенкой, кроме изменения направления сделайте сдвиг на количество пикселей, которые шарик прошел внутри стенки, чтобы его вытолкнуть
    – gil9red
    16 окт 2019 в 6:18
  • @gil9red, он у меня застревает вообще в какой-то невидимой и несуществующей стенке. Не понимаю, откуда она берётся, если у меня зависимость от границ квадрата 16 окт 2019 в 6:32

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Посмотрите другие вопросы с метками или задайте свой вопрос.