精靈在執行曲線或者移動動作時,發現方向沒有變化看着很奇怪,這裏仿照cc.Repeat等動作封裝了包裝動作RotateAction, 這樣就可以實時的改變精靈的朝向(尤其適合捕魚類遊戲😄)
cocos的動作類關鍵就是step和update方法,我們只需要在step裏計算前後的位置就可以計算出需要調整的角度。下面是代碼:
/**
* Created by xujiawei on 2020-03-13 12:08:52
* 包裝動作,用來包裝move,besizer等動作, 用來在執行動作過程中更新節點角度
*/
let RotateAction = cc.Class({
extends: cc.ActionInterval,
__ctor__ (action) {
this._elapsed = 0;
this._innerAction = null;
this._innerTarget = null;
action && this.initWithAction(action);
},
initWithAction (action) {
if (!action) {
cc.errorID(1026);
return false;
}
this._innerAction = action;
return true;
},
clone () {
let action = new RotateAction();
this._cloneDecoration(action);
action.initWithAction(this._innerAction.clone());
return action;
},
startWithTarget (target) {
this._innerTarget = target;
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._innerAction.startWithTarget(target);
},
step (dt) {
let prePos = this._innerTarget.getPosition();
this._innerAction.step(dt);
let curPos = this._innerTarget.getPosition();
// 更新角度
let dis = curPos.subSelf(prePos);
dis = dis.normalizeSelf();
// 默認方向爲(0,1)即y軸朝上爲0度
let origin = cc.v2(0, 1);
let r = origin.signAngle(dis);
let angle = cc.misc.radiansToDegrees(r);
// cc.log("angle:", angle);
this._innerTarget.angle = angle;
this._elapsed += dt;
},
/*
* Set inner action.
* @param {ActionInterval} action
*/
setInnerAction:function (action) {
if (this._innerAction !== action) {
this._innerAction = action;
}
},
/*
* Get inner action.
* @return {ActionInterval}
*/
getInnerAction:function () {
return this._innerAction;
},
isDone:function () {
return (this._elapsed >= this._innerAction._duration);
},
});
/**
* @method rotateAciton
* @param {ActionInterval} action
* @return {ActionInterval}
*/
cc.rotateAciton = function (action) {
return new RotateAction(action);
}