Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function spawnBouncingBall(options) {
- options = options || {};
- // --- RANDOM BALL CHARACTER ---
- const randomChars = options.randomChars || ["๐ฉ", "๐ฉ", "๐ฉ", "๐ฉ", "๐ฉ", "๐ฉ", "0", "ยค", "โข"];
- const ballChar = randomChars[Math.floor(Math.random() * randomChars.length)];
- const colliderChar = options.colliderChar || "-";
- const speed = options.speed || 1;
- const friction = (options.friction !== undefined) ? options.friction : 0.98;
- const gravity = (options.gravity !== undefined) ? options.gravity : 0.05;
- const layer = options.layer || 0;
- // --- Random Color ---
- function randomColor() {
- const r = Math.floor(Math.random() * 255);
- const g = Math.floor(Math.random() * 255);
- const b = Math.floor(Math.random() * 255);
- return `rgb(${r},${g},${b})`;
- }
- const ballColor = randomColor();
- // --- RANDOM SPAWN AROUND CURSOR ---
- const dirs = [
- [1,0],[-1,0],[0,1],[0,-1],
- [1,1],[1,-1],[-1,1],[-1,-1]
- ];
- const spawnDir = dirs[Math.floor(Math.random() * dirs.length)];
- let x = cursor.x + spawnDir[0];
- let y = cursor.y + spawnDir[1];
- writeCharAt(ballChar, layer, x, y, ballColor);
- // --- Random initial velocity ---
- let vx = (Math.random() * 2 - 1) * speed;
- let vy = (Math.random() * 2 - 1) * speed;
- if (Math.abs(vx) < 0.2) vx = 0.2 * Math.sign(vx || 1);
- if (Math.abs(vy) < 0.2) vy = 0.2 * Math.sign(vy || 1);
- let rafId = null;
- function tick() {
- writeCharAt(" ", layer, Math.round(x), Math.round(y));
- vx *= friction;
- vy *= friction;
- vy += gravity; // gravity
- let newX = x + vx;
- let newY = y + vy;
- let rx = Math.round(newX);
- let ry = Math.round(newY);
- const info = getCharInfoXY(rx, ry);
- if (info && info.char === colliderChar) {
- const horizInfo = getCharInfoXY(Math.round(x + vx), Math.round(y));
- const vertInfo = getCharInfoXY(Math.round(x), Math.round(y + vy));
- if (horizInfo && horizInfo.char === colliderChar) vx = -vx;
- if (vertInfo && vertInfo.char === colliderChar) vy = -vy;
- newX = x + vx;
- newY = y + vy;
- rx = Math.round(newX);
- ry = Math.round(newY);
- }
- x = newX;
- y = newY;
- writeCharAt(ballChar, layer, rx, ry, ballColor);
- rafId = requestAnimationFrame(tick);
- }
- rafId = requestAnimationFrame(tick);
- return {
- stop() { cancelAnimationFrame(rafId); },
- setSpeed(newSpeed) {
- const factor = newSpeed / speed;
- vx *= factor;
- vy *= factor;
- },
- char: ballChar,
- color: ballColor
- };
- }
- // Example:
- spawnBouncingBall({
- gravity: 0.1,
- randomChars: ["@", "#", "$", "%", "&", "o"]
- });
Advertisement
Add Comment
Please, Sign In to add comment