[英]How to draw a geometry shape exactly where mouse is clicked in ThreeJS
我正在嘗試在單擊鼠標的位置准確地繪制一個圓圈,但在 position 處繪制的圓圈並不准確。 請讓我知道代碼中需要更正的內容:
var camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 0, 0, 1000 );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {
event.preventDefault();
if( event.which == 1) { // left mouse click
// x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
// y = - ( event.clientY / renderer.domElement.clientWidth ) * 2 + 1;
var x = event.clientX; // x coordinate of a mouse pointer
var y = event.clientY; // y coordinate of a mouse pointer
var rect = event.target.getBoundingClientRect();
x = ((x - rect.left) - window.innerWidth/2)/(window.innerWidth/2);
y = (window.innerHeight/2 - (y - rect.top))/(window.innerHeight/2);
var geometry = new THREE.CircleGeometry( 20, 32 );
var material = new THREE.MeshBasicMaterial( { color: 0x65A8FF } );
circle = new THREE.Mesh( geometry, material );
//circle.position.x = x*window.innerWidth*1.23;
//circle.position.y = y*765;
circle.position.x = x*window.innerWidth;
circle.position.y = y*window.innerHeight;
scene.add( circle );
}
}
您的方法的問題在於它假設 3D xy
坐標連接到像素坐標,而不考慮相機的視角或深度。 使用透視相機,點越深,它的 x、y 坐標就越大。 您需要為要停止的點設置深度 (z)。 此外,如果您的相機移動或旋轉,您的X, Y
坐標將不起作用。
我建議您使用THREE.Raycaster
,它會為您執行所有這些相機投影計算(文檔在頁面頂部有一個使用示例)。 您可以在此示例中看到該方法的實際效果。
它的工作方式是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.