diff --git a/src/lib/shimeji/physics2d/primitives/aabb.ts b/src/lib/shimeji/physics2d/primitives/aabb.ts new file mode 100644 index 0000000..0ffe0dd --- /dev/null +++ b/src/lib/shimeji/physics2d/primitives/aabb.ts @@ -0,0 +1,24 @@ +import Vector2 from "$lib/stores/vector"; +import Rigidbody2D from "../rigidbody/rigidbody2d"; + +class AABB { + private size: Vector2 = new Vector2(); + private halfSize: Vector2 = new Vector2(); + private rigidbody: Rigidbody2D | null = null; + + constructor(); + constructor(min?: Vector2, max?: Vector2) { + if(min !== undefined && max !== undefined) + this.size = new Vector2(max).sub(min); + + this.halfSize = new Vector2(this.size.mul(0.5)); + } + + public get getMin(): Vector2 { + return new Vector2(this.rigidbody.getPosition).sub(this.halfSize); + } + + public get getMax(): Vector2 { + return new Vector2(this.rigidbody.getPosition).add(this.halfSize); + } +} \ No newline at end of file diff --git a/src/lib/shimeji/physics2d/primitives/box2d.ts b/src/lib/shimeji/physics2d/primitives/box2d.ts new file mode 100644 index 0000000..6cceee5 --- /dev/null +++ b/src/lib/shimeji/physics2d/primitives/box2d.ts @@ -0,0 +1,20 @@ +import Vector2 from "$lib/stores/vector" +import type Rigidbody2D from "../rigidbody/rigidbody2d"; + +class Box2D { + private size: Vector2 = new Vector2(); + private halfSize: Vector2 = new Vector2(); + private rigidbody: Rigidbody2D | null = null; + + constructor(); + constructor(min?: Vector2, max?: Vector2) { + if(min !== undefined && max !== undefined) + this.size = new Vector2(max).sub(min); + + this.halfSize = new Vector2(this.size.mul(0.5)); + } + + public get getMin(): Vector2 { + + } +} \ No newline at end of file diff --git a/src/lib/shimeji/physics2d/primitives/collider2d.ts b/src/lib/shimeji/physics2d/primitives/collider2d.ts new file mode 100644 index 0000000..4f06243 --- /dev/null +++ b/src/lib/shimeji/physics2d/primitives/collider2d.ts @@ -0,0 +1,9 @@ +import Vector2 from "$lib/stores/vector"; + +class Collider2D { + protected offset: Vector2 = new Vector2(); + + //public abstract getInnertiaTensor(mass: number): number; + + +} \ No newline at end of file diff --git a/src/lib/shimeji/physics2d/rigidbody/rigidbody2d.ts b/src/lib/shimeji/physics2d/rigidbody/rigidbody2d.ts new file mode 100644 index 0000000..6362b01 --- /dev/null +++ b/src/lib/shimeji/physics2d/rigidbody/rigidbody2d.ts @@ -0,0 +1,25 @@ +import Vector2 from "$lib/stores/vector"; + +class Rigidbody2D { + private position: Vector2 = new Vector2(); + private rotation: number = 0.0; + + public get getPosition(): Vector2 { + return this.position; + } + + public set setPosition(position: Vector2) { + this.position = position; + } + + public get getRotation(): number { + return this.rotation; + } + + public set setRotation(rotation: number) { + this.rotation = rotation + } + +} + +export default Rigidbody2D; \ No newline at end of file diff --git a/src/lib/stores/shimeji.ts b/src/lib/stores/shimeji.ts index bd2bb15..b1d7690 100644 --- a/src/lib/stores/shimeji.ts +++ b/src/lib/stores/shimeji.ts @@ -1,42 +1,37 @@ +import Vector2 from "./vector"; + export class Shimeji { private element: HTMLElement; + private canvas: HTMLCanvasElement; + private rect: DOMRect; - private x: number; - private y: number; - 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; + private pos: Vector2 = Vector2.zero; + private vel: Vector2 = Vector2.zero; + + private mousePos: Vector2 = Vector2.zero; + + private pivot: Vector2 = Vector2.zero; private isBeingDragged: boolean = false; private rafId: number | null = null; private prevDeltaTime: number = 0; - // Physics parameters - private readonly RESTITUTION: number = 0.6; // 1 perfect bounciness 0 no bounce - private readonly STIFFNESS: number = 100; // Spring constant - private readonly DAMPING: number = 1; // Air resistance 1 - no resistance 0.1 high air density - private readonly MASS: number = 10.0; // Mass + private readonly TIMESCALE: number = 1; + private readonly RESTITUTION: number = 0.4; + private readonly CURSOR_STRENGTH: number = 250; + private readonly DAMPING: number = 1; + private readonly MASS: number = 0.1; + private readonly FRICTION: number = 0.9; + private readonly GRAVITY: number = 50; - // Gravity (pixels per frame squared) - private gravity: number = 10; - - // Boundaries private bounds: { minX: number; minY: number; maxX: number; maxY: number }; - // Optional forces - private wind: number = 0; - private friction: number = 0.8; - - constructor(element: HTMLElement) { + constructor(element: HTMLElement, canvas: HTMLCanvasElement) { this.element = element; + this.canvas= canvas; + this.rect = element.getBoundingClientRect(); - // Initialize bounds (will update on resize) this.bounds = { minX: 0, minY: 0, @@ -44,9 +39,7 @@ export class Shimeji { maxY: window.innerHeight }; - // Start with element at center - this.x = window.innerWidth / 2; - this.y = window.innerHeight / 2; + this.pos.set(window.innerWidth / 2, window.innerHeight/ 2); this.updateBounds(); window.addEventListener('resize', () => this.updateBounds()); @@ -63,6 +56,9 @@ export class Shimeji { maxX: window.innerWidth, maxY: window.innerHeight }; + + this.canvas.width = window.innerWidth; + this.canvas.height = window.innerHeight; } start(): void { @@ -74,7 +70,8 @@ export class Shimeji { } const animate = (delta: number) => { - const dt: number = Math.min(delta - this.prevDeltaTime, 0.05); + let dt = (delta - this.prevDeltaTime) / 1000; // seconds + dt = Math.min(dt, 0.05 * this.TIMESCALE); // cap to 50 ms this.prevDeltaTime = delta; this.updatePhysics(dt); @@ -98,25 +95,18 @@ export class Shimeji { e.preventDefault(); this.isBeingDragged = true; this.element.style.cursor = 'grabbing'; + const parent = this.element.parentElement; - if(parent) parent.style.cursor = 'grabbing'; - - const rect = this.element.getBoundingClientRect(); - const x = e.clientX - rect.left; - const y = e.clientY - rect.top; - - const pivotX = (x / rect.width) * 100; - const pivotY = (y / rect.height) * 100; - - this.element.style.transformOrigin = `${pivotX}% ${pivotY}%`; + if(parent) parent.style.cursor = 'grabbing'; + this.pivot.x = e.offsetX - this.rect.width / 2; + this.pivot.y = e.offsetY - this.rect.height / 2; + }); document.addEventListener('mousemove', (e) => { - this.mouseX = e.pageX; - this.mouseY = e.pageY; - this.mouseAccelX = e.movementX * 0.1; - this.mouseAccelY = e.movementY * 0.1; + this.mousePos.x = e.pageX; + this.mousePos.y = e.pageY; }); document.addEventListener('mouseup', (e) => { @@ -126,7 +116,11 @@ export class Shimeji { const parent = this.element.parentElement; if(parent) parent.style.cursor = 'auto'; + + this.pivot = Vector2.zero; } + + this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height); }); this.element.addEventListener('dragstart', (e) => { @@ -136,135 +130,78 @@ export class Shimeji { private updatePhysics(dt: number): void { if (this.isBeingDragged) { - console.log(this.element.style.transformOrigin); - - // Spring force toward mouse - const dx = this.mouseX - this.x; - const dy = this.mouseY - this.y; + const direction: Vector2 = this.mousePos.sub(this.pivot).sub(this.pos); - const forceX = dx * this.STIFFNESS; - const forceY = dy * this.STIFFNESS; + const force: Vector2 = direction.mul(this.CURSOR_STRENGTH); + + const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001); - // Apply force to acceleration (F = ma) - const accelerationX = Math.abs(forceX / this.MASS) < 0.0001 ? 0 : (forceX / this.MASS); - const accelerationY = Math.abs(forceY / this.MASS) < 0.0001 ? 0 : (forceY / this.MASS); + acceleration.mulEq(dt); - - console.log(accelerationX, accelerationY); - - // Update velocity with acceleration - this.velocityX += accelerationX * dt; - this.velocityY += accelerationY * dt; - - this.velocityX *= 0.8; - this.velocityY *= 0.8; + this.vel.addEq(acceleration); + this.vel.mulEq(0.8); } - // Apply gravity (always present) - this.velocityY += this.gravity; - - this.velocityX *= this.DAMPING; - this.velocityY *= this.DAMPING; + this.vel.y += this.GRAVITY; + this.vel.mulEq(this.DAMPING); - // Apply additional friction when on ground (touching bottom) - if (this.y + this.getElementHeight() >= this.bounds.maxY) { - this.velocityX *= this.friction; + if (this.pos.y + this.rect.width >= this.bounds.maxY) { + this.vel.x *= this.FRICTION; } - - - // Update position with velocity - this.x = this.x + this.velocityX * dt; - this.y = this.y + this.velocityY * dt; - } - - private getElementHeight(): number { - return this.element.offsetHeight; - } - - private getElementWidth(): number { - return this.element.offsetWidth; + const outVel = this.vel.mul(dt); + this.pos.addEq(outVel); } private applyBoundaries(): void { - const elementWidth = this.getElementWidth(); - const elementHeight = this.getElementHeight(); + const leftBound = this.rect.width / 2; + const rightBound = this.bounds.maxX - this.rect.width / 2; - // X-axis boundaries (account for element width with center positioning) - const leftBound = elementWidth / 2; - const rightBound = this.bounds.maxX - elementWidth / 2; - - if (this.x < leftBound) { - this.x = leftBound; - this.velocityX = -(this.RESTITUTION) * this.velocityX; - } else if (this.x > rightBound) { - this.x = rightBound; - this.velocityX = -(this.RESTITUTION) * this.velocityX; + if (this.pos.x < leftBound) { + this.pos.x = leftBound; + this.vel.x = -(this.RESTITUTION) * this.vel.x; + } else if (this.pos.x > rightBound) { + this.pos.x = rightBound; + this.vel.x = -(this.RESTITUTION) * this.vel.x; } - // Y-axis boundaries - const topBound = elementHeight / 2; - const bottomBound = this.bounds.maxY - elementHeight / 2; + const topBound = this.rect.height / 2; + const bottomBound = this.bounds.maxY - this.rect.height / 2; - if (this.y < topBound) { - this.y = topBound; - this.velocityY = -(this.RESTITUTION) * this.velocityY; - } else if (this.y > bottomBound) { - this.y = bottomBound; - this.velocityY = -(this.RESTITUTION) * this.velocityY; - - if (Math.abs(this.velocityY) < 0.3) { - this.velocityY = 0; - } + if (this.pos.y < topBound) { + this.pos.y = topBound; + this.vel.y = -(this.RESTITUTION) * this.vel.y; + } else if (this.pos.y > bottomBound) { + this.pos.y = bottomBound; + this.vel.y = -(this.RESTITUTION) * this.vel.y; } } + + private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) { + const ctx = this.canvas.getContext("2d")!; + ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + ctx.strokeStyle = "white"; + ctx.lineWidth = 0.1 + ctx.beginPath(); + ctx.moveTo(pos1.x, pos1.y); + ctx.lineTo(pos2.x, pos2.y); + ctx.stroke(); + } private render(): void { - this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`; + this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px)`; + + /* if(this.isBeingDragged) { + this.drawRay( + {x: this.mouseX, y: this.mouseY}, + {x: this.x + this.pivotX, y: this.y + this.pivotY} + ) + } */ } - // 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; - } - - // 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; - } - - getState() { - return { - x: this.x, - y: this.y, - velocityX: this.velocityX, - velocityY: this.velocityY, - mouseX: this.mouseX, - mouseY: this.mouseY - }; + this.vel.x += x; + this.vel.y += y; } moveTo(pos: number) { diff --git a/src/lib/stores/shimeji2.ts b/src/lib/stores/shimeji2.ts index bd95a5d..981a96e 100644 --- a/src/lib/stores/shimeji2.ts +++ b/src/lib/stores/shimeji2.ts @@ -1,71 +1,58 @@ -// Shimeji.ts +import Vector2 from "./vector"; + export class Shimeji { private element: HTMLElement; + private canvas: HTMLCanvasElement; + private rect: DOMRect; - // 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 pos: Vector2 = Vector2.zero; + private vel: Vector2 = Vector2.zero; + + private angle: number = 0; // radians + private angularVelocity: number = 0; // rad/s + private inertia: number; // kg·m² + private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed) + + private mousePos: Vector2 = Vector2.zero; + + private pivot: Vector2 = Vector2.zero; + private isBeingDragged: boolean = false; private rafId: number | null = null; + private prevDeltaTime: number = 0; + + + private readonly RESTITUTION: number = 0.6; + private readonly STIFFNESS: number = 500; + private readonly DAMPING: number = 1; + private readonly MASS: number = 10.0; + private readonly FRICTION: number = 0.9; + private readonly GRAVITY: number = 10; - // 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) { + constructor(element: HTMLElement, canvas: HTMLCanvasElement) { this.element = element; + this.canvas= canvas; + this.rect = element.getBoundingClientRect(); - // Initialize bounds (will update on resize) this.bounds = { minX: 0, minY: 0, maxX: window.innerWidth, maxY: window.innerHeight }; + + this.inertia = (1 / 12) * + this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height); - // Start with element at center - this.x = window.innerWidth / 2; - this.y = window.innerHeight / 2; + this.pos.set(window.innerWidth / 2, window.innerHeight/ 2); this.updateBounds(); window.addEventListener('resize', () => this.updateBounds()); + + console.log(this.element.getBoundingClientRect()); this.setupDragEvents(); } @@ -77,19 +64,30 @@ export class Shimeji { maxX: window.innerWidth, maxY: window.innerHeight }; + + this.canvas.width = window.innerWidth; + this.canvas.height = window.innerHeight; } start(): void { if (this.rafId !== null) return; - - const animate = () => { - this.updatePhysics(); + + const firstFrame = (delta: number) => { + this.prevDeltaTime = delta; + this.rafId = requestAnimationFrame(animate); + } + + const animate = (delta: number) => { + const dt: number = Math.min(delta - this.prevDeltaTime, 0.05); + this.prevDeltaTime = delta; + + this.updatePhysics(dt); this.applyBoundaries(); this.render(); this.rafId = requestAnimationFrame(animate); }; - this.rafId = requestAnimationFrame(animate); + this.rafId = requestAnimationFrame(firstFrame); } stop(): void { @@ -99,49 +97,58 @@ export class Shimeji { } } + private getCornerWorld(lx: number, ly: number): Vector2 { + // lx, ly are in local coordinates (relative to center, with rotation) + const cos = Math.cos(this.angle); + const sin = Math.sin(this.angle); + return new Vector2( + this.pos.x + (lx * cos - ly * sin), + this.pos.y + (lx * sin + ly * cos) + ); + } + private setupDragEvents(): void { this.element.addEventListener('mousedown', (e) => { e.preventDefault(); this.isBeingDragged = true; this.element.style.cursor = 'grabbing'; + + const parent = this.element.parentElement; + if(parent) parent.style.cursor = 'grabbing'; + + const clickWorld = new Vector2(e.pageX, e.pageY); + const center = this.pos; + const offset = clickWorld.sub(center) + const cos = Math.cos(-this.angle); + const sin = Math.sin(-this.angle); + + this.localGrip = new Vector2( + offset.x * cos - offset.y * sin, + offset.x * sin + offset.y * cos + ); + + this.pivot.x = e.offsetX - this.rect.width / 2; + this.pivot.y = e.offsetY - this.rect.height / 2; - // 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.mousePos.x = e.pageX; + this.mousePos.y = e.pageY; }); - this.element.addEventListener('mouseup', (e) => { + document.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 = []; + + const parent = this.element.parentElement; + if(parent) parent.style.cursor = 'auto'; + + this.pivot = Vector2.zero; } + + this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height); }); this.element.addEventListener('dragstart', (e) => { @@ -149,223 +156,181 @@ export class Shimeji { }); } - 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 + private updatePhysics(dt: number): void { + + const cos = Math.cos(this.angle); + const sin = Math.sin(this.angle); + const gripWorld = new Vector2( + this.pos.x + (this.localGrip.x * cos - this.localGrip.y * sin), + this.pos.y + (this.localGrip.x * sin + this.localGrip.y * cos) + ); + if (this.isBeingDragged) { - const dx = this.mouseX - this.x; - const dy = this.mouseY - this.y; + const direction: Vector2 = this.mousePos.sub(gripWorld); - const forceX = dx * this.STIFFNESS; - const forceY = dy * this.STIFFNESS; + const force: Vector2 = direction.mul(this.STIFFNESS); + + const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001); - // 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; + acceleration.mulEq(dt); + + this.vel.addEq(acceleration); + this.vel.mulEq(0.8); + + const r = gripWorld.sub(this.pos); + const torque = r.cross(force); + this.angularVelocity += (torque / this.inertia) * dt; } - // 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; + this.vel.y += this.GRAVITY; + this.vel.mulEq(this.DAMPING); + + if (this.pos.y + this.rect.width >= this.bounds.maxY) { + this.vel.x *= this.FRICTION; } - - // 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; + + const outVel = this.vel.mul(dt); + this.pos.addEq(outVel); + + this.angle += this.angularVelocity * dt; + this.angle %= 2 * Math.PI; } 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; - } + const w = this.rect.width / 2; + const h = this.rect.height / 2; + + // List of corners in local coordinates (four combinations) + const corners = [ + { lx: w, ly: h }, // top‑right + { lx: w, ly: -h }, // bottom‑right + { lx: -w, ly: h }, // top‑left + { lx: -w, ly: -h } // bottom‑left + ]; + + // Check each wall + // Left wall (x = leftBound) + const leftBound = w; + for (const corner of corners) { + const world = this.getCornerWorld(corner.lx, corner.ly); + if (world.x < leftBound) { + // Penetration depth (distance from wall to corner) + const penetration = leftBound - world.x; + // Normal points to the right (+x) + const normal = new Vector2(1, 0); + // Contact point is the wall at corner's y (or clamp to avoid escaping) + const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h); + const contactPoint = new Vector2(leftBound, contactY); + this.resolveCollision(normal, contactPoint); + // Reposition to avoid continuous penetration + this.pos.x = leftBound - w; + return; // after one correction, stop checking further walls to avoid multiple impulses } } - - 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; + + // Right wall (x = rightBound) + const rightBound = this.bounds.maxX - w; + for (const corner of corners) { + const world = this.getCornerWorld(corner.lx, corner.ly); + if (world.x > rightBound) { + const penetration = world.x - rightBound; + const normal = new Vector2(-1, 0); + const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h); + const contactPoint = new Vector2(rightBound, contactY); + this.resolveCollision(normal, contactPoint); + this.pos.x = rightBound + w; + return; + } + } + + // Top wall (y = topBound) + const topBound = h; + for (const corner of corners) { + const world = this.getCornerWorld(corner.lx, corner.ly); + if (world.y < topBound) { + const penetration = topBound - world.y; + const normal = new Vector2(0, 1); + const contactX = Math.min(Math.max(world.x, leftBound), rightBound); + const contactPoint = new Vector2(contactX, topBound); + this.resolveCollision(normal, contactPoint); + this.pos.y = topBound - h; + return; + } + } + + // Bottom wall (y = bottomBound) + const bottomBound = this.bounds.maxY - h; + for (const corner of corners) { + const world = this.getCornerWorld(corner.lx, corner.ly); + if (world.y > bottomBound) { + const penetration = world.y - bottomBound; + const normal = new Vector2(0, -1); + const contactX = Math.min(Math.max(world.x, leftBound), rightBound); + const contactPoint = new Vector2(contactX, bottomBound); + this.resolveCollision(normal, contactPoint); + this.pos.y = bottomBound + h; + return; + } + } +} + + private resolveCollision(normal: Vector2, contactPoint: Vector2): void { + // Vector from center to contact point + const r = contactPoint.sub(this.pos); + + // Velocity of the contact point + const v_rel = this.vel.clone(); + // Add tangential component from angular velocity: ω × r + v_rel.x -= this.angularVelocity * r.y; + v_rel.y += this.angularVelocity * r.x; + + // Relative velocity along normal + const vn = v_rel.dot(normal); + if (vn > 0) return; // Already separating + + // Impulse numerator + const numerator = -(1 + this.RESTITUTION) * vn; + + // Denominator: 1/m + (r × n)^2 / I + const r_cross_n = r.cross(normal); + const denominator = 1 / this.MASS + (r_cross_n * r_cross_n) / this.inertia; + + const j = numerator / denominator; + const impulse = normal.mul(j); + + // Apply impulse + this.vel.addEq(impulse.div(this.MASS)); + this.angularVelocity += r.cross(impulse) / this.inertia; + } + + private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) { + const ctx = this.canvas.getContext("2d")!; + ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + ctx.strokeStyle = "white"; + ctx.lineWidth = 0.1 + ctx.beginPath(); + ctx.moveTo(pos1.x, pos1.y); + ctx.lineTo(pos2.x, pos2.y); + ctx.stroke(); } private render(): void { - this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`; + this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) rotate(${this.angle * 180 / Math.PI}deg)`; + + /* if(this.isBeingDragged) { + this.drawRay( + {x: this.mousePos.x, y: this.mousePos.y}, + {x: this.pos.x + this.pivot.x, y: this.pos.y + this.pivot.y} + ) + } */ } - // 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; + this.vel.x += x; + this.vel.y += 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 - }; + + moveTo(pos: number) { + } } \ No newline at end of file diff --git a/src/lib/stores/vector.ts b/src/lib/stores/vector.ts new file mode 100644 index 0000000..a67eef0 --- /dev/null +++ b/src/lib/stores/vector.ts @@ -0,0 +1,282 @@ +class Vector2 { + public x: number; + public y: number; + + constructor(x?: number, y?: number); + constructor(v?: Vector2); + constructor(x: Vector2 | number = 0, y: number = 0) { + if (typeof x === 'object' && x !== null) { + this.x = x.x; + this.y = x.y; + } + else { + this.x = x; + this.y = y; + } + } + + add(s: number): Vector2; + add(v: Vector2): Vector2; + add(arg: number | Vector2): Vector2 { + if (typeof arg === 'number') { + return new Vector2(this.x + arg, this.y + arg); + } + else { + return new Vector2(this.x + arg.x, this.y + arg.y); + } + } + + sub(s: number): Vector2; + sub(v: Vector2): Vector2; + sub(arg: number | Vector2): Vector2 { + if (typeof arg === 'number') { + return new Vector2(this.x - arg, this.y - arg); + } + else { + return new Vector2(this.x - arg.x, this.y - arg.y); + } + } + + mul(s: number): Vector2; + mul(v: Vector2): Vector2; + mul(arg: number | Vector2): Vector2 { + if (typeof arg === 'number') { + return new Vector2(this.x * arg, this.y * arg); + } + else { + return new Vector2(this.x * arg.x, this.y * arg.y); + } + } + + div(s: number): Vector2; + div(v: Vector2): Vector2; + div(arg: number | Vector2): Vector2 { + if (typeof arg === 'number') { + return new Vector2(this.x / arg, this.y / arg); + } + else { + return new Vector2(this.x / arg.x, this.y / arg.y); + } + } + + equals(v: Vector2, epsilon: number = 1e-10): boolean { + return Math.abs(this.x - v.x) < epsilon && Math.abs(this.y - v.y) < epsilon; + } + + get sqrLength(): number { + return this.x * this.x + this.y * this.y; + } + + get length(): number { + return Math.sqrt(this.sqrLength); + } + + get normalized(): Vector2 { + const len = this.length; + return len === 0 ? new Vector2(0, 0) : new Vector2(this.x / len, this.y / len); + } + + get angle(): number { + return Math.atan2(this.y, this.x); + } + + addEq(s: number): this; + addEq(v: Vector2): this; + addEq(arg: number | Vector2): this { + if (typeof arg === 'number') { + this.x += arg; + this.y += arg; + } + else { + this.x += arg.x; + this.y += arg.y; + } + return this; + } + + subEq(s: number): this; + subEq(v: Vector2): this; + subEq(arg: number | Vector2): this { + if (typeof arg === 'number') { + this.x -= arg; + this.y -= arg; + } + else { + this.x -= arg.x; + this.y -= arg.y; + } + return this; + } + + mulEq(s: number): this; + mulEq(v: Vector2): this; + mulEq(arg: number | Vector2): this { + if (typeof arg === 'number') { + this.x *= arg; + this.y *= arg; + } + else { + this.x *= arg.x; + this.y *= arg.y; + } + return this; + } + + divEq(s: number): this; + divEq(v: Vector2): this; + divEq(arg: number | Vector2): this { + if (typeof arg === 'number') { + this.x /= arg; + this.y /= arg; + } + else { + this.x /= arg.x; + this.y /= arg.y; + } + return this; + } + + cross(v: Vector2): number { + return this.x * v.y - this.y * v.x; + } + + dot(v: Vector2): number { + return this.x * v.x + this.y * v.y; + } + + set(x: number, y: number): this { + this.x = x; + this.y = y; + return this; + } + + normalize(): this { + const len = this.length; + if (len !== 0) { + this.x /= len; + this.y /= len; + } + return this; + } + + rotate(angle: number): Vector2 { + const cos = Math.cos(angle); + const sin = Math.sin(angle); + return new Vector2(this.x * cos - this.y * sin, this.x * sin + this.y * cos); + } + + get perpendicular(): Vector2 { + return new Vector2(-this.y, this.x); + } + + clone(): Vector2 { + return new Vector2(this.x, this.y); + } + + toString(): string { + return `Vector2(${this.x}, ${this.y})`; + } + + toArray(): [number, number] { + return [this.x, this.y]; + } + + [Symbol.iterator](): Iterator { + let index = 0; + const components = [this.x, this.y]; + return { + next: (): IteratorResult => { + if (index < components.length) { + return { value: components[index++], done: false }; + } + else { + return { value: undefined as any, done: true }; + } + }, + }; + } + + deadZone(threshold: number = 1e-4): Vector2 { + return new Vector2( + Math.abs(this.x) < threshold ? 0 : this.x, + Math.abs(this.y) < threshold ? 0 : this.y + ); + } + + deadZoneEq(threshold: number = 1e-4): this { + if (Math.abs(this.x) < threshold) this.x = 0; + if (Math.abs(this.y) < threshold) this.y = 0; + return this; + } + + static fromAngle(angle: number, magnitude: number = 1): Vector2 { + return new Vector2(Math.cos(angle) * magnitude, Math.sin(angle) * magnitude); + } + + static dot(a: Vector2, b: Vector2): number { + return a.x * b.x + a.y * b.y; + } + + static cross(a: Vector2, b: Vector2): number { + return a.x * b.y - a.y * b.x; + } + + static distance(a: Vector2, b: Vector2): number { + const dx = a.x - b.x; + const dy = a.y - b.y; + return Math.sqrt(dx * dx + dy * dy); + } + + static distanceSqr(a: Vector2, b: Vector2): number { + const dx = a.x - b.x; + const dy = a.y - b.y; + return dx * dx + dy * dy; + } + + static lerp(a: Vector2, b: Vector2, t: number): Vector2 { + return new Vector2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); + } + + static clamp(v: Vector2, min: Vector2, max: Vector2): Vector2 { + return new Vector2( + Math.min(Math.max(v.x, min.x), max.x), + Math.min(Math.max(v.y, min.y), max.y) + ); + } + + static angleBetween(a: Vector2, b: Vector2): number { + const dot = Vector2.dot(a, b); + const mag = a.length * b.length; + if (mag === 0) + return 0; + + const cos = dot / mag; + return Math.acos(Math.min(1, Math.max(-1, cos))); + } + + static get zero(): Vector2 { + return new Vector2(0, 0); + } + + static get one(): Vector2 { + return new Vector2(1, 1); + } + + static get up(): Vector2 { + return new Vector2(0, 1); + } + + static get down(): Vector2 { + return new Vector2(0, -1); + } + + static get left(): Vector2 { + return new Vector2(-1, 0); + } + + static get right(): Vector2 { + return new Vector2(1, 0); + } +} + +export default Vector2; diff --git a/src/modules/Login.svelte b/src/modules/Login.svelte index 750f900..6a88c7a 100644 --- a/src/modules/Login.svelte +++ b/src/modules/Login.svelte @@ -31,7 +31,7 @@
- {username} + {username}
diff --git a/src/modules/Shimeji.svelte b/src/modules/Shimeji.svelte index 58052b2..f1bef97 100644 --- a/src/modules/Shimeji.svelte +++ b/src/modules/Shimeji.svelte @@ -7,10 +7,8 @@ let shimeji: Shimeji; let sprite: HTMLElement; - let pos: number = $state(0); - let vel: number = $state(0); - let targetPos: number = $state(0); - let rafId: number; + let canvas: HTMLCanvasElement; + let shown: boolean = $state(false); function genRandomPos(min: number, max: number): number{ const out = Math.random() * (max - min) + min; @@ -18,9 +16,14 @@ } onMount(() => { - shimeji = new Shimeji(sprite); + canvas.width = window.innerWidth; + canvas.height = window.innerHeight; + + shimeji = new Shimeji(sprite, canvas); shimeji.start(); + shown = true; + document.addEventListener('keydown', (e) => { if(e.key === 'a') { shimeji.addImpulse(-500, -100); @@ -36,14 +39,16 @@ return () => { shimeji.stop(); }; + }) -
-
+
+ +
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index f9c8c2b..321b1bf 100755 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -4,6 +4,7 @@ import { onMount, type Snippet } from 'svelte'; import { theme } from '$lib/stores/theme'; import Loading from '../modules/Loading.svelte'; + import Shimeji from '../modules/Shimeji.svelte'; let { children }: { children: Snippet } = $props(); @@ -43,6 +44,7 @@ class:dark={$theme === 'dark'} class:light={$theme === 'light'} > + {@render children()} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 38c25d4..5112c58 100755 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -39,7 +39,7 @@ {:else}
-
+