HTML5 Javascript Canvas Collision 2
by Spsoi
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script src="canvas.js" ></script>
</body>
</html>
CSS
canvas {
border: 1px solid #000;
}
JavaScript
canvas = document.querySelector('#canvas');
let c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
let mouse = {
x: innerWidth / 2,
y: innerHeight / 2
}
let colors = [
'#2185c5',
'#7ECEFD',
'#FFF6E5',
'#FF7F66'
];
document.addEventListener("mousemove", function(event){
mouse.x = event.clientX;
mouse.y = event.clientY;
});
addEventListener("resize", function(){
//console.log()
canvas.width = innerWidth;
canvas.height = innerHeight;
// init();
});
function randomIntFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomColor (color){
return color[Math.floor(Math.random() * color.length)];
}
function getDistance(x1, y1, x2, y2) { // расчёт дистанции до центра кругов
let xDistance = x2 -x1;
let yDistance = y2 -y1;
let distance = Math.pow(xDistance, 2) + Math.pow(yDistance, 2); // Теорема Пифагора
return Math.sqrt(distance); // квадратный корень числа
}
addEventListener("click", function () {
init();
})
function rotate(velocity, angle) { // !*
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
function resolveCollision(particle, otherParticle) { // !*
const xVelocityDiff = particle.velocity.x - otherParticle.velocity.x;
const yVelocityDiff = particle.velocity.y - otherParticle.velocity.y;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
// Предотвращение случайного наложения частиц
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
// Угол захвата между двумя сталкивающимися частицами
const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
// Сохраняем массу в переменную для лучшей читаемости в уравнении...