quhluh

SPRINTING MECHANIC FOR JAVASCRIPT CODE (STEP BY STEP EXPLANATION)

May 29th, 2023
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // HTML
  2. // You'll need a button or key event to trigger the sprinting mechanic.
  3.  
  4. // JavaScript
  5. const player = {
  6.   speed: 5, // Normal movement speed
  7.   sprintMultiplier: 2, // Multiplier applied to speed during sprint
  8.   isSprinting: false, // Flag to track sprinting state
  9. };
  10.  
  11. // Function to handle sprinting mechanic
  12. function handleSprinting() {
  13.   // Check if the player is sprinting
  14.   if (player.isSprinting) {
  15.     player.speed =  player.speed * player.sprintMultiplier;
  16.     console.log("Player is sprinting");
  17.   } else {
  18.     player.speed = 5; // Reset speed to normal when not sprinting
  19.     console.log("Player is not sprinting");
  20.   }
  21. }
  22.  
  23. // Event listener to toggle sprinting
  24. document.addEventListener("keydown", function(event) {
  25.   if (event.key === "Shift") {
  26.     player.isSprinting = true;
  27.     handleSprinting();
  28.   }
  29. });
  30.  
  31. document.addEventListener("keyup", function(event) {
  32.   if (event.key === "Shift") {
  33.     player.isSprinting = false;
  34.     handleSprinting();
  35.   }
  36. });
Advertisement
Add Comment
Please, Sign In to add comment