Swapping out meshes on the fly using three.js動态替换单个网格与

I have a unique idea for a breakout game where the paddle is shaped like a piece of roof trim, with its shape changing based on the pitch of the roof. Hitting special bricks will alter the pitch variable, thus changing the "steepness" of the paddle. However, I am facing an issue where every time a pitch change occurs, a new paddle is drawn on the screen but the old one remains. As a result, multiple paddles with varying pitches end up cluttering the screen after hitting multiple special bricks.

//Innovative breakout game with dynamic paddle shape

var gridSize=50;
var geometry;
var extrudeSettings;
var startPitch = 1;
var pitch  = startPitch;
var pitchChange = false;
var paddle;
var paddleWidth = run*2;
var paddleX = 0;
var paddleLineThickness = .5;
var paddleMat = new THREE.MeshLambertMaterial({color: "purple"});
var paddleShape = new THREE.Shape();
var side = 10;
var pi = Math.PI;


function definePaddleShape() {
    roofAngle = Math.atan(pitch/12);
    rise = side*Math.sin(roofAngle);
    run = side*Math.cos(roofAngle);
    paddleWidth = run*2;
    paddleShape.moveTo(  -run, 0 );
    paddleShape.lineTo(  -run, paddleLineThickness );
    paddleShape.lineTo(0, rise + paddleLineThickness );
    paddleShape.lineTo( run, paddleLineThickness );
    paddleShape.lineTo(  run, 0 );
    paddleShape.lineTo(  0, rise );
    extrudeSettings = {amount:4, steps: 1, bevelSegments:0, bevelSize:0, bevelThickness:0};
}

function drawPaddle() {
    geometry = new THREE.ExtrudeGeometry(paddleShape, extrudeSettings);
    paddle = new THREE.Mesh(geometry, paddleMat);
    paddle.castShadow = true;
    scene.add(paddle);
    paddle.rotateX(-pi/2);
    paddle.translateY(-gridSize);
    paddle.translateX(paddleX);
}


function draw() {
    requestAnimationFrame(draw);

// pitch gets changed when a collision 
// between ball and special brick occurs
// sets pitchChange to true

    if(pitchChange) {
        scene.remove(paddle);
        definePaddleShape();
        drawPaddle();
        pitchChange = false;
            }


       renderer.render(scene, camera);
}


definePaddleShape();
drawPaddle();
document.addEventListener("mousemove", mouseMoveHandler, false);
draw();

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

Answer №1

To start, you can set up the mesh for your paddle in the init() function. Then, in the drawPaddle() function, all you need to do is update the paddle's geometry:

function drawPaddle() {
    geometry = new THREE.ExtrudeGeometry(paddleShape, extrudeSettings);
    geometry.rotateX(-pi/2);
    //
    paddle.geometry.dispose();
    paddle.geometry = geometry;
    //
    paddle.castShadow = true;
    //scene.add(paddle); // not necessary since the paddle mesh is already added in init()
    paddle.translateY(-gridSize);
    paddle.translateX(paddleX);
}

This approach is commonly used for demonstrating geometries on threejs.org

Here is an example on jsfiddle

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

What is the method for determining the required or imported base path?

My package.json includes the main option to set the default file for importing like import 'my-index' from 'my-module' However, I would like to break up my-module into separate files so developers can include them individually with sta ...

Highlighting an Element Using Selenium Webdriver at Specific Coordinates

I'm currently in the process of automating a web application built with HTML5 using Selenium Webdriver. I need help figuring out how to highlight the exact coordinates where I have clicked on the Canvas element. For example, if I click on the Canvas a ...

Pass the pre-encoded value through Ajax

Is there a way to prevent AJAX from encoding an already encoded value when passing it through data? I'm facing this issue where my value gets further encoded. Any solutions? This is the AJAX code I'm using: $.ajax({ url: form.attr(" ...

How can we effectively create reusable modals in React with the most efficient approach?

Currently, I am developing an application using React and Material UI. In order to streamline the use of Modals across multiple pages, I have implemented a global modal context that dynamically populates the modal with different props based on state change ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Retrieving the URL of an image from a webpage's photo gallery utilizing the Facebook Graph API with the help of Javascript

After trying out multiple tutorials, it appears that the latest version of the Graph API has caused some issues with my code. Here is the snippet I am working with: function fetchAlbumImages(){ FB.api( '/760126260690750/photos&ap ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...

Strategies for restricting user input within a datalist

I have a project in which I am creating a webpage that displays a list of flights that can be filtered by destination, origin, price, and more. To achieve this, I have categorized each flight within a div element using its specific properties as classes. F ...

Guide to organizing elements in an array within a separate array

Our array consists of various items: const array = [object1, object2, ...] The structure of each item is defined as follows: type Item = { id: number; title: string contact: { id: number; name: string; }; project: { id: number; n ...

Strategies for Repurposing local file.js across multiple Vue projects

I have a file called myfile.js with functions that I want to reuse in multiple vue projects, specifically within the App.vue file. Here is the file structure: -- projec1 ---- src ------ App.vue -- project2 ---- src ------ App.vue -- myfile.js Directly ...

What is the reason behind the android code being incompatible with IOS operating systems?

I'm encountering an issue where a particular code is working on Android, but not on IOS. The code in question involves using JavaScript to differentiate the items in a list within an HTML select tag. It's perplexing to me how the code can operat ...

In Chrome, it seems like every alternate ajax request is dragging on for ten times longer than usual

I've been running into an issue with sending multiple http requests using JavaScript. In Chrome, the first request consistently takes around 30ms while the second request jumps up to 300ms. From then on, subsequent requests alternate between these two ...

Troubleshooting problem with Electron and sqlite3 post application packaging

I've been facing various challenges with Node and databases lately, hence the numerous questions I've posted here recently. Here's some background: I have an Electron app with an AngularJS frontend. On the electron side, I run an express s ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

Syntax highlighting in custom blocks with VueJS

Vue single file components allow for the creation of custom blocks (besides the commonly used script, template, and style). For more information, you can refer to the official documentation here: . However, I am struggling to enable syntax highlighting w ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

How can I disable a checkbox in AngularJS?

Is there a way to automatically disable a checkbox when selecting an item from the combo box? For example, if "ABONE" is selected, Angular should disable the ABONE checkbox. Note (for example): DefinitionType: ABONE https://i.sstatic.net/vcZpR.png ...