我想在拖動 lil gui 滑塊時更改圓圈的大小。我有這段代碼,它在黑屏上用一個藍線畫了一個圓圈,帶有一個正交相機:
initGUI();
let radius = 0.6;
let vertices = [];
for(let i = 0; i <= 360; i ){
vertices.push(new THREE.Vector3(Math.sin(i*(Math.PI/180))*radius, Math.cos(i*(Math.PI/180))*radius, 0));
}
let geometry = new THREE.BufferGeometry().setFromPoints(vertices);
let material = new THREE.LineBasicMaterial({color:"blue"})
var lineStrip = new THREE.Line( geometry, material );
我也有這個 initGUI() 函式,它可以制作一張幻燈片來改變 controls.radius 的值
function initGUI() {
controls = { radius : 0.6
};
gui.add( controls, 'radius', 0.1, 0.7).onChange(value => changeRadius(value));
gui.open();
};
onChange 方法將半徑的新值發送給函式 changeRadius,即:
function changeRadius(value) {
radius = value;
var vertices = [];
for(let i = 0; i <= 360; i ){
vertices.push(new THREE.Vector3(Math.sin(i*(Math.PI/180))*radius, Math.cos(i*(Math.PI/180))*radius, 0));
}
renderer.clear();
renderer.render(scene, camera);
}
但是,這不起作用。它會產生錯誤“未定義渲染器”。我嘗試將渲染器作為函式引數傳遞,然后它給出了類似于“未定義場景和相機”的內容,然后我還將場景和相機設定為函式的引數并且沒有產生錯誤,但是圓圈沒有改變它的大小。
uj5u.com熱心網友回復:
除了@prisoner849 的建議(意思是創建半徑為 1 的圓,然后縮放它),您可以使用下面的代碼片段來更新幾何圖形。我想這就是你最初的想法。
import * as THREE from 'three';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
let camera, scene, renderer;
let lineStrip;
const params = {
radius: 0.6
};
init();
render();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
const radius = params.radius;
const vertices = [];
for ( let i = 0; i <= 360; i ) {
vertices.push( new THREE.Vector3( Math.sin( i * ( Math.PI / 180 ) ) * radius, Math.cos( i * ( Math.PI / 180 ) ) * radius, 0 ) );
}
const geometry = new THREE.BufferGeometry().setFromPoints( vertices );
const material = new THREE.LineBasicMaterial( { color: 'blue' } );
lineStrip = new THREE.Line( geometry, material );
scene.add( lineStrip );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const gui = new GUI( { width: 300 } );
gui.add( params, 'radius', 0.1, 2 ).onChange( changeRadius );
gui.open();
}
function render() {
renderer.render( scene, camera );
}
function changeRadius() {
const positionAttribute = lineStrip.geometry.getAttribute( 'position' );
const radius = params.radius;
for ( let i = 0; i <= 360; i ) {
const x = Math.sin( i * ( Math.PI / 180 ) ) * radius;
const y = Math.cos( i * ( Math.PI / 180 ) ) * radius;
const z = 0;
positionAttribute.setXYZ( i, x, y, z );
}
positionAttribute.needsUpdate = true;
render();
}
vertices注意更新陣列是不夠的。您必須改為更新緩沖區屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519342.html
下一篇:按鈕不斷出現并重新出現
