发生单击时显示和隐藏GUI的最佳方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发生单击时显示和隐藏GUI的最佳方法相关的知识,希望对你有一定的参考价值。
我希望dat.GUI()实例在网格内部发生单击时出现,并且再次单击时消失。显然,当它被重新单击时,我想重新包装。我尝试了许多不同的操作,但无法获得想要的行为...
例如,小鸡这段代码:
function onDocumentMouseClick(event) //if we detect a click event
{
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
event.preventDefault();
// update the mouse variable
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// calculate objects intersecting the picking ray
var intersects = raycaster.intersectObjects( scene.children );
//if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
{
isClicked = true;
cube.material.color.set( 0xF7F7F7 );
var params = {
textField: "Enter value:"
}
var item = gui.add(params, "textField").onFinishChange(function (value) {
//Do something with the new value
console.log(value);
});
}
//if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
{
isClicked = false;
cube.material.color.set( cube.userData.originalColor );
dat.GUI.toggleHide();
//gui.toggleHide()
}
}
现在,当我单击网格时,将创建GUi,当我重新单击它时,将失去作用,但是当我再次单击时,会发生奇怪的事情。
有时隐藏按钮不起作用,但最终我得到了许多不同的GUI,我只想要一个。
并且可以选择使其显示/消失。
答案
您可以这样操作:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
params = {
zAxis: "1"
}
var gui = new dat.GUI();
gui.add(params, "zAxis").onFinishChange(val => {
cube.scale.z = parseFloat(val);
});
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var intersects;
window.addEventListener("click", event => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
intersects = raycaster.intersectObject(cube);
if (intersects.length > 0) {
let vis = gui.domElement.style.visibility;
gui.domElement.style.visibility = vis == "" ? "hidden" : "";
}
});
var animate = function() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/libs/dat.gui.min.js"></script>
以上是关于发生单击时显示和隐藏GUI的最佳方法的主要内容,如果未能解决你的问题,请参考以下文章