This commit is contained in:
nora 2021-06-17 10:09:19 +02:00
parent 735522fff8
commit 1888dca4e8
15 changed files with 236 additions and 76 deletions

View file

@ -0,0 +1,73 @@
import Vector from "./Vector";
import SimObject from "./Drawable";
import {Ctx, FillStyle} from "../MainDraw";
import {circle} from "../Shapes";
import {CANVAS_HEIGHT, CANVAS_WIDTH} from "../../App";
const PARTICLE_SIZE = 5;
const PARTICLE_EDGE_REPULSION_FORCE = 0.1;
const FRICTION = 0.99;
const RANDOM_ACCELERATION = 2;
export default class Particle implements SimObject {
private _position: Vector;
private _velocity: Vector;
// private _color: FillStyle;
private _charge: number;
constructor(position: Vector, /*color = "black", */charge = 0) {
this._position = position;
this._velocity = new Vector();
//this._color = color;
this._charge = charge;
}
public applyForce(force: Vector) {
this._velocity = this._velocity.add(force);
}
public draw(ctx: Ctx): void {
circle(ctx, this._position.x, this._position.y, PARTICLE_SIZE, colorFromCharge(this._charge));
}
public update(): void {
this._position = this._position.add(this._velocity);
this._velocity = this._velocity.scale(FRICTION);
// random movement
if (this._velocity.magnitude() < 0.1 && Math.random() > 0.4) {
this.applyForce(new Vector((Math.random() - 0.5) * RANDOM_ACCELERATION, (Math.random() - 0.5) * RANDOM_ACCELERATION));
}
if (this._position.x < 50) {
this.applyForce(new Vector(PARTICLE_EDGE_REPULSION_FORCE, 0));
}
if (this._position.x > CANVAS_WIDTH - 50) {
this.applyForce(new Vector(-PARTICLE_EDGE_REPULSION_FORCE, 0));
}
if (this._position.y > CANVAS_HEIGHT - 50) {
this.applyForce(new Vector(0, -PARTICLE_EDGE_REPULSION_FORCE));
}
if (this._position.y < 50) {
this.applyForce(new Vector(0, PARTICLE_EDGE_REPULSION_FORCE));
}
}
public get charge() {
return this._charge;
}
public get position() {
return this._position;
}
}
function colorFromCharge(charge: number): FillStyle {
if (charge === 0) {
return "black";
}
if (charge < 0) {
return "blue";
}
return "red";
}