Skip to content
Snippets Groups Projects
Verified Commit 476d9090 authored by TheJoeCoder's avatar TheJoeCoder
Browse files

Use mouse's velocity to calculate dot collisions

parent 80ed241a
No related branches found
No related tags found
No related merge requests found
......@@ -127,7 +127,9 @@ const setDisplayParameters = () => {
setDisplayParameters();
let dots = [];
let prevMousePos = [0, 0];
let mousePos = [0, 0];
let mouseVel = [0, 0];
for (let i = 0; i < DOTS_NUM; i++) {
// Append new dot to the array with a random position, radius, and velocity
......@@ -191,15 +193,25 @@ const drawConnectingLines = () => {
};
const drawDebugText = () => {
// Dots
for(let dot of dots) {
let vx = Math.round((dot.vx + Number.EPSILON) * 100) / 100
let vy = Math.round((dot.vy + Number.EPSILON) * 100) / 100
let vx = Math.round((dot.vx + Number.EPSILON) * 100) / 100;
let vy = Math.round((dot.vy + Number.EPSILON) * 100) / 100;
ctx.beginPath();
ctx.font = "15px Arial";
ctx.fillStyle = "#fff";
ctx.fillText(`${vx}/${vy}`,dot.x,dot.y);
ctx.closePath();
}
// Mouse
let vx = Math.round((mouseVel[0] + Number.EPSILON) * 100) / 100;
let vy = Math.round((mouseVel[1] + Number.EPSILON) * 100) / 100;
ctx.beginPath();
ctx.font = "15px Arial";
ctx.fillStyle = "#fff";
ctx.fillText(`${vx}/${vy}`,mousePos[0], mousePos[1]);
ctx.closePath();
};
const draw = () => {
......@@ -274,8 +286,18 @@ const physics = () => {
let cx = ax + (r * ((bx - ax) / Math.sqrt((bx - ax)**2 + (by - ay)**2)));
let cy = ay + (r * ((by - ay) / Math.sqrt((bx - ax)**2 + (by - ay)**2)));
/*
dot.vx = -dot.vx;
dot.vy = -dot.vy;
*/
let dotNormVx = Math.abs(dot.vx);
let dotNormVy = Math.abs(dot.vy);
let mouseNormVx = Math.abs(mouseVel[0]);
let mouseNormVy = Math.abs(mouseVel[1]);
// Set velocity based on mouse velocity
dot.vx = dot.x >= mousePos[0] ? dotNormVx + mouseNormVx : -dotNormVx - mouseNormVx;
dot.vy = dot.y >= mousePos[1] ? dotNormVy + mouseNormVy : -dotNormVy - mouseNormVy;
dot.vx *= VELOCITY_PUSH_MULTIPLIER;
dot.vy *= VELOCITY_PUSH_MULTIPLIER;
......@@ -310,6 +332,14 @@ window.addEventListener("mousemove", (event) => {
// Scale clientX and clientY in case the screen size has changed
mousePos[0] = (canvas.width / window.innerWidth) * event.clientX;
mousePos[1] = (canvas.height / window.innerHeight) * event.clientY;
// Work out velocity
mouseVel[0] = mousePos[0] - prevMousePos[0];
mouseVel[1] = mousePos[1] - prevMousePos[1];
// Set previous mouse pos
prevMousePos[0] = mousePos[0];
prevMousePos[1] = mousePos[1];
});
window.addEventListener("resize", () => {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment