Using ThreeJs to create interactive 3D objects with button-controlled movement

Currently, I'm diving into the world of Three.js and I have a fascinating project in mind. I want to create movement buttons that will control the position of a sphere object. Through some research, I found out that I can use the onclick function on button elements, but I am unsure about how to define the 3D sphere object for the movement functions.

function moveup() {
    sphere.translateZ -= 1; 
}

function movedown() {
    sphere.translateZ += 1; 
}

function moveleft() {
    sphere.translate.X -= 1; 
    
}

function moveright() {
    sphere.translate.X += 1; 
}

The code snippet above shows the functions I plan to use for moving the sphere with the buttons. However, my struggle lies in defining the 3D sphere object within this context. Any tips or guidance on this matter would be greatly appreciated!

Answer №1

To achieve this functionality, I've written the following code. Firstly, you'll need a scene, camera, and renderer to interact with objects and navigate using HTML buttons for movement:

In Index.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StackOverflow</title>
    <link rel="stylesheet" href="./style.css"></link>
  
   
</head>
<body>
    <script src="../libs/three.js"></script>
    <script  src="../libs/three.min.js"></script>
    <script src="../libs/OrbitControls.js"></script>
    <section class="container">   

      <ul class="sidebar">
        <li class="sidebar__item"><button class="sidebar__button" onclick="moveUp()">up</button></li>
        <li class="sidebar__item"><button class="sidebar__button" onclick="moveDown()">down</button></li>
        <li class="sidebar__item"><button class="sidebar__button" onclick="moveRight()">Right</button></li>
        <li class="sidebar__item"><button class="sidebar__button" onclick="moveLeft()">Left</button></li>
      </ul>

      <canvas class="webgl"></canvas>
      
      </section>
      <script src="./main.js"></script>


</body>
</html>

In main.js :

/**
 * Base
 */
// Canvas
const canvas = document.querySelector('canvas.webgl')


// Sizes
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

// Scene
const scene = new THREE.Scene()


// Camera
const camera = new THREE.PerspectiveCamera(45, sizes.width / sizes.height, 0.01, 1000)
camera.position.set( 0, 10, 10 );
camera.lookAt( 0, 0, 0 );
scene.add(camera)

// Controls
const controls = new THREE.OrbitControls(camera, canvas)
controls.enableDamping = true

// Renderer
const renderer = new THREE.WebGLRenderer({
    antialias: true,
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio,2))


renderer.setClearColor( 0x404040, 1);

//Create Mesh 

const mesh = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1, 5, 5, 5),
    new THREE.MeshBasicMaterial({ color: 0xff0000 })
)

scene.add(mesh)


var increment =1;

function moveUp()
{
    mesh.position.y +=increment;


}

function moveDown()
{
    mesh.position.y -= increment;

    
}
function moveRight()
{
    mesh.position.x +=increment;

}
function moveLeft()
{
    mesh.position.x -= increment;

}


const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // mesh.rotation.y +=0.01

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

In style.css:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  overflow: hidden;
}
.container{
  position: relative;
}


.webgl {
  outline: none;
}
.sidebar{
  position: absolute;
  z-index: 10;
  height: 100%;
  background-color: #333;
}
.sidebar__item{
  height: 40px;
  width: 40px;
  border-bottom:1px solid rgb(179, 179, 179);
}
.sidebar__button{
  width: 100%;
  height: 100%;
  background: #333;
    outline: none;
    border: 0;
    color: #ddd;
    font: bold;
    font-size: large;
}

.sidebar__button:hover {
  background-color: #888;
  color: black;
  
}
.sidebar__button:active {
  background-color: #aaa;
  color: black;
  
}

https://i.sstatic.net/asWaK.gif

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

Manipulate elements by adding and removing classes sequentially based on an array

Previously, some had difficulty understanding my question. I have an array of variables representing the ids of 5 divs. My goal is to change the color of each div sequentially for a brief moment before reverting back, mimicking the behavior of traffic ligh ...

Loading articles seamlessly in Yii using Ajax

I am currently working on a project where I need to display articles from databases, but every time an article is viewed, the whole page reloads. I would like to load articles without having to reload the page, and I believe this can be achieved using Ajax ...

Eliminating divs and preserving content

Is there a way to remove certain DIV elements using jQuery or pure JavaScript without affecting the content within them? Here is an example structure: <div class="whatever_name"> <div class="whatever_name"> <h2>subtitle</h2&g ...

What is an alternative method for transferring data between components in React without directly invoking the target component?

I am facing a challenge in sending the room.id data from Homepage.js component to Player.js component. The use of PrivateRouter component in App.js has made it difficult for me to directly call the component while routing the route with Link. homepage.js ...

Click on the dropdown item in the Bootstrap btn-group dropdown

I am interested in clicking the dropdown item within the btn-group and triggering an alert message. This is the HTML code I have: <td> <div class="btn-group" role="group"> <button id="btnGroupVerticalDrop2" type="button" class= ...

What is causing the malfunction in jQuery version 1.7.x?

Here is a code snippet demonstrating the issue I am facing: var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append( $('<span>span</span>& ...

When attempting to call a script function in PHP and expecting a return value, an error was encountered: "Uncaught SyntaxError

My functions are working fine: <script> function createCookie(name,value,sec) { if (sec) { console.log('createCookie: '+name+', '+value+', '+sec); var date = new Date(); date.setTime(date.getTime()+(sec*1000 ...

Suggestions for updating ng-repeat variable with autocomplete functionality?

Many thanks to the Stack Overflow community for helping me resolve my previous angularjs and autocomplete issue. Here is the link to the question: Angularjs with jquery auto complete not working However, I am facing a similar problem now within the ng-rep ...

Navigating through props outside a class component in React

I'm struggling to grasp how I can access props that are defined outside of a React class component. In the code snippet below, all props are clearly outlined except for this.props.checkboxArray, which is currently throwing an error "cannot read prope ...

Protractor successfully opens Firefox, however no URL is loaded. Chrome, on the other hand, functions perfectly

Every time I attempt to execute my protractor tests on Firefox, the browser opens but no URL is loaded. Eventually, an error message appears in the command prompt: Using FirefoxDriver directly... [launcher] Running 1 instances of WebDriver ERROR - Unabl ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Incorporating middleware to handle 404 errors in Express

scenario app.use("/api/tobaccos", tobaccos); app.use(function(err, req, res, next) { console.error(err.message); }); API details: router.get("/:id", async (req, res) => { console.log("GET TOBACCO:" + req.params.id); ...

Simple chart with four sections in DimpleJS (D3)

Recently I decided to give DimpleJS a try for the first time with hopes of creating something like this: However, I seem to have run into some trouble. No matter what I do, nothing appears on the screen. http://jsbin.com/xosehedejo/1/edit window.onloa ...

How can the background color be shown using a transparent PNG on material?

I'm currently developing a case builder using THREE.js, where I aim to adjust the height/width/length of a box, rotate it, and modify its background color. To see my progress so far, visit: I have successfully implemented dimension changes and box m ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...

Display the tooltip only when the checkbox is disabled in AngularJS

My current setup includes a checkbox that is disabled based on a scope variable in Angular. If the scope variable is true, the checkbox stays disabled. However, if the scope variable is false, the checkbox becomes enabled. I am looking to implement a too ...