今日嘗試根據建立好的夾爪剛體將利用 Tween.js 動畫將物件抓起,做到類似夾娃娃機的效果
在 ejs 處加入按鈕
<button id="gripper_btn" style="height:50px;width:100px;font-size:30px" onclick="click_Gripper()">Grip</button>
建立 tween.js 動畫,分為夾爪向下,夾取,向上,三種動畫
設定夾爪向下、夾取、向上時目標位置
initR_x = gripperRBody.position.x
initR_z = gripperRBody.position.z
initR_y = gripperRBody.position.y
initL_x = gripperLBody.position.x
initL_z = gripperLBody.position.z
initL_y = gripperLBody.position.y
// R
let offsetR = {x:initR_x,z:initR_z,y:initR_y}
let DownTargetR = {x:initR_x,z:initR_z,y:initR_y-4.5}
let MoveTargetR = {x:initR_x-0.65,z:initR_z,y:initR_y-4.5}
let UpTargetR = {x:initR_x-0.65,z:initR_z,y:initR_y}
let OriginR = {x:gripperR_init_x-0.65,z:gripperR_init_z,y:gripperR_init_y}
let ReleaseTargetR = {x:gripperR_init_x,z:gripperR_init_z,y:gripperR_init_y}
// L
let offsetL= {x:initL_x,z:initL_z,y:initL_y}
let DownTargetL = {x:initL_x,z:initL_z,y:initL_y-4.5}
let MoveTargetL = {x:initL_x+0.65,z:initL_z,y:initL_y-4.5}
let UpTargetL = {x:initL_x+0.65,z:initL_z,y:initL_y}
let OriginL = {x:gripperL_init_x+0.65,z:gripperL_init_z,y:gripperL_init_y}
let ReleaseTargetL = {x:gripperL_init_x,z:gripperL_init_z,y:gripperL_init_y}
建立夾爪向下動畫
const DownR=()=>{
gripperRBody.position.y = offsetR.y
}
tweenDownR = new TWEEN.Tween(offsetR)
.to(DownTargetR,1800)
.easing(TWEEN.Easing.Quintic.Out)
.onUpdate(DownR)
.onComplete(()=>{
console.log("downR")
})
const DownL=()=>{
gripperLBody.position.y = offsetL.y
}
tweenDownL = new TWEEN.Tween(offsetL)
.to(DownTargetL,1800)
.easing(TWEEN.Easing.Quintic.Out)
.onUpdate(DownL)
.onComplete(()=>{
console.log("downL")
})
建立夾爪夾取動畫
const MoveR=()=>{
gripperRBody.position.x = DownTargetR.x
}
tweenMoveR = new TWEEN.Tween(DownTargetR)
.to(MoveTargetR,1500)
.easing(TWEEN.Easing.Quintic.Out)
.onUpdate(MoveR)
.onComplete(()=>{
console.log("moveR")
})
const MoveL=()=>{
gripperLBody.position.x = DownTargetL.x
}
tweenMoveL = new TWEEN.Tween(DownTargetL)
.to(MoveTargetL,1500)
.easing(TWEEN.Easing.Quintic.Out)
.onUpdate(MoveL)
.onComplete(()=>{
console.log("moveL")
})
建立夾爪向上動畫
tweenUpR = new TWEEN.Tween(MoveTargetR)
.to(UpTargetR,2500)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(UpR)
.onComplete(()=>{
console.log("UpR")
})
const UpL=()=>{
gripperLBody.position.y = MoveTargetL.y
}
tweenUpL = new TWEEN.Tween(MoveTargetL)
.to(UpTargetL,2500)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(UpL)
.onComplete(()=>{
console.log("UpL")
})
將三種動畫串接在一起
tweenDownR.start()
tweenDownR.chain(tweenMoveR)
tweenMoveR.chain(tweenUpR)
tweenDownL.start()
tweenDownL.chain(tweenMoveL)
tweenMoveL.chain(tweenUpL)
建立完後 render() 處記得也要調用 tween.js 功能
function render() {
\\\
TWEEN.update()
\\\
}
Day22 Demo | Github
按下 gripper 夾起物體
實際上夾取剛體樣子