creator图片循环显示_CocosCreator背景图循环播放
以前在玩小游戲的時候發現有的小游戲背景圖一直再動,視覺效果挺好,給人一種炫炫的感覺,讓我這寫后臺的碼農很是羨慕和膜拜。沒想到天意弄人,我也開始寫游戲前端了剛接觸CocosCreator,好多東西都不懂,整個懵逼狀態,然后只能硬著頭皮上來寫,其實寫代碼思路還是有的,就是api和工具用起來有點陌生。這不,下午有個前端大佬讓我弄個游戲背景圖循環播放功能,說是游戲里會用到,然后就擼起袖子開干了。
大致思路:
1. 既然是至少輪播得有兩張圖吧
2. 輪播是肯定是要修改坐標的,橫播就是改X坐標,豎播就是改y坐標
3. 循環播就是一張播放完畢,得重新修改它的坐標等待下次播放
算了,直接點還是直接來代碼吧。
在資源管理器新建一個TypeScript文件,重命名為Game,然后把Game文件拖到層級管理器的Cavas下面。Game內容如下:
const {ccclass, property} = cc._decorator;
@ccclass
export default class Game extends cc.Component {
@property({displayName: '播放速度'})
speed: number = 0; // 移動時控制速度的變量
@property({displayName: '播放方向0橫1豎'})
orient: number = 0;// 0橫 1豎
@property( {displayName: '背景圖', type: cc.Node})
bgArr: cc.Node[] = []; // 用于管理背景圖片結點的數組,記得回cocos面板中添加數組的結點數量
curBg: cc.Node = null;// 當前播放背景
nextBg: cc.Node = null;// 即將播放背景
curIndex: number = 0;// 當前播放背景索引
xy:string = 'x';// x | y
wh:string = 'w';// 寬高
// 是否可以播放
move:boolean = true;
start () {
if (this.bgArr.length == 0) {
this.move = false;
return;
}
// 如果只有一張背景圖,則克隆一個
if (this.bgArr.length == 1) {
this.bgArr[1] = cc.instantiate(this.bgArr[0]);
this.bgArr[0].parent.addChild(this.bgArr[1]);
}
this.xy = this.orient == 0 ? 'x' : 'y';
this.wh = this.orient == 0 ? 'width' : 'height';
this.curBg = this.bgArr[this.curIndex];
this.nextBg = this.bgArr[this.curIndex + 1];
// 設置背景圖坐標
this.setBgPosition();
}
/**
* 設置背景圖坐標
*/
setBgPosition () {
this.bgArr[this.curIndex][this.xy] = 0;
this.bgArr[this.curIndex + 1][this.xy] = - (this.curBg[this.wh] / 2 + this.nextBg[this.wh] / 2);
}
update (dt) {
this.bgMove();
}
/**
*
* @param bgList
* @param speed 速度
*/
bgMove() {
if (this.move) {
this.curBg[this.xy] += this.speed;
this.nextBg[this.xy] += this.speed;
// 當前背景圖已播放完
if(this.curBg[this.xy] >= this.curBg[this.wh]) {
this.curBg = this.nextBg;
this.nextBg = this.bgArr[this.curIndex ++ % this.bgArr.length];
this.nextBg[this.xy] = this.curBg[this.xy] - this.curBg[this.wh] / 2 - this.nextBg[this.wh] / 2;
}
}
}
}
把要播放的背景圖拖入層級管理器的Cavas下面,坐標設置如下圖
給Game腳本屬性賦值(把背景圖拖入進來),如圖
以上就是CocosCreator實現輪播圖的一個思路。代碼獲取
總結
以上是生活随笔為你收集整理的creator图片循环显示_CocosCreator背景图循环播放的全部內容,希望文章能夠幫你解決所遇到的問題。