标签:event ddc cts doc 点击 函数 position 目标 height
OrbitControls
// 点击功能
let raycaster = null
let instersected = null
let mouse = null
let useClick = false
/**
* 打开addClick函数再执行addWran点击动画
*/
function addClick() {
console.log(‘执行了addClick‘)
mouse = new THREE.Vector2()
var onDocumentMouseDown = function (e) {
console.log(e)
}
let mainCanvas = document.getElementById(‘myCanvas‘)
var onDocumentMouseUp = function (event) {
useClick = true // 当点击界面后再执行变红
console.log(‘点击了‘)
event.preventDefault()
// getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性
// 屏幕坐标转标准设备坐标
mouse.x =
((event.clientX - mainCanvas.getBoundingClientRect().left) /
mainCanvas.offsetWidth) *
2 -
1 // 标准设备横坐标
// 这里的mainCanvas是个dom元素,getBoundingClientRectangle会返回当前元素的视口大小.
mouse.y =
-(
(event.clientY - mainCanvas.getBoundingClientRect().top) /
mainCanvas.offsetHeight
) *
2 +
1 // 标准设备纵坐标
}
raycaster = new THREE.Raycaster()
document.addEventListener(‘pointerup‘, onDocumentMouseUp, false) // 交互
document.addEventListener(‘pointerdown‘, onDocumentMouseDown, false) // 交互
}
// 添加点击点谁谁变红事件
function addWranAnimate() {
if (!mouse || !useClick) {
return console.log(‘需要先打开addClick函数再执行addWran点击动画‘)
}
let standardVector = new THREE.Vector3(mouse.x, mouse.y, 1) // 标准设备坐标
// 标准设备坐标转世界坐标
let worldVector = standardVector.unproject(camera)
// 射线投射方向单位向量(worldVector坐标减相机位置坐标)
let ray = worldVector.sub(camera.position).normalize()
// 创建射线投射器对象
let rayCaster = new THREE.Raycaster(camera.position, ray)
// 返回射线选中的对象 第二个参数如果不填 默认是false
let intersects = rayCaster.intersectObjects(scene.children, true)
// 点谁谁变红----------------------点谁谁变红----------------------点谁谁变红
if (intersects.length > 0) {
// console.log(‘intersects‘)
// console.log(intersects)
if (instersected !== intersects[0].object) {
if (instersected) {
instersected.material.color.setHex(instersected.currentHex)
}
instersected = intersects[0].object
instersected.currentHex = instersected.material.color.getHex()
instersected.material.color.set(0xff0000)
}
} else {
if (instersected) {
instersected.material.color.set(instersected.currentHex)
}
instersected = null
}
// 点谁谁变红----------------------点谁谁变红----------------------点谁谁变红
}
three.js中,绑定 mouseup 和 mousedown 事件不起作用/使用three.js实现点谁谁变红,已解决鼠标选不到目标问题
标签:event ddc cts doc 点击 函数 position 目标 height
原文地址:https://www.cnblogs.com/sugartang/p/14388072.html