Unable to invoke a function in Java Script

Currently, I am experimenting with Box2dWeb and creating a top-down car game.

The issue I am facing is related to controlling the car's movement. Initially, I want the car to only move forward without using wheels. Instead, I am applying force directly to the car, which is represented as a box.

I have created a function for handling controls, but for some reason, it is not being called. This is where I require some guidance or advice. (The creation and placement of objects are functioning correctly)

Below is a snippet of the code:

var GlobalVar={   }
var KEY = {
    UP: 87,//W
    DOWN: 83,//s
    LEFT: 65,//A
    RIGHT: 68//D
}        
GlobalVar.pressedKeys = [];//an array to remember which key is pressed or not

$(function(){
   $(document).keydown(function(e){
     GlobalVar.pressedKeys[e.keyCode] = true;
 });
$(document).keyup(function(e){
  GlobalVar.pressedKeys[e.keyCode] = false;
 });

Rendering();
PlaceStuff(GlobalVar.currentLevel);//placing stuff, like car and boundaries/walls
moveCar();

});
function moveCar(){
 if (GlobalVar.pressedKeys[KEY.UP]){
   var force = new b2Vec2(0, -10000000);
   GlobalVar.car.ApplyForce(force, GlobalVar.car.GetWorldCenter());
  }
}

Answer №1

It seems that the moveCar function is only being called once.

To address this, consider the following:

function moveCar(){

   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force, GlobalVar.car.GetWorldCenter());
    }

    requestAnimationFrame(moveCar);

}

You may need to incorporate a modifier to adjust the force based on frame rate:

then = Date.now();

function moveCar(){

    var now = Date.now();
    var modifier = now - then; // Calculate the time in milliseconds since the last execution of moveCar.

    then = now;

   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force * modifier, GlobalVar.car.GetWorldCenter());
    }

    requestAnimationFrame(moveCar);

}

This method ensures consistent movement speed across different systems.


If you want to execute the Rendering() function multiple times, consider creating a new function to call both functions repeatedly:

then = Date.now();

function moveCar(modifier){
   if (GlobalVar.pressedKeys[KEY.UP]){
       var force = new b2Vec2(0, -10000000);
       GlobalVar.car.ApplyForce(force * modifier, GlobalVar.car.GetWorldCenter());
    }
}

function update() {
    var now = Date.now();
    var modifier = now - then; // Calculate the time in milliseconds since the last execution of moveCar.

    then = now;

    moveCar(modifier);
    Rendering();

    requestAnimationFrame(update);
}

Answer №2

The feedback provided emphasizes the importance of calling the moveCall function after every key press event, rather than just once:

$(document).on('keydown keyup', function(e){
    GlobalVar.pressedKeys[e.keyCode] = true;
    moveCar();
});

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

When you zoom in, the HTML elements tend to shift out of place

Spent the entire day yesterday attempting to make my page responsive while Zooming In, but I just can't seem to get it right. Even after adding height and weight, elements still get mixed up when zooming in on the page. I've scoured countless w ...

jQuery experiences difficulty in sending arrays in the JSON content type

I have a JavaScript script that looks like this: $.ajax({ url: 'myservice', type: 'POST', contentType: 'application/json', data: ["test"], }); However, when I execute the script, it sends a request to myservi ...

Steps to set Option one as the selected value following a click event or an onClick function:

I'm having trouble getting this code to change the default option value! JS <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> function updateDefa ...

Unable to assign focus to textbox

In my chrome extension, I have implemented two text boxes - one for entering a URL and the other for LDAP. Upon clicking on the extension icon, a popup page opens where I automatically fill the URL text box with the current page's URL using the code s ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...

Always ensure that an element remains at the bottom during the sorting process

Currently, I have a list of items with an integer attribute that aids in sorting the list. However, I am looking for a way to designate specific items to always appear at the bottom of the list regardless of the sorting criteria. Is there a singular valu ...

Ways to effectively shut down the jQuery context menu

I'm having trouble with a jQuery context menu that won't close when I want it to. Here are the functions I have set up: function openContextMenu(event) { event.preventDefault(); $("#custom-menu") .css({ top: eve ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

The results returned by the jQuery find() function vary across various pages

One interesting feature on my website is the header bar with a search function. I have implemented a function that involves resizing boxes to contain search results. On one specific page, this function works like a charm: $(".suggestionCategory").each(fu ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Utilizing JavaScript async over setInterval for improved efficiency

Let's say I want to execute the function update() every second. I have two options to achieve this: async function interval() { await new Promise((resolve, reject) => { setTimeout(resolve, 1000) }) update() interval() } or setInter ...

What is the best way to show real-time values using chart js?

Just recently, I've delved into the world of web development and am eager to learn how to integrate chart js for real-time value display. Could anyone offer advice or guide me through the process? var data = []; var temp = []; async f ...

What is the best way to notify an XML file using jQuery?

I am encountering an issue with a login api when trying to send an xml document. The error occurs when including '<?', but I need to send the whole XML with it. Can someone assist me in sending the complete XML using a different method or type ...

Set the value of one email input to another email input in AngularJS

I'm having trouble trying to link an email input field to another in angularjs without success. Here is what I have attempted so far: <div class="row-fluid"> <div class="control-group span12"> <label for="email">Email</labe ...

What are the best practices for managing NVM in a live production setting?

Currently, I am developing a Sails web application using NVM. I have successfully installed node v0.12.7 through NVM and use this particular version to power the website. nvm use 0.12.7 sails lift Sails typically runs on port 1337, but for production pur ...

Protecting website pages on both the admin and user side in Next.js 14 to ensure maximum security

I'm currently using nextjs 14 and I am working on developing a website similar to a property app. It will have an admin dashboard and a user side. How can I ensure the security of both the admin and user sides, and what should my folder structure look ...

What is the process for converting a URL or HTML document to a PDF using the html2pdf JavaScript library?

I am working on creating a button that utilizes the html2pdf library to convert an HTML page into a PDF. Instead of selecting an element with query selector or getElementById, I would like to pass a URL because the page I want to convert is not the same as ...

Tips for enhancing the efficiency of large-scale data Angular Material apps when using internet explorer

Our team is currently working on an Angular Material application that deals with a significant amount of data, ranging from 20 to 40 thousand rows. While this application performs smoothly in Chrome, we are experiencing slow performance issues in MSIE 11 ...

JQuery is having issues with $(this) and the find function not working properly

I am attempting to access a child of the div with the class form-group, specifically, I want to display the value of the input element. <div class="form-group"> <label>text</label> <input name="text" type="text" class="form-co ...

The art of handling jQuery promises and interconnected AJAX requests

Is there a better way to handle dependent AJAX calls using promises/deferred in jQuery? Currently, my code looks like this: $.when($.ajax('https://somedomain.com/getuserinfo/results.jsonp', { dataType : 'jsonp', jsonp ...