Spin the item following the path it is traveling

As an example, when I press the "W" button, the object should rotate to the side

https://i.sstatic.net/ifq1G.jpg

if (keyBoard[87]) {
    camera.position.x -= Math.PI / 10;
    bulba.position.x -= Math.PI / 10;
}

if (keyBoard[83]) {
    camera.position.x += Math.PI / 10;
    bulba.position.x += Math.PI / 10;
}

if (keyBoard[65]) {
    camera.position.z += Math.PI / 10;
    bulba.position.z += Math.PI / 10;
}

if (keyBoard[68]) {
    camera.position.z -= Math.PI / 10;
    bulba.position.z -= Math.PI / 10;
}

This is my basic method for implementing movement

Answer №1

Exploring a basic concept with Tween.js:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 5);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var boxGeom = new THREE.BoxBufferGeometry(1, 1, 3);
boxGeom.translate(0, 0, 2.5);
var box = new THREE.Mesh(boxGeom, new THREE.MeshNormalMaterial());
box.rotation.y = Math.PI * 0.5;
scene.add(box);

window.addEventListener("keydown", onKeyDown, false);

function onKeyDown(event) {

  if (![65, 68, 83, 87].includes(event.keyCode)) return;

  var angleTo = 0;
  switch (event.keyCode) {
    case 87:
      angleTo = Math.PI;
      break;
    case 65:
      angleTo = Math.PI * -0.5;
      break;
    case 83:
      angleTo = 0;
      break;
    case 68:
      angleTo = Math.PI * 0.5;
      break;
  }

  startTween(angleTo);

}

function startTween(angleTo) {
  let tween = new TWEEN.Tween(box.rotation).to({
    y: angleTo
  }, 250).onStart(() => {
    window.removeEventListener("keydown", onKeyDown, false);
  }).onComplete(() => {
    window.addEventListener("keydown", onKeyDown, false)
  });
  tween.start();
}

renderer.setAnimationLoop(() => {
  TWEEN.update();
  renderer.render(scene, camera);
})
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>

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

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...

Achieve compatibility for two different types of route parameters in Vue.js

I am trying to set up nested sets of categories in URLs that lead to specific products, but I'm having trouble with matching the routes correctly. Here are the URLs I want: --- renders a "category.show.vue": /$categorySlug+ app.com/catA/cat ...

Dynamically arranging data rows in a table using dates with Vue

In my Vue application, I am currently processing data for employees, including their hours and swipes, and multiplying this data for each employee every day. This process is generating new rows of data so that I have a complete set of information for each ...

Issue with updating element value based on option select

I am struggling to update the text of a div based on the selection of an option in another div. The code snippet I have tried is not working as expected. Is there anyone who can provide assistance with this issue? <div class="field-wrap"> <inpu ...

Using the video-js feature to play multiple videos simultaneously

Is it possible to play multiple videos using video-js functionality simultaneously? The answer is yes! Check out Fiddle 1 However, an issue arises when wrapping a trigger, such as a button, around the function that invokes playVideo(). This causes the v ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

Utilizing Selenium to inject javascript permanently or on every page refresh

In my selenium webdriver test using Python 3, I have implemented a semi-automated process. This means that some routines are automated while other tasks require user interaction with the browser, such as page refreshes or redirects. My challenge is to inj ...

Excluding a Spec File in Your Protractor Configurations

I have a scenario where I have 10 spec files all named *********.test.js. I need to run tests on all 9 of these files, excluding the file named Idontwantyou.test.js. Currently, I am locating my spec files in the config.file using: specs: ['*.test.js ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

What is the best way to set up the Bootstrap 4 popover in a React project?

Struggling with implementing popovers in my project, following the guidelines at: https://getbootstrap.com/docs/4.0/components/popovers/. The documentation mentions that popovers are a plugin and require the tooltip plugin as well. After making changes to ...

Request Pending | Observation of WebSockets in NestJS

I'm currently working on a NestJS application that interacts with the Binance Websocket API to retrieve some data. While I am able to see all the data in my console.log, I'm facing an issue where the request seems to be pending when using Postman ...

Tips for selecting the right decorator for your space

I am working on developing a game that utilizes an AI. This AI's API consists of 3 methods implemented in an Angular Service Here is a simplified version of the code: app.service('AI', [function(){ return { offer: angular.noop, ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

I encountered a difficulty trying to assign a value to @Input decorators in the spec file

While writing a test case for form submission, I encountered an issue where the Input decorator (e.g. station) value is reassigned during form submission. However, when attempting to define this Input value in the spec file, the component.station value is ...

Extract the height of children from the height of their parent

Hey there! I recently discovered a fantastic plugin that helped me achieve equal heights for all the divs on my website. If you're interested, you can check out the plugin here. $('.item-container').responsiveEqualHeightGrid(); However, I& ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...

A clever JavaScript function generator encapsulated within an instant function nested within a jQuery ready statement

This code snippet features an immediate function enclosed within a jQuery ready function. $((function(_this) { return function() { document.write('called!'); }; })(this)); I am puzzled by where the resultant function ...

Is it possible to pre-select a value in a PrimeVue Dropdown component?

Situation: Currently, I am incorporating PrimeVue into a Vue.js project. Within this setup, there is a dropdown component sourced from PrimeVue, utilizing an array of objects. The structure of the dropdown component appears as follows: <template #positi ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...