Learn how to create simple animations in Three.JS with just a single key press

Is it possible to make a cube move smoothly in a certain direction with just one key press? I've only been able to create continuous animation while the key is held down.

Below is the code snippet I am currently working with:

<script>
    function setup() {
... additional code ...
        document.addEventListener("keydown", handleKeyDown, false);
                    };

            function handleKeyDown(event) {
                var keyPressed = event.which; 
                if (keyPressed == 37) {
                    animateLeft();     
                }
            };
            function animateLeft() {
                var timer = 0.0001 * Date.now();
                for(var v = 0; v < 10; v++){
                    cube.position.x = Math.cos(timer) * v;
                }
                startAnimation();       
            }
            function startAnimation() {
                requestAnimationFrame(startAnimation);
                renderCube();
            };
            function renderCube() {
                renderer.render(scene, camera);
            }
            setup();
            startAnimation();
</script>

Answer №1

When using the leftAnimation() function, it will only run once during the internal loop before updating the frame. This can make the cube seem like it's just nudging instead of animating.

To solve this issue, you can use a fixed motion vector that is initially set to null. When a key is pressed, you can then initialize the vector with the desired direction for moving the cube.

In the code example below, the current vector is added to the cube's position only when it is not null:

// Your initialized code here ...

// Motion vector
var vector = null;

// Key press handler
document.onkeydown = function(e) {
  e.preventDefault();
  if (e.keyCode === 37) {             
    vector = {x: -0.02, y: 0, z: 0};  
  }
};

(function loop() {
  requestAnimationFrame(loop);
  render();
  // Update cube position with vector deltas if vector is set
  if (vector) {  
    cubeMesh.position.x += vector.x;
    cubeMesh.position.y += vector.y;
    cubeMesh.position.z += vector.z;
  }
})();

// Additional rendering functions here ...

You can also choose to accumulate the vector by initializing it with zeros and adding or subtracting values based on key presses for more controlled movements:

// Motion vector
var vector = {x: 0, y: 0, z: 0};

// Key press handler
document.onkeydown = function(e) {
  e.preventDefault();
  if (e.keyCode === 37) {       
    vector.x -= 0.002;
  } else if (e.keyCode === 39) {
    vector.x += 0.002;
  }
};

(function loop() {
  requestAnimationFrame(loop);
  render();
  cubeMesh.position.x += vector.x;
  cubeMesh.position.y += vector.y;
  cubeMesh.position.z += vector.z;
})();

For a more detailed approach, you can use individual variables/constants for each direction of movement. Feel free to customize as needed.

View live example

View another live example

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

Incorporate dc.js into your Cumulocity web application

Our team is facing a challenge while trying to integrate dc.js into our Cumulocity web application. While the standalone version works perfectly, we encounter issues when attempting to use it within Cumulocity. Below is the code for our standalone applica ...

Jquery slide animation not functioning properly

Hello, I am attempting to create a sliding effect for specific text where the slide effect adds something similar to extra spacing. The desired effect can be seen here: like margin or something, the framework being used is . My question is: Is there a wa ...

next-auth: after hitting login, user will be redirected to /api/auth/error

I'm encountering an issue where NextAuth consistently redirects to the error page without returning a user as expected based on my code in: ./app/account/login/page.tsx "use client"; import React, { useState } from "react"; import ...

Generating an interactive table using JSON with Angular 5

Can a dynamic table with dynamic columns be created based on a JSON object using Angular 5? If yes, how? The API response includes the following JSON: { "ResponseStatus": true, "ResponseData": [ { "Parent": "Company 1", ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

Utilizing the power of HTML5 canvas technology, coupled with advanced

We are currently experimenting with using HTML5 canvas in conjunction with tablet styluses. However, we have encountered an issue where palm touching on multitouch tablets causes unintended lines to appear while drawing. Is there a way to disable multitou ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Cross domain request in a simple HTML document

I'm currently working on an app that is strictly in plain HTML files without a server. I'm facing difficulties with cross domain requests from JavaScript. Whenever I try to make a request, the browser displays this error message: XMLHttpRequest ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

What is the correct way to invoke a function from the reducer/actions within this specific scenario?

There seems to be an issue with the action/reducer I am attempting to call. It appears that the function is not being read correctly when called. The problem lies within the deleteWorkout function. I've attempted to use mapDispatchToProps and have al ...

Repetitive NodeJS event triggers within Electron-React application causing unexpected behavior

In my custom software package (referred to as PACKAGE_A), I have implemented various automated tasks using a node script. This package includes a Notifier module that creates and exports an EventEmitter. (The entire project is structured as a Monorepo) co ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

HTML/JS Implementation: Back to Top Visual Element

- This website appears to be quite simple at first glance. However, I have encountered an issue where every time I scroll down and then click on the "About" menu option, it abruptly takes me back to the top of the page before displaying the section with a ...

Choose the default text option for your AngularJS dropdown menu

I am facing an issue with my angularjs dropdownlist that is using ng-options. <select ng-options="perlocation.name for perlocation in locations" ng-model="locationDropdown"> Even though my dropdown list loads correctly, the selected option 0 is dis ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Managing the `selected` property of an option in React/NextJS

I have been working on a website and encountered an issue with a dynamic select box in React. Despite the functionality of my app being intact, I am struggling to add the selected property to an option once it is chosen. Is there a more effective way to ...

Tips for efficiently rendering large data in nextjs when it comes into view?

Is there a way to create a dropdown option in Nextjs where users can easily select an erc20 token from a token list? I attempted to use a standard mapping function on the token list, but it caused the site to become unresponsive and very slow due to the s ...

Ways to alter the color of a link after clicking it?

Is there a way to change the link color when clicking on it? I have tried multiple approaches with no success. The links on this page are ajax-based and the request action is ongoing. <div class="topheading-right"> <span> ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...