Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rudimentary mouse click repel/attract #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/Universe.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class Universe {
this.friction = 0;
this.flatForce = false;
this.wrap = false;

this.mouseForce = {x: null, y: null, forceLevel: null};
}

reSeed(
Expand Down Expand Up @@ -117,7 +119,16 @@ class Universe {
for (let i = 0; i < this.particles.length; ++i) {
// Current particle
const p = this.particles[i];

if (this.mouseForce.x !== null && this.mouseForce.y !== null) {
const repelRadius = 40;
const r_x = p.x - this.mouseForce.x;
const r_y = p.y - this.mouseForce.y;

if (Math.sqrt(Math.pow(r_x,2) + Math.pow(r_y, 2)) < repelRadius) {
p.vx += this.mouseForce.forceLevel / r_x;
p.vy += this.mouseForce.forceLevel / r_y;
}
}
// Interactions
for (let j = 0; j < this.particles.length; ++j) {
// Other particle
Expand Down Expand Up @@ -310,6 +321,30 @@ class Universe {
console.log('');
}
}

startRepelling(x, y) {
this.mouseForce.x = x;
this.mouseForce.y = y;
this.mouseForce.forceLevel = 5;
}

startAttracting(x, y) {
this.mouseForce.x = x;
this.mouseForce.y = y;
this.mouseForce.forceLevel = -1;
}

stopRepelling() {
this.mouseForce.x = null;
this.mouseForce.y = null;
this.mouseForce.forceLevel = null;
}

stopAttracting() {
this.mouseForce.x = null;
this.mouseForce.y = null;
this.mouseForce.forceLevel = null;
}
}

module.exports = Universe;
19 changes: 19 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,25 @@ const sketch = ({ width, height }) => {
width,
height
);

document.oncontextmenu = function(e){
return false;
}

window.addEventListener('mousedown', event => {
event.preventDefault();
if (event.which === 1) universe.startRepelling(event.pageX, event.pageY);
if (event.which === 3) universe.startAttracting(event.pageX, event.pageY);
});

window.addEventListener('mouseup', event => {
event.preventDefault();
if (event.which === 1) universe.stopRepelling();
if (event.which === 3) universe.stopAttracting();

});


universe.wrap = universeSettings.wrap;
universe.reSeed(
universeSettings.attractMean,
Expand Down