Cocos Creator之自定義Action

2021-09-10 07:00:10 字數 2894 閱讀 6671

使用方法

學習自定義action的最好方法是去檢視cocos creator中常用動作的寫法。比如cc.moveto繼承了cc.moveby,而cc.moveby則進一步繼承了cc.actioninterval

可以從cocos-creator的引擎原始碼找到cc.moveby的相關定義:

cc.moveby = cc.

class

(...

})

如果需要自定義action只需要按照自己的需求仿照cc.moveby的定義寫乙個就行了。如實現cc.actioninterval類的initwithdurationstartwithtargetupdate方法。「sprite 圓形運動,圓周運動」給出了自定義乙個圓周運動的三種方案,其中第一種方案就是整合cc.actioninterval,自定義action的方法。這裡不再贅述。

因為自己做cocos creator時用的ts語言,在寫法上與之前提到的略有不同。目的是實現精靈繞某一點旋轉一定的角度。

根據精靈自身旋轉角度和給定半徑確定精靈圓周運動的圓心。

在精靈圓周運動過程中自動調整精靈自身的旋轉角度。

這裡給出實現的原始碼,並做相關解釋。

const

= cc._decorator;

export

default

class

arcmove

extends

cc.actioninterval

initwithduration

(duration,

r, angle)

:boolean

return

false;}

startwithtarget

(target:cc.node)

else

// 根據節點自身傾角和半徑計算圓心

let angle =

-(target.rotation +90)

;let v1:cc.vec2 =

newcc.vec2

(math.

cos(angle/

180*math.pi)

, math.

sin(angle/

180*math.pi)

);let center: cc.vec2 = v1.

mul(

this

._r)

.add

(target.position)

;this

._centre .x = center.x;

this

._centre .y = center.y;

// 計算節點在圓上初始位置

this

._initangle =

90- target.rotation;

this

._rotation = target.rotation;

cc.log(

"在圓上角度:"

+this

._initangle);}

update

(dt)

varr

=this

._r;

var rat =

this

._initangle * math.pi/

180+ dir * dt * math.pi*

2*(this

._angle /

360)

;var x = locstartposition.x +

r* math.

cos(rat)

;var y = locstartposition.y +

r* math.

sin(rat)

;this

._target.

setposition

(x, y)

;this

._target.rotation =

this

._rotation + dt *

this

._angle;

let a =1;

}else}}

}export

vararcmove

=function

(duration,

r, angle)

這裡的_positiondelta和_previousposition暫時沒有用到。由於需要根據精靈的自身旋轉角度和給定的半徑得出圓心。隨後從當前位置開始圓周運動並調整精靈的自身旋轉角度。_angle指定精靈的圓周運動度數,一圈是360,具體運動度數可以任意設定。_target則是精靈節點,在initwithtarget中完成初始化。_initangle記錄的是初始時,從水平方向到精靈的旋轉角度,即記錄精靈在圓上的初始位置。_rotation記錄精靈初始的自身旋轉角度。

js中重寫initwithdurationinitwithtarget方法是通過cc.actioninterval.prototype.initwith***.call()的方式進行的。但ts似乎沒有把介面暴露出來,因此這裡採用了super["initwith***"]()的形式。

餘下內容計算出圓心、初始圓上位置等等。在update函式中,需要注意dt,比如給定精靈的運動時間duration為3秒,dt的變化還是從0到1.

在使用的時候,import 該類。

let action = armove(3, 100, 180);

隨後節點runaction即可。

Cocos Creator之Layout控制項

之前閱讀cocos creator文件的時候,看到了這個控制項,最近才用得到。需求是在按鈕上顯示購買 如xx元購買。xx是通過label控制項顯示,元購買 則是一張。由於 對應的數字是一位或者兩位數字,因此顯示的時候,單純的通過位置控制 xx元購買 不容易居中,因此需要用到layout控制項。方案是...

CocosCreator之Prefab 預製資源

官方文件 關於prefab的使用與講解 cc版prefab的方式說明 prefab 大家習慣喊它 預製體 其實通俗的講大家可以理解成是個 被打包的集合 prefab可以是由乙個或多個節點 node 元件 sprite label js指令碼等 組合,當然其中也會包括元件之間的關係等一同儲存。a 什麼...

cocos creator小遊戲案例之橡皮怪

註冊setinputcontrol function this 移動 this node.on touchmove function e this 結束 this node.on touchend function e this this node.on touchcancel function e...