Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3().

However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the following error message:

Uncaught TypeError: Cannot read property 'set' of undefined

window.addEventListener('DOMContentLoaded',function(){

    var scene, camera, renderer,
        width  = window.innerWidth,
        height = window.innerHeight,
        radians = .025,
        wallHeight = 128,
        mesh = new THREE.Object3D();

    renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setSize(innerWidth, innerHeight);
    renderer.setClearColor(0xfcfcfc);
    document.body.appendChild(renderer.domElement);

    scene = new THREE.Scene();

    var groundG = new THREE.PlaneGeometry(500, 1024),
        commomMaterial = new THREE.MeshLambertMaterial({
            color:0xf5f5f5
        }),
        charcterMaterial = new THREE.MeshLambertMaterial({
            color:0x7A43B6
        }),
        mainGround = new THREE.Mesh(groundG, commomMaterial);
        mainGround.position.set(0,55,0);
        mainGround.rotation.x = THREE.Math.degToRad(270);

    var wall = [
        new THREE.PlaneGeometry(groundG.parameters.height, wallHeight),
        new THREE.PlaneGeometry(groundG.parameters.width, wallHeight),
        new THREE.PlaneGeometry(groundG.parameters.height, wallHeight),
        new THREE.PlaneGeometry(groundG.parameters.width, wallHeight),
    ];
    mesh.add(mainGround);
    var walls = []
    for (var i = 0; i < wall.length; i++) {
        walls[i] = new THREE.Mesh(wall[i],new THREE.MeshLambertMaterial({color:0xff0000}));
        walls[i].position.y = wallHeight;
        mesh.add(walls[i]);
    }

    walls[0].rotation.y = -Math.PI / 2;
    walls[0].position.x = groundG.parameters.width / 2;
    walls[1].rotation.y = Math.PI;
    walls[1].position.z = groundG.parameters.height / 2;
    walls[2].rotation.y = Math.PI / 2;
    walls[2].position.x = -groundG.parameters.width / 2;
    walls[3].position.z = -groundG.parameters.height / 2;

    scene.add(mesh);

    var characterMesh = new THREE.Object3D();
        characterMesh.position.y = 88,
        characterDirection = new THREE.Vector3(0, 0, 0);;

    var headG = new THREE.SphereGeometry(32, 50, 50),
        head = new THREE.Mesh(headG, charcterMaterial),
        noseG = new THREE.SphereGeometry(4, 4, 4),
        nose = new THREE.Mesh(noseG, charcterMaterial);

        head.position.y = 0;
        characterMesh.add(head);

        nose.position.y = 0;
        nose.position.z = 32;
        characterMesh.add(nose);


    scene.add(characterMesh);
    var light = new THREE.PointLight();

    light.position.set(50, 400, 0);
    scene.add(light);

    camera = new THREE.PerspectiveCamera(55, width/height, 0.1, 10000000);
    camera.position.set(0,356 ,740);
    camera.lookAt(mesh);

    camera.lookAt(mainGround.position);

    function render () {
        renderer.render(scene, camera);
        requestAnimationFrame(render);
    }

    document.addEventListener('keydown', function (e) {
        var dx =0 , dy = 0, dz = 0;
        switch(e.keyCode) {
            case 37: 
                dx = 1;
            break;
            case 38:    
            break;
            case 39: 
                dx = -1;
            break;
            case 40:                
            break;
        }
        characterDirection.direction.set(dx,dy,dz);
    })
    render();
});

Answer №1

Your mainGround code is using THREE.Mesh.

According to the documentation, Mesh objects do not inherently have a position. Perhaps you need to consider changing the position to a different property...

Answer №2

When handling the 'keydown' event, you are implementing the following code:

characterDirection.direction.set(dx,dy,dz);

However, it seems like in your sample code, characterDirection is an instance of THREE.Vector3, and this class does not have a property named direction.

It is likely that you intended to directly modify characterDirection using the set method provided by the class:

characterDirection.set(dx,dy,dz);

This approach would properly update the Vector3 instance with the specified values.

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

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

A guide to defining a color variable in React JS

I am trying to use a random color generated from an array to style various elements in my design. Specifically, I want to apply this color to certain elements but am unsure how to do so. For example, I know how to make a heading red like this: const elem ...

Can PushState be used to Ajaxify CSS files?

Currently, I am in the process of developing a basic website and have decided to incorporate the Ajaxify library for seamless page transitions. One challenge I have encountered involves the combination of global CSS files (applied throughout the entire sit ...

I'm baffled by why I keep receiving the error message "Unknown provider: $routeProvider <- $route <- AppController" in AngularJS, even though I have already

I've exhausted all the solutions I found on stackoverflow without success. Apologies if this is a duplicate question. My goal is to reset the content of my Bootstrap table with a button click using the function $route.reload(). However, when I includ ...

I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test: import { shallowMount } from '@vue/test-utils' import Wor ...

What is causing the issue with the code `exports = { z: function() {} };` not functioning as intended?

Script A exports = { z: function() { console.log('aZ'); } }; Script Main require('./a').z(); // error Have you ever wondered why require('./a') ends up returning an empty object? ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Create HTML elements based on the information in a JSON object

My goal is to create span elements for each word in my subtitle text, which is stored in a JSON object. Here is the JSON data I am working with: var sub_info = [ {'start': 3.92, 'end': 6.84, 'words ...

Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS. The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops. Here's the code I've be ...

Revamp your website with an AJAX-powered login form that dynamically updates the page content upon successful

Imagine having a page with a dynamic login/logout feature in the header that operates smoothly via AJAX. When a user is not logged in, display a message saying "Hey, login" and provide the option to login via AJAX, which functions correctly. However, onc ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

Is it possible for my code in ReactJS to utilize refs due to the presence of backing instances?

When working with ReactJS components, I often piece together JSX elements to create my code. For example, take a look at the snippet below. I recently came across this page https://facebook.github.io/react/docs/more-about-refs.html which mentions that "Re ...

Observables do not provide any results when used in a pipe with an image src

I recently created a custom pipe for the image src in my application: It is applied to selectors like this: <img [src]="myobject?.URL | secure" /> Here's the code snippet for the pipe: import { Pipe, PipeTransform } from '@angular/c ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Currently, I am developing a Vue.js chat application. I am facing a challenge when it comes to sending the entire input div along with the keyboard popping up on Android devices. How can I achieve this

I'm in the process of developing a chat application using vuejs that will be accessed through a webview on Android. I currently have an input-bx element for sending messages, but I need to find a way to ensure it remains visible when the Android keybo ...

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...