threejs中PC与手机操作的一些总结
? ? ? ? 在一些簡單的webgl項目中,我們經(jīng)常碰到的操作就是兩指縮放,滑動旋轉(zhuǎn),這兩種操作經(jīng)常要進(jìn)行PC和手機(jī)的適配,這里總結(jié)一下我踩了的一些小小的坑吧~
? ? ? ? 1.手機(jī)與PC獲取屏幕對應(yīng)點擊位置的方法不同:
? ? ? ? 手機(jī)是觸摸獲取位置,PC是點擊鼠標(biāo)獲取位置兩者的代碼略有不同,這與threejs構(gòu)建的3D世界沒有關(guān)系,僅僅是將點擊/觸摸的位置轉(zhuǎn)換為窗體位置罷了,我在下面總結(jié)一下:
? ? ? ? PC點擊位置:
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; ? ? ? ? 手機(jī)觸摸位置:
mouse.x = (event.touches[ 0 ].pageX / window.innerWidth) * 2 -1; mouse.y = -(event.touches[ 0 ].pageY / window.innerHeight) *2 +1; ? ? ? ? 2.手機(jī)和電腦移動方式的不同:
? ? ? ? 大家都知道,鼠標(biāo)和觸摸都分為點擊/按下、移動/滑動、抬起這三個階段,這里就有一個小坑了!點擊抬起手機(jī)電腦的操作方式都是一樣的,但是移動這塊,電腦中鼠標(biāo)點擊之后到下次點擊鼠標(biāo)的移動會不斷觸發(fā)onDocumentMouseMove方法,也就是說鼠標(biāo)不可能點擊(0,0)位置,突然下一次移動到(10,10)位置,因為期間還有一個鼠標(biāo)移動事件不斷地觸發(fā)。而手機(jī)則不同,這次你點擊了(0,0)下次點擊(10,10)就在正常不過了,我們也不需要手指在屏幕上進(jìn)行滑動。那是這些有什么用呢?
? ? ? ? 這里就不得不提到我最近做的一個小的程序,用threejs實現(xiàn)3D地球展示,當(dāng)手指滑動/鼠標(biāo)拖動時旋轉(zhuǎn)地球,我用的方法是,每次移動獲得x/y的值,減去上次移動的值,得到這次滑動的偏移量然后旋轉(zhuǎn)地球,這個效果在PC上沒有任何問題,可是到了手機(jī)上,每次滑動完屏幕,下次滑動時地球又嗖的一下跳回去了,然后我想了半天才發(fā)現(xiàn)是這個原因,手機(jī)在滑動完成之后,下一次滑動點擊位置不同,x/y的差值太大了,所以需要在每次點擊時就先儲存到上次移動的值~下面是代碼
function onDocumentMouseDown( event ) {is_click = true; is_move = false; //適配手機(jī) if(event.touches){mouse.x = (event.touches[ 0 ].pageX / window.innerWidth) * 2 -1; mouse.y = -(event.touches[ 0 ].pageY / window.innerHeight) *2 +1; pre_mouse.x = mouse.x; pre_mouse.y = mouse.y; }}function onDocumentMouseMove( event ) {is_move = true; mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; if(is_click){if(earth && earth_cloud){earth.rotation.set(earth.rotation.x - (mouse.y - pre_mouse.y), earth.rotation.y + (mouse.x - pre_mouse.x), earth.rotation.z); earth_cloud.rotation.set(earth_cloud.rotation.x - (mouse.y - pre_mouse.y), earth_cloud.rotation.y + (mouse.x - pre_mouse.x), earth_cloud.rotation.z); }}pre_mouse.x = mouse.x; pre_mouse.y = mouse.y; }function onDocumentTouchMove() {is_move = true; mouse.x = (event.touches[ 0 ].pageX / window.innerWidth) * 2 -1; mouse.y = -(event.touches[ 0 ].pageY / window.innerHeight) *2 +1; if(is_click){if(earth && earth_cloud){earth.rotation.set(earth.rotation.x - (mouse.y - pre_mouse.y), earth.rotation.y + (mouse.x - pre_mouse.x), earth.rotation.z); earth_cloud.rotation.set(earth_cloud.rotation.x - (mouse.y - pre_mouse.y), earth_cloud.rotation.y + (mouse.x - pre_mouse.x), earth_cloud.rotation.z); }}pre_mouse.x = mouse.x; pre_mouse.y = mouse.y; } ? ? ? ? 先總結(jié)這兩個坑~大家在開發(fā)中遇到什么問題也可以在評論中指出,多交流,多學(xué)習(xí)才有助于提高嘛~
總結(jié)
以上是生活随笔為你收集整理的threejs中PC与手机操作的一些总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我要dz插件
- 下一篇: iOS中调用短信和邮箱的方法