skip to Main Content

In my game, there is a "boost" option that pushs the player forward when they press Left Shift.
The problem is you can spam the button and go flying across the map.
To resolve this issue I want to add a small cooldown that will give the player good speed, but also won’t let the player exploit the feature by speeding across the entire map in 5 seconds.

I have tried looking up how to fix the issue but nothing helped because the code was in something like c++ or python.

Here is the code for my movement:

function Input() {
    document.addEventListener('keydown', (event) => {
    var name = event.key;
    var code = event.code;
    if (code == "ArrowRight" || code == "KeyD") {
        velX+= 5
    }
    if (code == "ArrowDown" || code == "KeyS") {
        velY+= 5
    }
    if (code == "ArrowUp" || code == "KeyW") {
        velY-= 5
    }
    if (code == "ArrowLeft" || code == "KeyA") {
        velX-= 5
        
    }
    if (code == "ShiftLeft") {
        velX *= 2
        velY *= 2
    }
    

    }, false);
}

2

Answers


  1. You can add a set timeout for your boost along with a boolean flag and make sure the user has some interval within each boost.

    // Define variables to track boost state and cooldown
    let isBoosting = false;
    let boostCooldown = false;
    
    // Function to handle boost
    function boost() {
      if (!isBoosting && !boostCooldown) {
        // Start boosting
        isBoosting = true;
        console.log("Boosting!");
    
        // Set a timer for the boost duration (e.g., 3 seconds)
        setTimeout(() => {
          // Stop boosting after the boost duration
          isBoosting = false;
          console.log("Boost ended!");
    
          // Set a cooldown timer (e.g., 5 seconds)
          boostCooldown = true;
          setTimeout(() => {
            // Reset the cooldown after the cooldown duration
            boostCooldown = false;
            console.log("Boost cooldown ended!");
          }, 5000); // Cooldown duration in milliseconds
        }, 3000); // Boost duration in milliseconds
      }
    }
    
    // Example: Call the boost function when the Left Shift key is pressed
    document.addEventListener("keydown", function (event) {
      if (event.key === "Shift") {
        boost();
      }
    });

    enter image description here

    Login or Signup to reply.
  2. just add a variable named Pressed (or something dosent matter) set it to false and when the user uses that boost set it to true
    and let a setTimeout with the cooldown u want that boost to be run in bg
    when the time reaches 0 set Preseed to false
    also make sure to check if the Pressed is false before running the boost code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search