问题
该文中Laya版本 : 1.7.15
文中代码 : TypeScript 5.6.0
在使用Laya开发时突然发现Laya自带的动画控制器死活不能控制3D对象,找了半天最后发现官网并不支持使用Laya.tween控制3D对象,于是自己写了一个简单的3D动画控制工具,支持使用Laya自带的所有缓动效果。
解决方案
源码
class Sprite3DMoveContorller{
frompostion : Laya.Vector3;
topostion : Laya.Vector3;
moveDistance : Laya.Vector3;
moveObjcet : Laya.Sprite3D;
moveTime : number = 0;
moveValue : number = 0;
/**
* Sprite3D移动方法
* @param gameObject 需要移动的3D对象
* @param toPos 移动目标点
* @param playTime 移动总耗时
* @param easeFun 缓动函数 (Laya.Ease) 默认为线性移动
* @param obj 回调域
* @param callback 回调函数
*/
public onPositionMoveTo(gameObject : Laya.Sprite3D , toPos : Laya.Vector3 , playTime : number , easeFun : Function , obj : any = null , callback : Function = null){
this.moveDistance = new Laya.Vector3(toPos.x - gameObject.transform.position.x , toPos.y - gameObject.transform.position.y, toPos.z - gameObject.transform.position.z);
this.frompostion = gameObject.transform.position;
this.topostion = toPos;
this.moveObjcet = gameObject;
this.moveTime = playTime;
if(playTime == 0){
this.moveObjcet.transform.position = this.topostion;
return
}
this.startMove()
Laya.Tween.to(this , {moveValue : 1.0} , this.moveTime , easeFun , Laya.Handler.create(this , this.endMove , [Laya.Handler.create(obj , callback)]))
}
private startMove(){
Laya.timer.frameLoop(1 , this ,this.moveUpdate)
}
private endMove(handler : Laya.Handler){
Laya.timer.clear(this , this.moveUpdate)
this.moveObjcet.transform.position = this.topostion
handler.method();
}
private moveUpdate(){
this.moveObjcet.transform.position = new Laya.Vector3(
this.frompostion.x + (this.moveDistance.x * this.moveValue),
this.frompostion.y + (this.moveDistance.y * this.moveValue),
this.frompostion.z + (this.moveDistance.z * this.moveValue)
)
}
}
使用说明
利用缓动函数库自己封装的工具类使用如下:
简单用法:
new Sprite3DMoveContorller().onPositionMoveTo(需要移动的3Dsprite , 移动目标点 , 移动总时间)
稍微高级一点的用法
new Sprite3DMoveContorller().onPositionMoveTo(需要移动的3Dsprite , 移动目标点 , 移动总时间 , 缓动函数 , 回调域 , 回调方法)
思路建议
以上代码仅仅控制了对象的postion属性 , 完全可以用相同的方式实现Scale 和 Rotation的缓动控制。