"Quick as a keypress, the pace at which we move

Trying to explain my issue as clearly as possible. I have a Pacman game where the player controls Pacman using the keyboard. Pacman moves a constant unit in each direction and collision detection is based on a predefined map with obstacles marked by "-". Now, I want to introduce enemies that move randomly without keyboard input. The challenge is maintaining the speed control for enemies moving randomly compared to when controlled by the player. I am also trying to manage the frame rate using requestAnimationFrame but so far, my attempts at frame control haven't been successful. Here is the relevant section of my code:

function handleKeyPressed(e) {

   var PacMan = scene.getObjectByName('PacMan');
   gameSong.play();
   switch(String.fromCharCode(e.which))
   {
     case "w": if(!detectaColisao(PacMan.position.x, PacMan.position.y + SCALE))
          PacMan.position.y += SCALE;
       break;
     case "a": if(!detectaColisao(PacMan.position.x - SCALE, PacMan.position.y))
         PacMan.position.x -= SCALE;
       break;
     case "s": if(!detectaColisao(PacMan.position.x, PacMan.position.y - SCALE))
         PacMan.position.y -= SCALE;
       break;
     case "d": if(!detectaColisao(PacMan.position.x +SCALE, PacMan.position.y))
         PacMan.position.x += SCALE;
       break;

   }
}

function anima()
{
  var delta=clock.getDelta();
  orbitCamera.update(delta);

  requestAnimationFrame(anima);
  rendere

Answer №1

The object moves at position.x with a value of 10, but it shifts every time

Are you suggesting that it moves too frequently before the animation handling kicks in?

The issue here lies in the asynchronous nature of keypressed compared to your render loop - it triggers whenever a key is continuously held down.

To address this, ensure that your pacman only moves once per animate() cycle.

Incorporate booleans triggered by keypress events to control movement within the animate() cycle, like so:

var u, d, l, r;
u = d = l = r = false;

function handleKeyPressed(e) {
  switch (String.fromCharCode(e.which)) {
    case "w":
      u = true;
      break;
    case "a":
      l = true;
      break;
    case "s":
      d = true;
      break;
    case "d":
      r = true;
      break;
  }
}

function handleKeyReleased(e) {
  switch (String.fromCharCode(e.which)) {
    case "w":
      u = false;
      break;
    case "a":
      l = false;
      break;
    case "s":
      d = false;
      break;
    case "d":
      r = false;
      break;
  }
}

function moveModel(_u, _d, _l, _r, obj) {
  if (_u && !detectCollision(obj.position.x, obj.position.y + SCALE)) {
    obj.position.y += SCALE;
  }
  if (_d && !detectCollision(obj.position.x, obj.position.y + SCALE)) {
    obj.position.y -= SCALE;
  }
  if (_l && !detectCollision(obj.position.x, obj.position.y + SCALE)) {
    obj.position.x -= SCALE;
  }
  if (_r && !detectCollision(obj.position.x, obj.position.y + SCALE)) {
    obj.position.x += SCALE;
  }
}

function animate() {
  var PacMan = scene.getObjectByName('PacMan');
  moveModel(u, d, l, r, PacMan);
  var delta = clock.getDelta();
  orbitCamera.update(delta);
  requestAnimationFrame(animate);
  render();
}

Remember to reset these booleans when keys are released using handleKeyReleased function. This ensures we move only once per animate cycle, avoiding multiple movements in a single keypress event triggering.

This approach introduces an abstraction layer as key pressed responses occur independently, regardless of where you are in the animation cycle. By utilizing flags to dictate movement actions within the model, we maintain control over its behavior per animate() iteration.

Answer №2

It seems like a logical approach. Perhaps you could enhance their userData by including a variable such as "ghost.userData.timer" and incrementing it each cycle. Once it surpasses a predetermined coolDown value, for example 60, they can receive a random move and reset the timer to zero.

This method allows them to take steps at the intervals you specify.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement pagination for API requests in a JavaScript and React environment?

I am currently working on an app that fetches data from a movie API and returns 20 items from page 1. I am now looking to implement pagination so that users can click a button to view more items from subsequent pages. Below is my current API call: export ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

What is the correct way to shut down a Node.js Express server?

Upon receiving a callback from the /auth/github/callback URL, I am faced with the task of closing the server. Utilizing the standard HTTP API, the server can be closed using the server.close([callback]) API function. However, when working with a node-expre ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Toggle the Dropdowns and Submit Buttons on and off

I'm working on creating a web application that requires specific validation rules. When the page initially loads, I want only a single dropdown select box to be enabled while the rest of the elements like textboxes and buttons remain disabled. Once an ...

Tips for dealing with event bubbling in React

Looking for a way to add an onBlur event to the left panel so that it closes when the user clicks on the right panel. I attempted using onMouseLeave but the closing animation isn't as smooth as desired. Additionally, I'd like for users to close t ...

concealing a section of a div using the jQuery sortable feature

My code structure is quite similar to the example below, and I am attempting to conceal the TR elements with the class "some_row". <div id="sortable"> <table> <tr><td>Some Title 1</td></tr> <tr class="some_ro ...

What issue is there with the href attribute in the pug file?

/users/mihir/users/[object%20Object]/file.txt My pug file and JS code are set up to render a pug page with links for directories and files in the specified path. The problem arises when adding "users/" plus a username before the directory or filename whil ...

Retrieve Header information when making a cross-domain AJAX request

I've been working on a way to validate image URLs by using an AJAX call to check if the image is still available. The challenge I'm facing is that the image server is on a different domain, so I included the crossDomain: true attribute in my AJAX ...

Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well. After ex ...

Any suggestions on MySQL auto-inserted apostrophes?

Having trouble updating a value in my Database, as it's resulting in an error. Backend: router.patch("/toggleState", (req, res) => { const todoId = req.body.todoId; const attribute = req.body.attribute; const newValue = req.body.newValue ...

Opening the three.js editor by accessing local files

After downloading the three.js-master files, I noticed that it includes the three.js editor. Can anyone guide me on how to launch the editor from these files? ...

For each variable, assign a value

Apologies if this question has been asked before, but I'm encountering an issue with a foreach loop in JavaScript. let fields = temp_deviceAllocation.devices.forEach(async (device) => { const fields = await device_model .findOne({ dev ...

Encountering problem while exhibiting server's response message within a modal popup in Angular 6

I have implemented two custom dialog modals in an Angular component. The objective is to open the appropriate modal and display the response message. The component receives two values as Observables from my services: The name of the modal that needs to ...

Here is a unique PHP snippet that demonstrates how to close the current browser window:

After clicking a button, a popup window opens where I input values that are processed using server-side code. The issue arises when I try to close this window from there. Despite searching on stackoverflow for solutions, I have yet to find one that works. ...

Converting table data to JSON using JavaScript, including rows for "parent" and "children."

To create a JSON object by selecting values from multiple rows of a table using checkboxes, follow the structure below. The parent row, identified by the class 'primary color,' will be included in the JSON, along with the selected child rows. The ...

Mapping with groups in JavaScript

Is there a way to create a mapping in JavaScript? Currently, I am able to do if (number < 32) { group = 1; else if (number < 72) { group = 2; } else if (number < 100) { group = 3; } else { group = -1; } Instead of this, I am interested ...

What's the reason that app.use(app.static(...)); isn't functioning properly?

As someone who is new to programming, I am currently exploring Javascript, node.js, and express. I came across a question regarding the usage of app.use(express.static(path.join(...))); versus app.use(app.static(path.join(...)));. const app = express(); co ...

"Utilizing three.js to repeat a normal map texture effect

The mesh I have has a normalMap loaded, however, the normal map is not covering the entire surface. Despite correctly set UVs to cover the whole surface with texture. Is there a specific configuration to make the normal map repeat? Setting material.normal ...

Building a custom order creation system for Paypal shopping carts with personalized user information

I have a shopping cart where I store an array of my objects. Using a form and jQuery, I serialize all the custom user details. My goal is to integrate the user data gathered from the form (perhaps using payer or payer_info object) and also add my items to ...