The mouse control in Three.js

I've been attempting to make my sphere change variables based on the movement of the mouse cursor. Unfortunately, I seem to be encountering some issues as every time I try to include the variable code, the screen goes black. Here is the code snippet:

My goal is for the sphere to rotate in response to the position of the mouse cursor. However, I would appreciate any assistance in troubleshooting how to incorporate a mouse variable.

I have attempted this without success; whenever I insert the code into my existing one, the entire window blacks out.

mouse.x = event.clientX;

and

var mouse.x = event.clientX;

<script src="js/three.min.js"></script>

<script>
    var renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myCanvas'), antialias: true});
    renderer.setClearColor(0x000044);
    renderer.setSize(window.innerWidth, window.innerHeight);

    var camera = new THREE.PerspectiveCamera(15, window.innerWidth/window.innerHeight, 0.1, 3000);

    var scene = new THREE.Scene();

    var light = new THREE.AmbientLight(0xFFFFFF, 0.5);
    scene.add(light);

    var light2 = new THREE.PointLight(0xFFFFFF, 0.5);
    scene.add(light2);

    var geometry = new THREE.SphereGeometry(50, 30, 30);

    var material = new THREE.MeshPhongMaterial({
        color: 0xEEEEED,
        wireframe: true
    });

    var mesh = new THREE.Mesh(geometry,material);
    mesh.position.set(0, 0, -500);
    mesh.rotation.x = -0.05;

    scene.add(mesh);

    requestAnimationFrame(render);

    function render() {
        mesh.rotation.x += 0.005;
        mesh.rotation.y += 0.005;

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

    //document.body.appendChild(renderer.domElement);
</script>

Answer №1

I would suggest utilizing THREE.OrbitControls.

<script src="js/controls/OrbitControls.js"></script>

 controls = new THREE.OrbitControls( camera );

In order to ensure functionality and start with a properly initialized camera and mesh position, it is recommended to set the camera position away from the center of the world while keeping the mesh at the center of the world.

camera = new THREE.PerspectiveCamera(15, window.innerWidth/window.innerHeight, 0.1, 3000);
camera.position.set( 0, 0, 500 );

Check out the code snippet below:

var renderer, camera, controls, scene, mesh;

function init() {  

    renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myCanvas'), antialias: true});
    renderer.setClearColor(0x000044);
    
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(15, window.innerWidth/window.innerHeight, 0.1, 3000);
    camera.position.set( 0, 0, 500 );
    resize();
    window.onresize = resize;
    controls = new THREE.OrbitControls( camera );

    var light = new THREE.AmbientLight(0xFFFFFF, 0.5);
    scene.add(light);
    var light2 = new THREE.PointLight(0xFFFFFF, 0.5);
    scene.add(light2);

    var geometry = new THREE.SphereGeometry(50, 30, 30);
    var material = new THREE.MeshPhongMaterial({
        color: 0xEEEEED,
        wireframe: true
    });
    mesh = new THREE.Mesh(geometry,material);
    mesh.rotation.x = -0.05;

    scene.add(mesh);
}

function resize() {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
}

function render() {
    mesh.rotation.x += 0.005; mesh.rotation.y += 0.005;
    requestAnimationFrame( render );
    renderer.render( scene, camera );
}

init(); render();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

<canvas id="myCanvas"></canvas>

Answer №2

It is recommended to utilize the following scripts:

<script src="Detector.js"></script>
<script src="OrbitControls.js"></script>

Subsequently, add the following code:

controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;

Furthermore, ensure that your camera is correctly configured, for example:

camera.position.set(0, 0, 40);

It is advisable to break down the code into sections and then call them at the end.

document.addEventListener('DOMContentLoaded', function(event) {
init();
initLight();
animate();
requestAnimationFrame(render);
controls.update(); 
});

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

Babel transpilation results in: SyntaxError - Unforeseen token discovered at line 38, position

I've recently started working with Node and React, and I encountered an error while trying to build in Babel for uploading the server.js and react client to Heroku. While everything works perfectly fine in Postman, I'm unable to upload it to Her ...

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...

The Autocomplete feature in Material UI React includes both a "Select All" and a "Select

How can I add Select All and Select None buttons to an Autocomplete component in Material UI React? The goal is for all the options to be checked when Select All is clicked, and for all options to be unchecked when Select None is clicked. <Autocomple ...

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

Deactivate all functions of a complete row in the table

I'm working with a table that contains various user interaction controls in its cells, such as buttons and links. I'm looking to gray out certain rows of the table so that all operations related to those rows are disabled. Does anyone have sugge ...

What is the best way to halt an animation after a certain period of

Experimenting with the snow-fall animation and aiming to stop it after 5 seconds. Added animate within setTimeOut but no effect observed. What could be missing here? Here's the current code: function fallingSnow() { var snowflake; snowflake = ...

New options for outdated Webpack i18n plugin and loader

I am currently working on a TypeScript project that requires loading translations from individual .json files assigned to each country. For instance, we would have separate language files like en.json, es.json. The goal is to be able to access these trans ...

Can PDO prepared statements provide sufficient protection against SQL injection?

Is relying solely on PDO prepared statements enough to secure against MySQL-related security risks, or is it necessary to also perform server-side character validation? I am currently using PDO prepared statements and client-side JavaScript form checking, ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

Implementing Preloader: Combining NProgress.js with ember.js and utilizing ember data

While working on implementing the NProgress.js progress bar JQuery library with Ember.js to load data from the server, I successfully used JQuery post in Ember. However, I encountered difficulties in implementing it using Ember Data when loading data throu ...

What is the best way to retrieve a row in ui-grid using data from a specific column?

I am currently utilizing the ui-grid feature provided by . I have been experimenting with various methods, but due to my recent introduction to Angular, I find the documentation quite perplexing. I have implemented a custom search tag system and my goal i ...

The datetime picker does not have a default value specified

I've been attempting to configure a default value in my bootstrap datetimepicker, but it doesn't seem to be working as intended. var fromDate = "2022-08-24T11:24:00"; $('#inputFromDate').datetimepicker({ format: 'DD/M ...

Addressing the problem of refactoring in JavaScript when associating arguments with keys in MongoDB

I am facing a dilemma with two functions that are almost identical except for the value being set as indicated: function extracted_start(details, txt) { return FutureTasks.upsert({ number: details.number ...

What is the best way to ensure that my position on the page remains fixed during an auto-refresh triggered by a PHP

I am seeking help with incorporating AJAX into my website. I want users to be able to maintain a list of Magic game cards on the site, where they can add cards by pressing a button. However, each time a card is added, the page refreshes and the new card ap ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

Having trouble with Bootstrap-tour and Bootstrap 4 alpha 6? It seems like n.popover is not functioning properly

Attempting to integrate bootstrap-tour with bootstrap 4 and encountering the following error: Type Error: n.popover is not a function The code initialization looks like this: var tour = new Tour({ steps: [ { ...

What is the best way to retrieve declared functions within the done() scope of a jQuery plugin that handles JSON requests?

As I work on a jQuery plugin, my goal is to make it easily configurable and maintainable. To achieve this, I am focusing on keeping the functions short and testable. To accomplish this, I am implementing jQuery plugin code inspired by Addy Osmani's L ...

Passing form data to a different route using express

I need to send the data from this form, located on the index.ejs page, to another page "/rentingForm" for rendering at the "rentingForm" page. Here is the snippet of code from my app.js file: app.use(bodyParser.urlencoded({ extended: true })); app.use( bo ...

Upon page load, the opencart div tab content fails to display

I'm currently using an opencart template, and I'm attempting to display some data from a MySQL table in a div tab. Initially, everything works fine. However, when I reload the browser, it doesn't display the default current div with the MySQ ...

What is the method for incorporating locales into getStaticPaths in Next.js?

I am currently utilizing Strapi as a CMS and dealing with querying for slugs. My goal is to generate static pages using getStaticPaths and getStaticProps in Next.js. Since I'm working with multiple locales, I have to iterate through the locales to re ...