Стрельба шарами в правильном направлении
мне нужно сделать так, что б каждый новый шар вылетал в ту сторону, куда указывает моя стрелка (стрелка поворачивается на колесеко мыши). Все до чего я додумался, это использовать теорему Пифагора, но тоже не вышло.
let canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
r = 5,
x,
cursor = document.createElement("DIV"),
arrow = document.getElementsByClassName("fa-arrow-up")[0],
canvasPositionX = canvas.getBoundingClientRect().x,
canvasPositionY = canvas.getBoundingClientRect().y,
wheelCounter;
canvas.width = 800;
canvas.height = 500;
document.body.style.cursor = "none";
cursor.classList.add("divCursor");
document.body.appendChild(cursor);
cursor.appendChild(arrow)
class Ball {
constructor(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.dx = wheelCounter;
this.dy = -wheelCounter;
this.animate();
}
drawBall() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.clearRect(this.x - this.r - 4, this.y - this.r - 4, this.r + 16, this.r + 16);
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
animate() {
this.drawBall();
if (this.x + this.dx > canvas.width - this.r || this.x + this.dx < this.r) {
this.dx = -this.dx;
canvas.style.boxShadow = `inset 0px 0px 35px 0px rgb(${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)})`;
}
if (this.y + this.dy > canvas.height - this.r || this.y + this.dy < this.r) {
this.dy = -this.dy;
canvas.style.boxShadow = `inset 0px 0px 35px 0px rgb(${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)})`;
}
this.x += this.dx;
this.y += this.dy;
requestAnimationFrame(() => this.animate());
}
}
canvas.addEventListener("mousedown", () => {
cursor.style.animation = "cursorPressed 1s ease-in-out infinite";
x = setInterval(() => {
r++;
}, 200);
})
canvas.addEventListener("mouseup", (e) => {
cursor.style.animation = "cursor 1s ease-in-out infinite";
clearInterval(x);
if (r > 7) {
new Ball(e.clientX - canvasPositionX, e.clientY - canvasPositionY, 8, `rgb(${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)})`);
} else {
new Ball(e.clientX - canvasPositionX, e.clientY - canvasPositionY, r, `rgb(${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)},${Math.floor(Math.random() * 255)})`);
}
r = 5;
})
//cursor
window.addEventListener("mousemove", (e) => {
cursor.style.left = `${e.clientX - 15}px`
cursor.style.top = `${e.clientY - 15}px`
})
window.addEventListener("wheel", (e) => {
console.log(wheelCounter)
if (e.deltaY < 0) {
wheelCounter += 5;
} else {
wheelCounter -= 5
}
cursor.style.transform = `rotateZ(${wheelCounter}deg)`;
})