Webbserver - Love Blomberg

Show sourcecode

The following files exists in this folder. Click to view.

public_html/gamla-kurser/webbutv2/projekt/snake_br/js/

cookie-clicker.js
fidget-spinner.js
snake.js

fidget-spinner.js

79 lines ASCII Windows (CRLF)
document.addEventListener('DOMContentLoaded', function() {
  const fidgetSpinner = document.getElementById('fidgetSpinner');
  let isSpacePressed = false;
  let rotationAngle = 0;
  let angularVelocity = 0;
  let lastTimestamp = 0;
  let animationFrameId = null;
  
  // Physics constants
  const MAX_VELOCITY = 15; // Maximum rotation speed (radians per second)
  const ACCELERATION = 30; // How quickly it speeds up when space is pressed
  const FRICTION = 0.99; // Friction factor (how quickly it slows down)
  const MIN_VELOCITY = 0.1; // Velocity threshold to stop the animation
  
  // Prevent scrolling from game controls (space and arrow keys)
  document.addEventListener('keydown', function(event) {
    // Prevent default for space and arrow keys to avoid scrolling
    if (event.code === 'Space' || 
        event.code === 'ArrowUp' || 
        event.code === 'ArrowDown' || 
        event.code === 'ArrowLeft' || 
        event.code === 'ArrowRight') {
      event.preventDefault();
    }
    
    // Handle space bar for fidget spinner
    if (event.code === 'Space' && !event.repeat) {
      isSpacePressed = true;
      
      // Start the animation if it's not already running
      if (!animationFrameId) {
        lastTimestamp = performance.now();
        animationFrameId = requestAnimationFrame(updateSpinner);
      }
    }
  });
  
  // Handle space bar release
  document.addEventListener('keyup', function(event) {
    if (event.code === 'Space') {
      isSpacePressed = false;
    }
  });
  
  function updateSpinner(timestamp) {
    // Calculate time difference
    const deltaTime = (timestamp - lastTimestamp) / 1000; // in seconds
    lastTimestamp = timestamp;
    
    // Update angular velocity
    if (isSpacePressed) {
      // Accelerate when space is pressed
      angularVelocity += ACCELERATION * deltaTime;
      if (angularVelocity > MAX_VELOCITY) {
        angularVelocity = MAX_VELOCITY;
      }
    } else {
      // Apply friction when space is not pressed
      angularVelocity *= FRICTION;
    }
    
    // Update rotation angle
    rotationAngle += angularVelocity * deltaTime * 360; // Convert to degrees
    rotationAngle %= 360; // Keep angle within 0-360 range
    
    // Apply rotation
    fidgetSpinner.style.transform = `rotate(${rotationAngle}deg)`;
    
    // Stop animation if spinning very slowly
    if (!isSpacePressed && Math.abs(angularVelocity) < MIN_VELOCITY) {
      cancelAnimationFrame(animationFrameId);
      animationFrameId = null;
      return;
    }
    
    // Continue animation
    animationFrameId = requestAnimationFrame(updateSpinner);
  }
});