371 lines
12 KiB
TypeScript
371 lines
12 KiB
TypeScript
// Shimeji.ts
|
|
export class Shimeji {
|
|
private element: HTMLElement;
|
|
|
|
// Position and velocity
|
|
private x: number = 0;
|
|
private y: number = 0;
|
|
private velocityX: number = 0;
|
|
private velocityY: number = 0;
|
|
|
|
// Mouse tracking
|
|
private mouseX: number = 0;
|
|
private mouseY: number = 0;
|
|
private mouseAccelX: number = 0;
|
|
private mouseAccelY: number = 0;
|
|
|
|
// Throw detection - track mouse movement history
|
|
private mouseHistory: Array<{x: number, y: number, time: number}> = [];
|
|
private readonly HISTORY_LENGTH: number = 5;
|
|
|
|
private isBeingDragged: boolean = false;
|
|
|
|
private rafId: number | null = null;
|
|
|
|
// Physics parameters
|
|
private readonly STIFFNESS: number = 0.85;
|
|
private readonly DAMPING: number = 0.6;
|
|
private readonly MASS: number = 1.0;
|
|
|
|
// Gravity (pixels per frame squared)
|
|
private gravity: number = 10;
|
|
|
|
// Bounce coefficients (energy retention - lower = less bounce)
|
|
private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy
|
|
private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic)
|
|
private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy
|
|
|
|
// Minimum velocity to continue bouncing
|
|
private readonly MIN_BOUNCE_VELOCITY: number = 2;
|
|
|
|
// Boundaries
|
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
|
|
|
// Optional forces
|
|
private wind: number = 0;
|
|
private friction: number = 0.98;
|
|
|
|
// Track if on ground for additional effects
|
|
private wasOnGround: boolean = false;
|
|
private bounceCount: number = 0;
|
|
|
|
constructor(element: HTMLElement) {
|
|
this.element = element;
|
|
|
|
// Initialize bounds (will update on resize)
|
|
this.bounds = {
|
|
minX: 0,
|
|
minY: 0,
|
|
maxX: window.innerWidth,
|
|
maxY: window.innerHeight
|
|
};
|
|
|
|
// Start with element at center
|
|
this.x = window.innerWidth / 2;
|
|
this.y = window.innerHeight / 2;
|
|
|
|
this.updateBounds();
|
|
window.addEventListener('resize', () => this.updateBounds());
|
|
|
|
this.setupDragEvents();
|
|
}
|
|
|
|
private updateBounds(): void {
|
|
this.bounds = {
|
|
minX: 0,
|
|
minY: 0,
|
|
maxX: window.innerWidth,
|
|
maxY: window.innerHeight
|
|
};
|
|
}
|
|
|
|
start(): void {
|
|
if (this.rafId !== null) return;
|
|
|
|
const animate = () => {
|
|
this.updatePhysics();
|
|
this.applyBoundaries();
|
|
this.render();
|
|
this.rafId = requestAnimationFrame(animate);
|
|
};
|
|
|
|
this.rafId = requestAnimationFrame(animate);
|
|
}
|
|
|
|
stop(): void {
|
|
if (this.rafId !== null) {
|
|
cancelAnimationFrame(this.rafId);
|
|
this.rafId = null;
|
|
}
|
|
}
|
|
|
|
private setupDragEvents(): void {
|
|
this.element.addEventListener('mousedown', (e) => {
|
|
e.preventDefault();
|
|
this.isBeingDragged = true;
|
|
this.element.style.cursor = 'grabbing';
|
|
|
|
// Clear mouse history on new drag
|
|
this.mouseHistory = [];
|
|
});
|
|
|
|
// Track mouse movement globally for better throw detection
|
|
document.addEventListener('mousemove', (e) => {
|
|
if (this.isBeingDragged) {
|
|
this.mouseX = e.pageX;
|
|
this.mouseY = e.pageY;
|
|
this.mouseAccelX = e.movementX;
|
|
this.mouseAccelY = e.movementY;
|
|
|
|
// Store mouse position history for throw calculation
|
|
this.mouseHistory.push({
|
|
x: e.pageX,
|
|
y: e.pageY,
|
|
time: Date.now()
|
|
});
|
|
|
|
// Keep only recent history
|
|
if (this.mouseHistory.length > this.HISTORY_LENGTH) {
|
|
this.mouseHistory.shift();
|
|
}
|
|
}
|
|
});
|
|
|
|
this.element.addEventListener('mouseup', (e) => {
|
|
if(this.isBeingDragged) {
|
|
this.isBeingDragged = false;
|
|
this.element.style.cursor = 'grab';
|
|
|
|
// Calculate throw velocity based on mouse movement speed
|
|
this.applyThrowVelocity();
|
|
|
|
// Reset mouse history
|
|
this.mouseHistory = [];
|
|
}
|
|
});
|
|
|
|
this.element.addEventListener('dragstart', (e) => {
|
|
e.preventDefault();
|
|
});
|
|
}
|
|
|
|
private applyThrowVelocity(): void {
|
|
if (this.mouseHistory.length < 2) return;
|
|
|
|
// Get oldest and newest mouse positions
|
|
const oldest = this.mouseHistory[0];
|
|
const newest = this.mouseHistory[this.mouseHistory.length - 1];
|
|
|
|
// Calculate time delta in seconds
|
|
const timeDelta = (newest.time - oldest.time) / 1000;
|
|
if (timeDelta === 0) return;
|
|
|
|
// Calculate velocity in pixels per second
|
|
let throwVelX = (newest.x - oldest.x) / timeDelta;
|
|
let throwVelY = (newest.y - oldest.y) / timeDelta;
|
|
|
|
// Cap maximum throw velocity to prevent ridiculous speeds
|
|
const MAX_THROW_SPEED = 50;
|
|
throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
|
throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
|
|
|
// Apply throw velocity (divide by ~60 to convert from per-second to per-frame)
|
|
this.velocityX += throwVelX / 60;
|
|
this.velocityY += throwVelY / 60;
|
|
|
|
// Add a little extra oomph based on acceleration
|
|
if (Math.abs(this.mouseAccelX) > 5) {
|
|
this.velocityX += this.mouseAccelX / 30;
|
|
}
|
|
if (Math.abs(this.mouseAccelY) > 5) {
|
|
this.velocityY += this.mouseAccelY / 30;
|
|
}
|
|
}
|
|
|
|
private updatePhysics(): void {
|
|
// Apply spring force toward mouse when dragging
|
|
if (this.isBeingDragged) {
|
|
const dx = this.mouseX - this.x;
|
|
const dy = this.mouseY - this.y;
|
|
|
|
const forceX = dx * this.STIFFNESS;
|
|
const forceY = dy * this.STIFFNESS;
|
|
|
|
// Apply force to acceleration (F = ma)
|
|
const accelerationX = (forceX + this.mouseAccelX) / this.MASS;
|
|
const accelerationY = (forceY + this.mouseAccelY) / this.MASS;
|
|
|
|
// Update velocity with acceleration
|
|
this.velocityX += accelerationX;
|
|
this.velocityY += accelerationY;
|
|
}
|
|
|
|
// Apply gravity (always present, but stronger when not dragging)
|
|
if(!this.isBeingDragged) {
|
|
this.velocityY += this.gravity;
|
|
} else {
|
|
// Slight gravity even when dragging for realism
|
|
this.velocityY += this.gravity * 0.3;
|
|
}
|
|
|
|
// Apply wind (optional horizontal force)
|
|
if(this.y > 10) this.velocityX += this.wind;
|
|
|
|
// Apply damping (air resistance)
|
|
this.velocityX *= this.DAMPING;
|
|
this.velocityY *= this.DAMPING;
|
|
|
|
// Update position with velocity
|
|
this.x += this.velocityX;
|
|
this.y += this.velocityY;
|
|
}
|
|
|
|
private getElementHeight(): number {
|
|
return this.element.offsetHeight;
|
|
}
|
|
|
|
private getElementWidth(): number {
|
|
return this.element.offsetWidth;
|
|
}
|
|
|
|
private applyBoundaries(): void {
|
|
const elementWidth = this.getElementWidth();
|
|
const elementHeight = this.getElementHeight();
|
|
|
|
// X-axis boundaries with realistic bounce
|
|
const leftBound = elementWidth / 2;
|
|
const rightBound = this.bounds.maxX - elementWidth / 2;
|
|
|
|
if (this.x < leftBound) {
|
|
this.x = leftBound;
|
|
// Bounce with energy loss
|
|
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
|
|
|
// Stop if bounce is too small
|
|
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
|
this.velocityX = 0;
|
|
}
|
|
} else if (this.x > rightBound) {
|
|
this.x = rightBound;
|
|
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
|
|
|
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
|
this.velocityX = 0;
|
|
}
|
|
}
|
|
|
|
// Y-axis boundaries with realistic bounce
|
|
const topBound = elementHeight / 2;
|
|
const bottomBound = this.bounds.maxY - elementHeight / 2;
|
|
|
|
// Ceiling collision
|
|
if (this.y < topBound) {
|
|
this.y = topBound;
|
|
this.velocityY = -this.velocityY * this.CEILING_BOUNCE;
|
|
|
|
// Stop tiny bouncing on ceiling
|
|
if (Math.abs(this.velocityY) < this.MIN_BOUNCE_VELOCITY) {
|
|
this.velocityY = 0;
|
|
}
|
|
}
|
|
// Floor collision
|
|
else if (this.y > bottomBound) {
|
|
this.y = bottomBound;
|
|
|
|
const impactSpeed = Math.abs(this.velocityY);
|
|
|
|
// Only bounce if impact speed is significant
|
|
if (impactSpeed > this.MIN_BOUNCE_VELOCITY) {
|
|
// Apply floor bounce with energy loss
|
|
this.velocityY = -this.velocityY * this.FLOOR_BOUNCE;
|
|
|
|
// Bounce gets smaller each time naturally due to energy loss
|
|
this.bounceCount++;
|
|
|
|
// Apply ground friction on bounce
|
|
this.velocityX *= this.groundFriction;
|
|
|
|
// Optional: Visual feedback for bounce
|
|
// console.log(`Bounce ${this.bounceCount}: impact speed ${impactSpeed.toFixed(2)}, new velocity ${this.velocityY.toFixed(2)}`);
|
|
} else {
|
|
// Stop bouncing when energy is too low
|
|
this.velocityY = 0;
|
|
this.wasOnGround = true;
|
|
}
|
|
} else {
|
|
this.wasOnGround = false;
|
|
// Reset bounce count when in air
|
|
if (!this.isBeingDragged && this.velocityY !== 0) {
|
|
this.bounceCount = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
private get groundFriction(): number {
|
|
// More friction when moving fast
|
|
const speed = Math.abs(this.velocityX);
|
|
if (speed > 10) return this.friction * 0.9;
|
|
if (speed > 5) return this.friction * 0.95;
|
|
return this.friction;
|
|
}
|
|
|
|
private render(): void {
|
|
this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`;
|
|
}
|
|
|
|
// Public methods to control physics
|
|
setGravity(value: number): void {
|
|
this.gravity = value;
|
|
}
|
|
|
|
setWind(value: number): void {
|
|
this.wind = value;
|
|
}
|
|
|
|
setPhysics(stiffness: number, damping: number, mass: number = 1.0): void {
|
|
(this as any).STIFFNESS = stiffness;
|
|
(this as any).DAMPING = damping;
|
|
(this as any).MASS = mass;
|
|
}
|
|
|
|
setFriction(value: number): void {
|
|
this.friction = value;
|
|
}
|
|
|
|
// Configure bounce properties
|
|
setBounceProperties(wall: number, floor: number, ceiling: number = 0.4): void {
|
|
(this as any).WALL_BOUNCE = Math.min(Math.max(wall, 0), 1);
|
|
(this as any).FLOOR_BOUNCE = Math.min(Math.max(floor, 0), 1);
|
|
(this as any).CEILING_BOUNCE = Math.min(Math.max(ceiling, 0), 1);
|
|
}
|
|
|
|
// Add impulse (like a jump)
|
|
addImpulse(x: number, y: number): void {
|
|
this.velocityX += x;
|
|
this.velocityY += y;
|
|
}
|
|
|
|
// Reset position
|
|
resetPosition(x?: number, y?: number): void {
|
|
this.x = x ?? this.bounds.maxX / 2;
|
|
this.y = y ?? this.bounds.maxY / 2;
|
|
this.velocityX = 0;
|
|
this.velocityY = 0;
|
|
this.isBeingDragged = false;
|
|
this.bounceCount = 0;
|
|
}
|
|
|
|
getState() {
|
|
return {
|
|
x: this.x,
|
|
y: this.y,
|
|
velocityX: this.velocityX,
|
|
velocityY: this.velocityY,
|
|
mouseX: this.mouseX,
|
|
mouseY: this.mouseY,
|
|
isBeingDragged: this.isBeingDragged,
|
|
isOnGround: this.wasOnGround,
|
|
bounceCount: this.bounceCount
|
|
};
|
|
}
|
|
} |