三.js检测点击一个对象与光线投射不起作用



我尝试用光线投射器检测Three.js对象上的点击,但没有检测到任何碰撞。我使用Angular,下面是我的代码:

@Component({
selector: 'app-viewer-3d',
templateUrl: './viewer3d.component.html',
styleUrls: ['./viewer3d.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Viewer3dComponent implements OnInit, DoCheck {
pickPosition = {x: 0, y: 0};
scene = new THREE.Scene();
pickedObject;
raycaster = new THREE.Raycaster();
ngDoCheck() {
this.cameraState.emit(JSON.stringify(this.camera.matrix.toArray()));
console.log(this.pickPosition);
this.raycaster.setFromCamera(this.pickPosition, this.camera);
const intersectedObjects = this.raycaster.intersectObjects(this.scene.children);
if (intersectedObjects.length) {
if (this.pickedObject !== intersectedObjects[0].object) {
// console.log(this.pickedObject);
this.pickedObject = intersectedObjects[0].object;
}
console.log(this.pickedObject);
} else {
this.pickedObject = null;
console.log('NULL');
}
}
@HostListener('window:mouseout')
@HostListener('window:mouseleave')
clearPickPosition() {
this.pickPosition.x = -100000;
this.pickPosition.y = -100000;
// console.log(this.pickPosition);
}
@HostListener('window:mousemove', ['$event'])
setPickPosition(event) {
const pos = this.getCanvasRelativePosition(event);
this.pickPosition.x = (pos.x / this.canvas.width) * 2 - 1;
this.pickPosition.y = (pos.y / this.canvas.height) * -2 + 1;  // note we flip Y
// console.log(this.pickPosition);
}
getCanvasRelativePosition(event) {
const rect = this.canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * this.canvas.width / rect.width,
y: (event.clientY - rect.top) * this.canvas.height / rect.height,
};
}
}

在我的控制台中,当我移动鼠标时,y和x介于-1和1之间,但它总是打印NULL。所以,intersectedObjects。长度= 0.

你有什么想法吗?

提前感谢

raycaster.intersectObjects( this.scene.children, true );

相关内容

最新更新