What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2

While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this through animation? Additionally, I encountered an issue where the movement didn't work within a code snippet, although it functions properly in my visual studio code environment.

var bodyEl = document.querySelector("body");
var boxEl = document.querySelector("div");


var left = 0;
var top = 180;

var speed = 10;

bodyEl.addEventListener ("keydown", moveBox);

function moveBox(e) {
    if (e.keyCode === 37) {
        left -= speed;
    }

    else if (e.keyCode === 39) {
        left += speed;
    }

    else if (e.keyCode === 38) {
        top -= speed;
    }

    else if (e.keyCode === 40) {
        top += speed;
    }


    boxEl.style.top = top + "px";
    boxEl.style.left = left + "px";

}
body {
    background-image: url("https://i.stack.imgur.com/x1iaz.jpg");
    cursor: none;
    overflow: hidden;
}

div {
    position: absolute;
    top: 180px;
}
<div><img src="https://i.stack.imgur.com/9dPYr.png" height="300px" width="300px" ></div>

Answer №1

Try animating a box by adding a custom class when the right arrow key is pressed, and removing it when the left arrow key is pressed. You can do the same for the up and down arrow keys.

Add this CSS -

div.reverse img {
 -webkit-transform: scaleX(-1);
  transform: scaleX(-1);
 }

Update the JavaScript function -

function moveBox(e) {
    if (e.keyCode === 37) {
        boxEl.classList.remove("reverse");
        left -= speed;
    }

    else if (e.keyCode === 39) {
        boxEl.classList.add("reverse");
        left += speed;
    }

    else if (e.keyCode === 38) {
        top -= speed;
    }

    else if (e.keyCode === 40) {
        top += speed;
    }


    boxEl.style.top = top + "px";
    boxEl.style.left = left + "px";

}

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

Differences between using CSS properties and AngularJS filters:CSS properties

When working on an angularjs application, one task may be to convert a string to uppercase. There are 2 options available to achieve this, both yielding the same result. However, it is important to consider the scenarios in which one option may be preferre ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Tips for toggling Bootstrap 5 tabs using JavaScript instead of the button version

I am looking to switch tabs programmatically using bootstrap 5. The Bootstrap documentation recommends using buttons for tabs instead of links for a dynamic change. Here is the code I have: $("#mybut").click(function() { var sel = document.querySelector( ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Frequently encountering broken styles in Magento 1.9 due to missing CSS and JS files

Recently, I've been facing frequent style breaking issues on my Magento sites (1.9.2+). This results in the home page displaying only text with missing CSS, JS, and images. To fix this problem, I usually clear the cache by deleting the var/cache fold ...

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

Tips for aligning a logo in the center of a navigation bar

I'm struggling to center a logo within the navigation bar of a website I am designing. Despite my attempts, I have not been successful in achieving the desired result. My goal is to have the logo positioned in the middle of the navigation bar, with ot ...

What causes the function execution to not be delayed by setTimeout?

function attemptDownloadingWebsite(link) { iframe = document.getElementById('downloadIFrame'); iframe.src = link; setTimeout(removeFile(link), 25000); } This is the remove file function: function removeFile(link){ $.ajax ...

Is there a way to handle specific email format designs with PHP?

When trying to send an email with specific shipping information and tracking numbers, the formatting appears strange. Here is the desired format: Dear xyz , Per your request, this email is to no ...

How to trigger a force reload on a VueJS route with a different query parameter?

Is there a method to refresh the page component when two pages utilize the same Component? I have encountered an issue where the router does not reload and the previous edit values persist. { path: "/products/new", component: ProductPage, meta: { ...

Add a new value to an object and ensure that only the unique value is appended to the first

I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its kind. Obj1 [{ buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 // add new key valu ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...

The state initialization process is beginning with an [object Object] being passed into the setState function

Within the async function provided below, I am invoking stationData to verify that an array of objects is being passed into bartData (which currently consists of an empty array). Upon exploration, I have observed a response containing the anticipated array ...

Troubleshooting Azure Routing Issues after Switching to .ejs Files

I am facing an issue where my application breaks on Azure after changing the file extensions and routes to point to the renamed .ejs files, but it works perfectly fine locally. angularApp.js var app = angular.module('theApp', ['ui.router&a ...

Verifying that a parameter is sent to a function triggering an event in VueJS

One of the components in my codebase is designed to render buttons based on an array of objects as a prop. When these buttons are clicked, an object with specific values is passed to the event handler. Here's an example of how the object looks: { boxe ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

I am attempting to extract text from an element, but instead of the text, I received a value and am unable to click on it. This particular element is a dropdown button in a Selenium test, with

<div class="select-wrapper initialized"> <span class="caret">▼</span> <input type="text" class="select-dropdown" readonly="true" data-activates="select-options-56a6924e-42d9-1f78-1b82-fe2c1cbdfbdd" value="R3PORTS ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...