Commit a318d934 authored by Tt's avatar Tt

OP15

parent d5665d78
import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
import { itemData } from "./data";
import { hyLoader } from "./hyLoader";
import CardManager from "./cardManager";
import pg from "./pg";
import ani from "./ani";
import { asyncDelay, RandomInt, showFireworks } from "../script/utils";
cc.Class({
extends: cc.Component,
properties: {
},
// 生命周期 onLoad
onLoad() {
this.initSceneData();
this.initSize();
},
_imageResList: null,
_audioResList: null,
_animaResList: null,
initSceneData() {
this._imageResList = [];
this._audioResList = [];
this._animaResList = [];
},
_designSize: null, // 设计分辨率
_frameSize: null, // 屏幕分辨率
_mapScaleMin: null, // 场景中常用缩放(取大值)
_mapScaleMax: null, // 场景中常用缩放(取小值)
_cocosScale: null, // cocos 自缩放 (较少用到)
initSize() {
// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
let f = screen_size >= design_size
cc.Canvas.instance.fitHeight = f
cc.Canvas.instance.fitWidth = !f
const frameSize = cc.view.getFrameSize();
this._frameSize = frameSize;
this._designSize = cc.view.getDesignResolutionSize();
let sx = cc.winSize.width / frameSize.width;
let sy = cc.winSize.height / frameSize.height;
this._cocosScale = Math.min(sx, sy);
sx = frameSize.width / this._designSize.width;
sy = frameSize.height / this._designSize.height;
this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
},
// 生命周期 start
start() {
let getData = this.getData.bind(this);
if (window && window.courseware) {
getData = window.courseware.getData;
}
getData((data) => {
console.log('data:', data);
this.data = data || this.getDefaultData();
this.data = JSON.parse(JSON.stringify(this.data))
this.preloadItem()
})
},
getData(func) {
if (window && window.courseware) {
window.courseware.getData(func, 'scene');
return;
}
const middleLayer = cc.find('middleLayer');
if (middleLayer) {
const middleLayerComponent = middleLayer.getComponent('middleLayer');
middleLayerComponent.getData(func);
return;
}
func(this.getDefaultData());
},
getDefaultData() {
return itemData;
// return defaultData;
},
preloadItem() {
this.addPreloadImage();
this.addPreloadAudio();
this.addPreloadAnima();
this.preload();
},
addPreloadImage() {
this._imageResList.push({ url: this.data.pic_url });
this._imageResList.push({ url: this.data.pic_url_2 });
},
addPreloadAudio() {
this._audioResList.push({ url: this.data.audio_url });
},
addPreloadAnima() {
},
preload() {
const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
this.loadEnd();
if (window && window["air"]) {
window["air"].hideAirClassLoading();
}
cc.debug.setDisplayStats(false);
});
},
//---------------------------------项目代码开始---------------------------------
loadEnd() {
this.initData();
this.initSingleData();
this.initAudio();
this.initView();
// this.initListener();
},
//全局游戏
_gameCode: null,
initData() {
//数据解析
CardManager.getIns().initCards(this.data);
CardManager.getIns().resetPageNum();
CardManager.getIns().randomPageCards();
this._gameCode = 0;
},
//单局游戏
_cantouch: null,
_cardPage: null,
_cardLayout: null,
_cardTouchItems: null,
_successItems: null,
initSingleData() {
// 所有全局变量 默认都是null
this._cantouch = true;
//界面用数据
this._cardTouchItems = [];
this._successItems = [];
this._cardPage = CardManager.getIns().getPage();
cc.log(this._cardPage);
},
initAudio() {
},
initView() {
this.btn_replay = pg.view.find(this, "btn_replay");
pg.view.visible(this.btn_replay, false);
pg.view.touchOn(this.btn_replay, this.onTouchReplay, this);
this.initLayout();
this.catBegin().then(() => {
this.catChoice();
});
},
initStars() {
// this.length = CardManager.getIns().getTestlet();
// this.addStar();
},
initLayout() {
pg.view.visible(this.btn_replay, false);
this._cardLayout = pg.view.find(this, `layout_card_6`);
ani.scaleIn(this._cardLayout);
pg.view.visible(this._cardLayout, true);
let itemBase = pg.view.find(this, "item");
for (let i = 0; i < this._cardPage.length; i++) {
let data = this._cardPage[i];
let item = cc.instantiate(itemBase)
item.parent = this._cardLayout;
if (!data || !item || data.type == CardManager.TYPE_NULL) continue;
this.updateItem(item, data);
}
},
updateItem(item, data) {
let img = pg.view.find(item, `img`);
let txt = pg.view.find(item, `txt`);
let audio = pg.view.find(item, `audio`);
let box = pg.view.find(item, `box`);
pg.view.setNetImg(img, data.img);
pg.view.visible(img, true);
pg.view.visible(txt, false);
pg.view.visible(audio, true);
pg.view.visible(pg.view.find(audio, "icon_1"), false);
pg.view.visible(pg.view.find(audio, "icon_2"), false);
pg.view.visible(pg.view.find(audio, "icon_3"), false);
item.scaleX = 1;
item.scaleY = 1;
pg.view.visible(box, false);
item.attr({ data: data });
pg.view.visible(item, true);
pg.view.touchOn(item, this.onTouchItem, this);
pg.view.touchOn(audio, this.onTouchAudio, this);
},
onTouchAudio(touch) {
if (this._gameCode != 0) return resolve('');
if (!this._cantouch) return;
this._cantouch = false;
let item = touch.target.parent;
this.playAudioAni(item).then(() => {
this._cantouch = true;
});
},
onTouchItem(touch, info) {
return new Promise((resolve, reject) => {
if (this._gameCode != 0) return resolve('');
if (!this._cantouch) return resolve('');
let item = touch.target;
if (this._successItems.indexOf(item) > -1) return resolve('');
let data = item.data;
this._cantouch = false;
if (data.right) {
this.catRight();
pg.view.visible(pg.view.find(item, 'box'), true);
this.playSFX("audio_right").then(() => {
//audio 播放的时候动画播放, audio停的时候 动画正好能停下
//如果动画停的位置不对,直接强制设置对应的效果
//下一次播放没有问题即可
this.playAudioAni(item).then(() => {
this._cantouch = true;
this._successItems.push(item);
this.catNormal();
this.groupEnd();
resolve('');
})
});
} else {
this.catError();
//失败--抖动效果
ani.shake(item);
this.playSFX("audio_error").then(() => {
this.playAudioAni(item).then(() => {
this._cantouch = true;
this.catNormal();
resolve('');
});
});
}
});
},
playAudioAni(item) {
return new Promise((resolve, reject) => {
// var anim = pg.view.find(item, `audio`).getComponent(cc.Animation);
// anim.play();
let audio = pg.view.find(item, `audio`);
let icon_1 = pg.view.find(audio, "icon_1");
let icon_2 = pg.view.find(audio, "icon_2");
let icon_3 = pg.view.find(audio, "icon_3");
icon_1.active = true;
//如果没有audio也要能正常走
pg.audio.playAudioByUrl(item.data.audio).then(() => {
// anim.stop();
icon_1.active = false;
resolve('');
});
});
},
onTouchReplay() {
this.playSFX("audio_btn");
this.initData();
this.initSingleData();
pg.view.visible(this.btn_replay, false);
this.initStars();
this.initLayout();
},
//回合结束
groupEnd() {
if (this._successItems.length >= CardManager.getIns().allRightNum()) {
//判定结束
this._gameCode = 2;
this.catFinish();
}
// if (this._successItems.length < this._cardPage.length) return;
// if (this._gameCode != 0) return;
// let code = CardManager.getIns().addPageNum();
// if (code == 0) {
// this._gameCode = 0;
// this.initSingleData();
// this.initLayout();
// } else if (code == 1) {
// this._gameCode = 1;
// //播放星星动画 然后下一页
// this.playSFX("audio_bigStar");
// this.createStarAni().then(() => {
// this._gameCode = 0;
// this.initSingleData();
// this.initLayout();
// })
// } else if (code == 2) {
// this._gameCode = 2;
// //播放星星动画 然后结束
// this.playSFX("audio_bigStar");
// this.playSFX("audio_sahua");
// this.createStarAni().then(() => { })
// this.createFireworkAni().then(() => {
// //gameOver
// // 游戏结束时需要调用这个方法通知系统作业完成
// onHomeworkFinish();
// pg.view.visible(this.btn_replay, true);
// })
// }
},
createRightAni(pos) {
// let right = pg.view.find(this, 'right');
// let aniRight = cc.instantiate(right);
// aniRight.x = pos.x;
// aniRight.y = pos.y;
// pg.view.find(this, 'ani').addChild(aniRight);
// let armDisplay = aniRight.getComponent(dragonBones.ArmatureDisplay);
// armDisplay.playAnimation('newAnimation', 1);
// pg.view.visible(aniRight, true);
},
createStarAni() {
return new Promise((resolve, reject) => {
this.showStar();
setTimeout(() => {
resolve('');
}, 500);
});
},
createFireworkAni() {
return new Promise((resolve, reject) => {
// this.showAllFirework(cc.find('Canvas/firework_ani'), cc.find('Canvas/paperBase').children);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(0, -400), cc.v2(0, 1000), 200, 200
);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(-600, -400), cc.v2(200, 1000), 200, 200
);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(600, -400), cc.v2(-200, 1000), 200, 200
);
setTimeout(() => {
resolve('');
}, 1000);
});
},
playSFX(name) {
return new Promise((resolve, reject) => {
let node = pg.view.find(this, "audio/" + name);
if (!node) return resolve();
let audioSource = node.getComponent(cc.AudioSource);
if (!audioSource) return resolve();
let audioClip = audioSource.clip;
if (!audioClip) return resolve();
let id = cc.audioEngine.play(audioClip, false, 1);
cc.audioEngine.setFinishCallback(id, () => {
resolve('');
})
});
},
length,
addStar() {
if (!this.length) {
this.length = 0;
}
this.length++;
let length = this.length;
const starLayout = cc.find('Canvas/layout_stars');
starLayout.removeAllChildren();
const paddingY = starLayout.getComponent(cc.Layout).spacingY;
for (let i = 0; i < length; i++) {
const starBase = cc.instantiate(cc.find('Canvas/StarBase'));
starBase.name = `starBase_${i}`;
starBase.scale = this.Between(0.5, (starLayout.height / length - paddingY) / starBase.height, 1);
starBase.parent = starLayout;
}
this.currentStarIdx = 0;
},
currentStarIdx: null,
showStar() {
if (!this.currentStarIdx) {
this.currentStarIdx = 0;
}
const starBase = cc.find(`Canvas/layout_stars/starBase_${this.currentStarIdx}`);
if (!starBase) {
return;
}
const star = starBase.getChildByName('Star');
const starBig = star.getChildByName('StarBig');
starBig.scale = 1;
star.active = true;
star.scaleX = 0.7 / starBase.scale;
star.scaleY = 1 / starBase.scale;
star.angle = 90;
const canvas = cc.find('Canvas');
const startPos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
const middlePos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
star.x = startPos.x;
star.y = startPos.y - starBig.height;
console.log('middlePos = ' + JSON.stringify(middlePos));
const time = 1;
cc.tween(star)
.to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
.to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / starBase.scale, scaleY: 0.8 / starBase.scale }, { easing: 'quadOut' })
.to(0.1, { y: middlePos.y, scaleX: 1 / starBase.scale, scaleY: 1 / starBase.scale }, { easing: 'quadOut' })
.delay(0.1)
.to(0.8, { angle: -720, scale: 1 })
.start();
cc.tween(star)
.delay(0.6)
.to(0.8, { x: 0 }, { easing: 'quadIn' })
.start();
cc.tween(star)
.delay(0.6)
.to(0.8, { y: 0 }, { easing: 'quadOut' })
.start();
cc.tween(starBig)
.delay(0.6)
.to(0.8, { scale: 0 }, { easing: 'quadOut' })
.call(() => {
// this.checkGameEnd();
})
.start();
this.currentStarIdx++;
},
Between(a, b, c) {
return [a, b, c].sort()[1];
},
exchangeNodePos(targetNode, baseNode, basePos) {
return targetNode.convertToNodeSpaceAR(baseNode.convertToWorldSpaceAR(cc.v2(basePos.x, basePos.y)));
},
async showAllFirework(parentNode, nodeList) {
for (let i = 0; i < 6; i++) {
this.showFirework(cc.v2(0, -parentNode.height / 2), parentNode, nodeList, parentNode.width * 2 / 3, parentNode.height * 1.3);
await asyncDelay(0.1);
}
},
showFirework(pos, parentNode, nodeList, width = 200, height = 200, number = 30) {
for (let i = 0; i < number; i++) {
const quad = this.createQuads(pos, parentNode, nodeList);
const targetX = RandomInt(width / 2, -width / 2);
const targetY = RandomInt(height);
cc.tween(quad)
.by(0.5, { x: targetX })
.by(3, { x: targetX * 2 })
.start();
cc.tween(quad)
.by(0.5, { y: targetY }, { easing: 'quadOut' })
.to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
.removeSelf()
.start();
cc.tween(quad)
.delay(1)
.to(1.5, { opacity: 0 })
.start();
}
},
createQuads(pos, parentNode, nodeList) {
const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
quadBase.x = pos.x;
quadBase.y = pos.y;
quadBase.z = pos.z;
quadBase.angle = RandomInt(180);
quadBase.parent = parentNode;
const quad = quadBase.getChildByName('quad');
quad.x = 0;
quad.y = 0;
quad.angle = RandomInt(180);
const paper = quad.getChildByName('paper');
paper.scaleX = Math.random() * 0.5 + 0.5;
paper.scaleY = Math.random() * 0.5 + 0.5;
quadBase.scaleX = Math.random();
cc.tween(quadBase)
.to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
.call(() => {
const time = Math.random() * 0.2;
cc.tween(quadBase)
.to(0.1 + time, { scaleX: -1 })
.to(0.1 + time, { scaleX: 1 })
.union()
.repeatForever()
.start();
})
.start();
return quadBase;
},
catBegin() {
return new Promise((resolve, reject) => {
this._cantouch = false;
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "begin");
pg.audio.playAudioByUrl(CardManager.getIns().getAudio()).then(() => {
resolve('');
});
});
},
catChoice() {
return new Promise((resolve, reject) => {
this.playSFX("mao_choice").then(() => {
let items = this._cardLayout.children;
let item = items.filter(it => {
return it.data.cardId == 0
})[0];
this._cantouch = true;
this.onTouchItem({ target: item }).then(() => {
resolve('');
})
});
});
},
catFinish() {
return new Promise((resolve, reject) => {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "finish");
this.playSFX("mao_right").then(() => {
});
});
},
catRight() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "right");
},
catError() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "wrong");
},
catNormal() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "normal");
}
});
import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
import { itemData } from "./data";
import { hyLoader } from "./hyLoader";
import CardManager from "./cardManager";
import pg from "./pg";
import ani from "./ani";
import { asyncDelay, RandomInt, showFireworks } from "../script/utils";
cc.Class({
extends: cc.Component,
properties: {
},
// 生命周期 onLoad
onLoad() {
this.initSceneData();
this.initSize();
},
_imageResList: null,
_audioResList: null,
_animaResList: null,
initSceneData() {
this._imageResList = [];
this._audioResList = [];
this._animaResList = [];
},
_designSize: null, // 设计分辨率
_frameSize: null, // 屏幕分辨率
_mapScaleMin: null, // 场景中常用缩放(取大值)
_mapScaleMax: null, // 场景中常用缩放(取小值)
_cocosScale: null, // cocos 自缩放 (较少用到)
initSize() {
// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
let f = screen_size >= design_size
cc.Canvas.instance.fitHeight = f
cc.Canvas.instance.fitWidth = !f
const frameSize = cc.view.getFrameSize();
this._frameSize = frameSize;
this._designSize = cc.view.getDesignResolutionSize();
let sx = cc.winSize.width / frameSize.width;
let sy = cc.winSize.height / frameSize.height;
this._cocosScale = Math.min(sx, sy);
sx = frameSize.width / this._designSize.width;
sy = frameSize.height / this._designSize.height;
this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
},
// 生命周期 start
start() {
let getData = this.getData.bind(this);
if (window && window.courseware) {
getData = window.courseware.getData;
}
getData((data) => {
console.log('data:', data);
this.data = data || this.getDefaultData();
this.data = JSON.parse(JSON.stringify(this.data))
this.preloadItem()
})
},
getData(func) {
if (window && window.courseware) {
window.courseware.getData(func, 'scene');
return;
}
const middleLayer = cc.find('middleLayer');
if (middleLayer) {
const middleLayerComponent = middleLayer.getComponent('middleLayer');
middleLayerComponent.getData(func);
return;
}
func(this.getDefaultData());
},
getDefaultData() {
return itemData;
// return defaultData;
},
preloadItem() {
this.addPreloadImage();
this.addPreloadAudio();
this.addPreloadAnima();
this.preload();
},
addPreloadImage() {
this._imageResList.push({ url: this.data.pic_url });
this._imageResList.push({ url: this.data.pic_url_2 });
},
addPreloadAudio() {
this._audioResList.push({ url: this.data.audio_url });
},
addPreloadAnima() {
},
preload() {
const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
this.loadEnd();
if (window && window["air"]) {
window["air"].hideAirClassLoading();
}
cc.debug.setDisplayStats(false);
});
},
//---------------------------------项目代码开始---------------------------------
loadEnd() {
this.initData();
this.initSingleData();
this.initAudio();
this.initView();
// this.initListener();
},
//全局游戏
_gameCode: null,
initData() {
//数据解析
CardManager.getIns().initCards(this.data);
CardManager.getIns().resetPageNum();
CardManager.getIns().randomPageCards();
this._gameCode = 0;
},
//单局游戏
_cantouch: null,
_cardPage: null,
_cardLayout: null,
_cardTouchItems: null,
_successItems: null,
initSingleData() {
// 所有全局变量 默认都是null
this._cantouch = true;
//界面用数据
this._cardTouchItems = [];
this._successItems = [];
this._cardPage = CardManager.getIns().getPage();
cc.log(this._cardPage);
},
initAudio() {
},
initView() {
this.btn_replay = pg.view.find(this, "btn_replay");
pg.view.visible(this.btn_replay, false);
pg.view.touchOn(this.btn_replay, this.onTouchReplay, this);
this.initLayout();
this.catBegin().then(() => {
this.catChoice();
});
},
initStars() {
// this.length = CardManager.getIns().getTestlet();
// this.addStar();
},
initLayout() {
pg.view.visible(this.btn_replay, false);
this._cardLayout = pg.view.find(this, `layout_card_6`);
ani.scaleIn(this._cardLayout);
pg.view.visible(this._cardLayout, true);
let itemBase = pg.view.find(this, "item");
for (let i = 0; i < this._cardPage.length; i++) {
let data = this._cardPage[i];
let item = cc.instantiate(itemBase)
item.parent = this._cardLayout;
if (!data || !item || data.type == CardManager.TYPE_NULL) continue;
this.updateItem(item, data);
}
},
updateItem(item, data) {
let img = pg.view.find(item, `img`);
let txt = pg.view.find(item, `txt`);
let audio = pg.view.find(item, `audio`);
let box = pg.view.find(item, `box`);
pg.view.setNetImg(img, data.img);
pg.view.visible(img, true);
pg.view.visible(txt, false);
pg.view.visible(audio, true);
pg.view.visible(pg.view.find(audio, "icon_1"), false);
pg.view.visible(pg.view.find(audio, "icon_2"), false);
pg.view.visible(pg.view.find(audio, "icon_3"), false);
item.scaleX = 1;
item.scaleY = 1;
pg.view.visible(box, false);
item.attr({ data: data });
pg.view.visible(item, true);
pg.view.touchOn(item, this.onTouchItem, this);
pg.view.touchOn(audio, this.onTouchAudio, this);
},
onTouchAudio(touch) {
if (this._gameCode != 0) return resolve('');
if (!this._cantouch) return;
this._cantouch = false;
let item = touch.target.parent;
this.playAudioAni(item).then(() => {
this._cantouch = true;
});
},
onTouchItem(touch, info) {
return new Promise((resolve, reject) => {
if (this._gameCode != 0) return resolve('');
if (!this._cantouch) return resolve('');
let item = touch.target;
if (this._successItems.indexOf(item) > -1) return resolve('');
let data = item.data;
this._cantouch = false;
if (data.right) {
this.catRight();
pg.view.visible(pg.view.find(item, 'box'), true);
this.playSFX("audio_right").then(() => {
//audio 播放的时候动画播放, audio停的时候 动画正好能停下
//如果动画停的位置不对,直接强制设置对应的效果
//下一次播放没有问题即可
this.playAudioAni(item).then(() => {
this._cantouch = true;
this._successItems.push(item);
this.catNormal();
this.groupEnd();
resolve('');
})
});
} else {
this.catError();
//失败--抖动效果
ani.shake(item);
this.playSFX("audio_error").then(() => {
this.playAudioAni(item).then(() => {
this._cantouch = true;
this.catNormal();
resolve('');
});
});
}
});
},
playAudioAni(item) {
return new Promise((resolve, reject) => {
// var anim = pg.view.find(item, `audio`).getComponent(cc.Animation);
// anim.play();
let audio = pg.view.find(item, `audio`);
let icon_1 = pg.view.find(audio, "icon_1");
let icon_2 = pg.view.find(audio, "icon_2");
let icon_3 = pg.view.find(audio, "icon_3");
icon_1.active = true;
//如果没有audio也要能正常走
pg.audio.playAudioByUrl(item.data.audio).then(() => {
// anim.stop();
icon_1.active = false;
resolve('');
});
});
},
onTouchReplay() {
this.playSFX("audio_btn");
this.initData();
this.initSingleData();
pg.view.visible(this.btn_replay, false);
this.initStars();
this.initLayout();
},
//回合结束
groupEnd() {
if (this._successItems.length >= CardManager.getIns().allRightNum()) {
//判定结束
this._gameCode = 2;
this.catFinish();
}
// if (this._successItems.length < this._cardPage.length) return;
// if (this._gameCode != 0) return;
// let code = CardManager.getIns().addPageNum();
// if (code == 0) {
// this._gameCode = 0;
// this.initSingleData();
// this.initLayout();
// } else if (code == 1) {
// this._gameCode = 1;
// //播放星星动画 然后下一页
// this.playSFX("audio_bigStar");
// this.createStarAni().then(() => {
// this._gameCode = 0;
// this.initSingleData();
// this.initLayout();
// })
// } else if (code == 2) {
// this._gameCode = 2;
// //播放星星动画 然后结束
// this.playSFX("audio_bigStar");
// this.playSFX("audio_sahua");
// this.createStarAni().then(() => { })
// this.createFireworkAni().then(() => {
// //gameOver
// // 游戏结束时需要调用这个方法通知系统作业完成
// onHomeworkFinish();
// pg.view.visible(this.btn_replay, true);
// })
// }
},
createRightAni(pos) {
// let right = pg.view.find(this, 'right');
// let aniRight = cc.instantiate(right);
// aniRight.x = pos.x;
// aniRight.y = pos.y;
// pg.view.find(this, 'ani').addChild(aniRight);
// let armDisplay = aniRight.getComponent(dragonBones.ArmatureDisplay);
// armDisplay.playAnimation('newAnimation', 1);
// pg.view.visible(aniRight, true);
},
createStarAni() {
return new Promise((resolve, reject) => {
this.showStar();
setTimeout(() => {
resolve('');
}, 500);
});
},
createFireworkAni() {
return new Promise((resolve, reject) => {
// this.showAllFirework(cc.find('Canvas/firework_ani'), cc.find('Canvas/paperBase').children);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(0, -400), cc.v2(0, 1000), 200, 200
);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(-600, -400), cc.v2(200, 1000), 200, 200
);
showFireworks(
cc.find('Canvas/firework_ani'),
cc.find('Canvas/RibbonNodeBase').children,
cc.v2(600, -400), cc.v2(-200, 1000), 200, 200
);
setTimeout(() => {
resolve('');
}, 1000);
});
},
playSFX(name) {
return new Promise((resolve, reject) => {
let node = pg.view.find(this, "audio/" + name);
if (!node) return resolve();
let audioSource = node.getComponent(cc.AudioSource);
if (!audioSource) return resolve();
let audioClip = audioSource.clip;
if (!audioClip) return resolve();
let id = cc.audioEngine.play(audioClip, false, 1);
cc.audioEngine.setFinishCallback(id, () => {
resolve('');
})
});
},
length,
addStar() {
if (!this.length) {
this.length = 0;
}
this.length++;
let length = this.length;
const starLayout = cc.find('Canvas/layout_stars');
starLayout.removeAllChildren();
const paddingY = starLayout.getComponent(cc.Layout).spacingY;
for (let i = 0; i < length; i++) {
const starBase = cc.instantiate(cc.find('Canvas/StarBase'));
starBase.name = `starBase_${i}`;
starBase.scale = this.Between(0.5, (starLayout.height / length - paddingY) / starBase.height, 1);
starBase.parent = starLayout;
}
this.currentStarIdx = 0;
},
currentStarIdx: null,
showStar() {
if (!this.currentStarIdx) {
this.currentStarIdx = 0;
}
const starBase = cc.find(`Canvas/layout_stars/starBase_${this.currentStarIdx}`);
if (!starBase) {
return;
}
const star = starBase.getChildByName('Star');
const starBig = star.getChildByName('StarBig');
starBig.scale = 1;
star.active = true;
star.scaleX = 0.7 / starBase.scale;
star.scaleY = 1 / starBase.scale;
star.angle = 90;
const canvas = cc.find('Canvas');
const startPos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
const middlePos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
star.x = startPos.x;
star.y = startPos.y - starBig.height;
console.log('middlePos = ' + JSON.stringify(middlePos));
const time = 1;
cc.tween(star)
.to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
.to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / starBase.scale, scaleY: 0.8 / starBase.scale }, { easing: 'quadOut' })
.to(0.1, { y: middlePos.y, scaleX: 1 / starBase.scale, scaleY: 1 / starBase.scale }, { easing: 'quadOut' })
.delay(0.1)
.to(0.8, { angle: -720, scale: 1 })
.start();
cc.tween(star)
.delay(0.6)
.to(0.8, { x: 0 }, { easing: 'quadIn' })
.start();
cc.tween(star)
.delay(0.6)
.to(0.8, { y: 0 }, { easing: 'quadOut' })
.start();
cc.tween(starBig)
.delay(0.6)
.to(0.8, { scale: 0 }, { easing: 'quadOut' })
.call(() => {
// this.checkGameEnd();
})
.start();
this.currentStarIdx++;
},
Between(a, b, c) {
return [a, b, c].sort()[1];
},
exchangeNodePos(targetNode, baseNode, basePos) {
return targetNode.convertToNodeSpaceAR(baseNode.convertToWorldSpaceAR(cc.v2(basePos.x, basePos.y)));
},
async showAllFirework(parentNode, nodeList) {
for (let i = 0; i < 6; i++) {
this.showFirework(cc.v2(0, -parentNode.height / 2), parentNode, nodeList, parentNode.width * 2 / 3, parentNode.height * 1.3);
await asyncDelay(0.1);
}
},
showFirework(pos, parentNode, nodeList, width = 200, height = 200, number = 30) {
for (let i = 0; i < number; i++) {
const quad = this.createQuads(pos, parentNode, nodeList);
const targetX = RandomInt(width / 2, -width / 2);
const targetY = RandomInt(height);
cc.tween(quad)
.by(0.5, { x: targetX })
.by(3, { x: targetX * 2 })
.start();
cc.tween(quad)
.by(0.5, { y: targetY }, { easing: 'quadOut' })
.to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
.removeSelf()
.start();
cc.tween(quad)
.delay(1)
.to(1.5, { opacity: 0 })
.start();
}
},
createQuads(pos, parentNode, nodeList) {
const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
quadBase.x = pos.x;
quadBase.y = pos.y;
quadBase.z = pos.z;
quadBase.angle = RandomInt(180);
quadBase.parent = parentNode;
const quad = quadBase.getChildByName('quad');
quad.x = 0;
quad.y = 0;
quad.angle = RandomInt(180);
const paper = quad.getChildByName('paper');
paper.scaleX = Math.random() * 0.5 + 0.5;
paper.scaleY = Math.random() * 0.5 + 0.5;
quadBase.scaleX = Math.random();
cc.tween(quadBase)
.to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
.call(() => {
const time = Math.random() * 0.2;
cc.tween(quadBase)
.to(0.1 + time, { scaleX: -1 })
.to(0.1 + time, { scaleX: 1 })
.union()
.repeatForever()
.start();
})
.start();
return quadBase;
},
catBegin() {
return new Promise((resolve, reject) => {
this._cantouch = false;
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "begin");
pg.audio.playAudioByUrl(CardManager.getIns().getAudio()).then(() => {
resolve('');
});
});
},
catChoice() {
return new Promise((resolve, reject) => {
this.playSFX("mao_choice").then(() => {
let items = this._cardLayout.children;
let item = items.filter(it => {
return it.data.cardId == 0
})[0];
this._cantouch = true;
this.onTouchItem({ target: item }).then(() => {
resolve('');
})
});
});
},
catFinish() {
return new Promise((resolve, reject) => {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "finish");
this.playSFX("mao_right").then(() => {
});
});
},
catRight() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "right");
},
catError() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "wrong");
},
catNormal() {
let cat = pg.view.find(this, "cat");
pg.view.playDragonBone(cat, "normal");
}
});
class Ani {
//抖动效果
static shake(item) {
// alert("抖动效果");
let tween = cc.tween(item);
tween.to(0.06, { angle: 10 })
.to(0.06, { angle: 0 })
.to(0.06, { angle: -10 })
.to(0.06, { angle: 0 });
tween.repeat(4);
tween.start();
}
static scaleOut(item) {
return new Promise((resolve) => {
let tween = cc.tween(item);
tween.to(0.2, { scaleX: 0, scaleY: 0 })
.call(() => { resolve() });
tween.start();
})
}
static scaleIn(item) {
return new Promise((resolve) => {
item.scaleX = 0;
item.scaleY = 0;
let tween = cc.tween(item);
tween.to(0.2, { scaleX: 1, scaleY: 1 })
.call(() => { resolve() });
tween.start();
})
}
}
class Ani {
//抖动效果
static shake(item) {
// alert("抖动效果");
let tween = cc.tween(item);
tween.to(0.06, { angle: 10 })
.to(0.06, { angle: 0 })
.to(0.06, { angle: -10 })
.to(0.06, { angle: 0 });
tween.repeat(4);
tween.start();
}
static scaleOut(item) {
return new Promise((resolve) => {
let tween = cc.tween(item);
tween.to(0.2, { scaleX: 0, scaleY: 0 })
.call(() => { resolve() });
tween.start();
})
}
static scaleIn(item) {
return new Promise((resolve) => {
item.scaleX = 0;
item.scaleY = 0;
let tween = cc.tween(item);
tween.to(0.2, { scaleX: 1, scaleY: 1 })
.call(() => { resolve() });
tween.start();
})
}
}
export default Ani;
\ No newline at end of file
class Card {
constructor(picItem, cardId) {
this.cardId = cardId;
this.type = CardManager.TYPE_IMG;
this.right = picItem.radioValue == "1";
this.img = picItem.pic_url;
this.audio = picItem.audio_url;
}
}
class CardManager {
static TYPE_NULL = 0;
static TYPE_TXT = 1;
static TYPE_IMG = 2;
static TYPE_MP3 = 3;
static instance;
static getIns() {
if (!CardManager.instance) CardManager.instance = new CardManager();
return CardManager.instance;
}
_cardArray;//所有卡片的组
testletId;//组id
pageId;//页id
constructor() {
this._cardArray = [];//组 页
this._audio_url = "";
this.testletId = 0;
this.pageId = 0;
}
initCards(obj) {
console.log(obj);
let picArr = obj.contentObj.picArr;
let id = 0;
this._cardArray = picArr.list.map(cd => {
return new Card(cd, id++);
});
this._audio_url = picArr.audio_url
}
getTestlet() {
return this._cardArray.length - 1;
}
getPage() {
return this._cardArray;
}
getAudio() {
return this._audio_url;
}
allRightNum() {
return this._cardArray.filter(c => c.right).length;
}
addPageNum() {
this.pageId++;
if (!this.getPage()) {
this.pageId = 0;
this.testletId++;
if (!this.getPage()) {
return 2;//游戏结束
}
return 1;//组结束
} else {
return 0;//页结束
}
}
resetPageNum() {
this.testletId = 0;
this.pageId = 0;
}
randomPageCards() {
//页面内部数字要打乱 0 1 2 3 4 5 6 7 8 每次动态取出一个值 然后动态处理
let arr = [];
while (this._cardArray.length > 0) {
let rand = Math.floor(Math.random() * this._cardArray.length);
arr.push(this._cardArray[rand]);
this._cardArray.splice(rand, 1);
}
this._cardArray = arr;
}
}
class Card {
constructor(picItem, cardId) {
this.cardId = cardId;
this.type = CardManager.TYPE_IMG;
this.right = picItem.radioValue == "1";
this.img = picItem.pic_url;
this.audio = picItem.audio_url;
}
}
class CardManager {
static TYPE_NULL = 0;
static TYPE_TXT = 1;
static TYPE_IMG = 2;
static TYPE_MP3 = 3;
static instance;
static getIns() {
if (!CardManager.instance) CardManager.instance = new CardManager();
return CardManager.instance;
}
_cardArray;//所有卡片的组
testletId;//组id
pageId;//页id
constructor() {
this._cardArray = [];//组 页
this._audio_url = "";
this.testletId = 0;
this.pageId = 0;
}
initCards(obj) {
console.log(obj);
let picArr = obj.contentObj.picArr;
let id = 0;
this._cardArray = picArr.list.map(cd => {
return new Card(cd, id++);
});
this._audio_url = picArr.audio_url
}
getTestlet() {
return this._cardArray.length - 1;
}
getPage() {
return this._cardArray;
}
getAudio() {
return this._audio_url;
}
allRightNum() {
return this._cardArray.filter(c => c.right).length;
}
addPageNum() {
this.pageId++;
if (!this.getPage()) {
this.pageId = 0;
this.testletId++;
if (!this.getPage()) {
return 2;//游戏结束
}
return 1;//组结束
} else {
return 0;//页结束
}
}
resetPageNum() {
this.testletId = 0;
this.pageId = 0;
}
randomPageCards() {
//页面内部数字要打乱 0 1 2 3 4 5 6 7 8 每次动态取出一个值 然后动态处理
let arr = [];
while (this._cardArray.length > 0) {
let rand = Math.floor(Math.random() * this._cardArray.length);
arr.push(this._cardArray[rand]);
this._cardArray.splice(rand, 1);
}
this._cardArray = arr;
}
}
export default CardManager;
\ No newline at end of file
export const itemData = {
"contentObj": { "picArr": { "list": [{ "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/81f008a708cafed9caf1234e0af0d982.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/b8860997e5801c5410cf23fb7d44ea6f.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/f2a7d2c7df70548ca49cdd802656aeb4.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/bdc09d9eb89b73e67357b502ae2158dd.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/12c164fe8bd626872e2a8f7ba6d88f7e.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/aaeb274c49f400c26b05583d481aca09.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/94a3ead8d0972651c5d49d8aa25ac8b5.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/301ec5c708d22928ccf2162215f429fe.mp3" }, { "cardId": "", "radioValue": "0", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/b1baffd430e9f5feefde0b1053b7a7e2.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/2db9fa7c28a11fdbcecfa6a5b5e62319.mp3" }, { "cardId": "", "radioValue": "0", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/d1c6cedd0ea8ba9a6a8ca8ad3886df49.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/c3db5ac421ef039cf540edfa5116c831.mp3" }], "audio_url": "http://staging-teach.cdn.ireadabc.com/9bc9518c426d0e9a5e4a6b0614ddd195.mp3" } }
}
export const itemData = {
"contentObj": { "picArr": { "list": [{ "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/81f008a708cafed9caf1234e0af0d982.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/b8860997e5801c5410cf23fb7d44ea6f.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/f2a7d2c7df70548ca49cdd802656aeb4.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/bdc09d9eb89b73e67357b502ae2158dd.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/12c164fe8bd626872e2a8f7ba6d88f7e.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/aaeb274c49f400c26b05583d481aca09.mp3" }, { "cardId": "", "radioValue": "1", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/94a3ead8d0972651c5d49d8aa25ac8b5.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/301ec5c708d22928ccf2162215f429fe.mp3" }, { "cardId": "", "radioValue": "0", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/b1baffd430e9f5feefde0b1053b7a7e2.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/2db9fa7c28a11fdbcecfa6a5b5e62319.mp3" }, { "cardId": "", "radioValue": "0", "title": "", "pic_url": "http://staging-teach.cdn.ireadabc.com/d1c6cedd0ea8ba9a6a8ca8ad3886df49.png", "audio_url": "http://staging-teach.cdn.ireadabc.com/c3db5ac421ef039cf540edfa5116c831.mp3" }], "audio_url": "http://staging-teach.cdn.ireadabc.com/9bc9518c426d0e9a5e4a6b0614ddd195.mp3" } }
}
class HYLoader {
getSprNode(resName) {
const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
const node = new cc.Node();
node.addComponent(cc.Sprite).spriteFrame = sf;
return node;
}
getSpriteFrimeByUrl(url, cb) {
cc.loader.load({ url }, (err, img) => {
const spriteFrame = new cc.SpriteFrame(img)
if (cb) {
cb(spriteFrame);
}
})
}
getSprNodeByUrl(url, cb) {
const node = new cc.Node();
const spr = node.addComponent(cc.Sprite);
this.getSpriteFrimeByUrl(url, (sf) => {
spr.spriteFrame = sf;
if (cb) {
cb(node);
}
})
}
playAudioByUrl(audio_url, cb = null) {
if (audio_url) {
cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
const audioId = cc.audioEngine.play(audioClip, false, 0.8);
if (cb) {
cc.audioEngine.setFinishCallback(audioId, () => {
cb();
});
}
});
}
}
}
class HYLoader {
getSprNode(resName) {
const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
const node = new cc.Node();
node.addComponent(cc.Sprite).spriteFrame = sf;
return node;
}
getSpriteFrimeByUrl(url, cb) {
cc.loader.load({ url }, (err, img) => {
const spriteFrame = new cc.SpriteFrame(img)
if (cb) {
cb(spriteFrame);
}
})
}
getSprNodeByUrl(url, cb) {
const node = new cc.Node();
const spr = node.addComponent(cc.Sprite);
this.getSpriteFrimeByUrl(url, (sf) => {
spr.spriteFrame = sf;
if (cb) {
cb(node);
}
})
}
playAudioByUrl(audio_url, cb = null) {
if (audio_url) {
cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
const audioId = cc.audioEngine.play(audioClip, false, 0.8);
if (cb) {
cc.audioEngine.setFinishCallback(audioId, () => {
cb();
});
}
});
}
}
}
export const hyLoader = new HYLoader();
\ No newline at end of file
let pg = {};
//打印
pg.logger = {
d: (str) => {
cc.log(str);
},
w: function (str) {
cc.warn(str);
}
}
const log = pg.logger;
//显示常用
pg.view = {
//显示隐藏
//添加节点
//删除节点
//加载网络节点
touchEnable(item, isEnable) {
if (!item) return pg.logger.w("设置按钮响应失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node) return pg.logger.w("设置按钮响应失败,传入了错误的item");
let btn = node.getComponent(cc.Button);
if (!btn) return pg.logger.w("当前节点没有添加button->" + node.name);
btn.interactable = isEnable;
return true;
},
touchOn(item, callback, target) {
if (!item) return pg.logger.w("添加按钮响应失败,传入了错误的item");
if (!callback || !target) return pg.logger.w("添加按钮响应失败,传入了空回调");
let node = item.node ? item.node : item;
node.on(cc.Node.EventType.TOUCH_END, callback, target);
return true;
},
touchOff(item, callback, target) {
if (!item) return log.w("移除按钮响应失败,传入了错误的item");
if (!callback || !target) return log.w("移除按钮响应失败,传入了空回调");
let node = item.node ? item.node : item;
if (!node || !node.parent) return log.w("节点已移除");
node.off(cc.Node.EventType.TOUCH_END, callback, target);
return true;
},
//更换图片
setImg(item, res) {
return new Promise((resolve, reject) => {
if (!item) return log.w("图片更换失败,传入了错误的item");
if (!res) return log.w("图片更换失败,传入了错误的res");
pg.load.loadImg(res).then((spriteFrame) => {
if (!cc.isValid(item)) return log.i("节点已销毁");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.i("节点已销毁");
let component = node.getComponent(cc.Sprite);
let { width, height } = spriteFrame._rect;
component.spriteFrame = spriteFrame;
resolve({ width, height });
})
})
},
setNetImg(item, res) {
return new Promise((resolve, reject) => {
if (!item) return log.w("图片更换失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!res) {
node.active = false;
return log.w("图片更换失败,传入了错误的res");
}
if (!node) return log.w("图片更换失败,传入了错误的item");
if (node.net_url == res) return;
let w = node.width;
let h = node.height;
node.active = false;//
pg.load.loadNetImg(res).then((texture) => {
if (!cc.isValid(node)) return log.i("节点已销毁");
let nw = node.width = texture.width;
let nh = node.height = texture.height;
let component = node.getComponent(cc.Sprite);
let spriteFrame = new cc.SpriteFrame(texture);
component.spriteFrame = spriteFrame;
node.net_url = res;
let a = w / nw;//100 2000 0.05
let b = h / nh;//100 1000 0.1
if (a < b) {
node.width = a * nw;
node.height = a * nh;
} else {
node.width = b * nw;
node.height = b * nh;
}
node.active = true;
resolve({ w: nw, h: nh });
})
})
},
visible(item, isVisible) {
if (!item) return log.w("节点显示失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node || !node.parent) return log.w("节点已移除");
node.active = isVisible;
return true;
},
setString(item, text, count = 0) {
if (!item) return log.w("节点text失败,传入了错误的item");
if (count > 0) {
function parse_str(str, count) {
if (!str) return "";
var segmants = str.split('+');
str = segmants.join('');
var len = 0;
var idx = 0;
for (var i = 0; i < str.length; i++) {
var p = /[^x00-xff]/g;
var a = str.charAt(i);
if (p.test(a)) {
len += 2;
idx++;
}
else {
len += 1;
idx++;
}
if (len >= count * 2)
break;
}
return str.substr(0, idx);
}
text = parse_str(text, count);
}
let node = item.node ? item.node : item;
if (!node) return;
let component = node.getComponent(cc.Label);//组件功能 非node的功能
component.string = text;
return true;
},
setColor(item, color, outlineWidth = -1) {
if (!item) return log.w("setColor warn->传入了错误的item");
let RGB = this.colorRgb(color);
if (!RGB || RGB.length == 0) return log.w("color ->传入了错误的color");
item.color = new cc.Color(RGB[0], RGB[1], RGB[2]);
if (outlineWidth < 0) return;
let LabelOutline = item.getComponent(cc.LabelOutline);
if (!LabelOutline) return log.w("LabelOutline warn->未添加描边");
LabelOutline.width = outlineWidth;
},
colorRgb(color) {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var sColor = color;
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return sColorChange;
} else {
return sColor;
}
},
find(item, childPath) {
if (typeof item == "string") {
childPath = item;
item = null;
}
if (!childPath || childPath == '' || typeof childPath != 'string') return log.w("findChildByPath error->" + "请传入路径");
let child = null;
if (item) {
let node = item.node ? item.node : item;
if (!node.children || node.children.length == 0) return log.w("findChild error->" + "找不到此节点,请检查层级路径:" + childPath);
child = cc.find(childPath, node);
} else {
child = cc.find(childPath);
}
if (!child) return log.w("findChildByPath error->" + "找不到此节点,请检查层级路径:" + childPath);
return child;
},
addChild(item, child, zIndex) {
if (!child) return console.log("addChild error ->请传入子节点");
if (!item) return console.log("addChild error ->请传入父节点");
let node = item.node ? item.node : item;
if (!node) return console.log("addChild error ->请传入父节点");
if (child.parent)
return log.w("此节点已经有父节点->" + child.name);
if (zIndex >= 0) {
node.addChild(child, zIndex)
} else {
node.addChild(child);
}
return true;
},
removeSelf(item) {
if (!item) return log.w("节点移除失败,传入了错误的item");
let node = item.node ? item.node : item;
node.removeFromParent();
node.destroy();
},
removChildren(item) {
if (!item) return log.w("节点remove失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node.parent) return log.w("节点remove失败,传入了错误的item");
node.removeAllChildren();
return true;
},
removeChild(item, child) {
if (!item) return log.w("节点remove失败,传入了错误的item");
let node = item.node ? item.node : item;
if (child.parent && child.parent == node) {
node.removeChild(child);
node.destroy();
}
return true;
},
playSpineAnimation(item, aniName, loop) {
if (!item || !cc.isValid(item)) return log.w("动画播放失败,传入了错误的item");
if (!aniName) return log.w("动画播放失败,传入了错误的aniName");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.w("节点已销毁");
let skl = node.getComponent(sp.Skeleton);
skl.setAnimation(0, aniName, loop);
return skl;
},
playDragonBone(item, aniName, loop) {
if (!item || !cc.isValid(item)) return log.w("动画播放失败,传入了错误的item");
if (!aniName) return log.w("动画播放失败,传入了错误的aniName");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.w("节点已销毁");
let dba = node.getComponent(dragonBones.ArmatureDisplay);
dba.playAnimation(aniName, loop);
return dba;
},
cloneNode(node) {
return cc.instantiate(node);
}
}
//加载 未封装bundle
pg.load = {
loadRes: function (res, type, bundleName) {
// cc.assetManager.loadBundle('hall', (err, bundle) => {
// if (err) return cc.error(err);
// cc.director.loadScene("hall", () => { });
// });
// cc.assetManager.loadBundle('chess', (err, bundle) => {
// if (err) return cc.error(err);
// cc.director.loadScene("chess", () => {
// // //清理hall的资源
// // let hallBundle = cc.assetManager.getBundle(`hall`);
// // hallBundle.releaseAll();
// // cc.assetManager.removeBundle(hallBundle);
// });
// });
//此处需要二次封装,新的存在assetbundle
return new Promise((resolve, reject) => {
cc.loader.loadRes(res, type, (err, data) => {
if (err && !data) return resolve(pg.logger.d('loading loadRes error-> ', res));
resolve(data);
});
})
},
loadImg: function () {
return new Promise((resolve, reject) => {
this.loadRes(url, cc.SpriteFrame).then((data) => {
if (!data || data.length == 0) return;
resolve(data);
})
})
},
loadPrefab: function (path = "") {
return new Promise((resolve, reject) => {
url = "/prefabs/" + path;
this.loadRes(url, cc.Prefab).then((data) => {
if (!data || data.length == 0) return reject();
return resolve(cc.instantiate(data));
})
})
},
loadNetImg: function (url) {
return new Promise((resolve, reject) => {
cc.loader.load({ url }, (err, texture) => {
if (err && !data) return resolve(pg.logger.w('loading loadRes warn-> ', res));
resolve(texture);
});
})
},
}
//本地存储
pg.localStorage = {
setItem: function (key, val) {
cc.sys.localStorage.setItem(key, val);
},
getItem: function (key, defVal) {
return cc.sys.localStorage.getItem(key) || defVal;
}
}
//HTTP网络请求
pg.http = {
send: function (type = "GET", url, data, callback) {
let xhr = cc.loader.getXMLHttpRequest();
xhr.timeout = 5000;
xhr.responseType = "text";
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 300) {
try {
let resp = xhr.responseText;
pg.logger.d("resp->" + JSON.stringify(resp));
callback(resp);
} catch (e) {
}
}
else {
}
};
xhr.onerror = (e) => {
pg.logger.w("onerror->" + url);
};
xhr.ontimeout = (e) => {
pg.logger.w("ontimeout->" + url);
};
xhr.send(data);
}
}
/**事件监听部分
*
*
*
*/
class Emitter {
static instance;
static getInstance() {
if (!Emitter.instance) {
Emitter.instance = new Emitter();
}
return Emitter.instance;
}
constructor() {
this._callbacks = {};
return this;
}
on(event, fn) {
(this._callbacks[event] = this._callbacks[event] || []).push(fn);
};
once(event, fn) {
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
};
off(event, fn) {
// all
if (0 == arguments.length) {
this._callbacks = {};
return;
}
// specific event
let callbacks = this._callbacks[event];
if (!callbacks) return;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return;
}
// remove specific handler
let cb;
for (let i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return;
}
emit(event, ...args) {
this._callbacks = this._callbacks || {};
// let args = [].slice.call(arguments, 1);
let callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (let i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
}
listeners(event) {
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
hasListeners(event) {
return !!this.listeners(event).length;
};
}
class SceneStruct {
constructor() {
this.nowScene = "hb_login";
this.sceneObject = {};
this.sceneObject[this.nowScene] = [];
}
addScene(sceneName) {
this.nowScene = sceneName;
//if (!this.sceneObject[this.nowScene])
this.sceneObject[this.nowScene] = [];
}
addLayer(layerName) {
if (!this.sceneObject[this.nowScene]) return console.log("sceneStruct err->scene未初始化:" + this.nowScene)
if (!this.sceneObject[this.nowScene].includes(layerName)) {
this.sceneObject[this.nowScene].push(layerName);
}
}
removeLayer(layerName) {
if (!this.sceneObject[this.nowScene]) return console.log("sceneStruct err->scene未初始化:" + this.nowScene)
let arr = this.sceneObject[this.nowScene];
let isSuccess = false;
for (let i = arr.length - 1; i >= 0; i--) {
let laName = arr[i];
if (layerName == laName) {
isSuccess = true;
arr.splice(i, 1);
}
}
if (!isSuccess) {
console.log("sceneStruct err->scene没有对应layer:" + this.nowScene + ">" + layerName);
}
}
clearLayer() {
this.sceneObject[this.nowScene] = [];
}
getLayers() {
return this.sceneObject[this.nowScene] || [];
}
}
class SceneManager {
static debug = true;
static instance;
static getInstance() {
if (!SceneManager.instance) {
SceneManager.instance = new SceneManager();
}
return SceneManager.instance;
}
//py [-zIndex.bottom-]
//py [-zIndex.login-]
//py [-zIndex.hall-]
//py [-zIndex.club-]
//py [-zIndex.clubPop-]
//py [-zIndex.game-]
//py [-zIndex.game_1-]
//py [-zIndex.game_2-]
//py [-zIndex.game_3-]
//py [-zIndex.notice-]
//py [-zIndex.tip-]
//py [-zIndex.tips-]
//py [-zIndex.top-]
constructor() {
this.sceneStruct = new SceneStruct();
//addLayer之前和之后要对scene进行一次对比,如果异常,不进行添加。 继续游戏能看到大厅的bug。
this.zIndex = {
bottom: 0,
login: 1,
hall: 2,
game: 5,
notice: 9,
tip: 10,
top: 12,
webView: 90,//webView 会在最上层,防止出现无法关闭活动界面
}
}
nameScene;
scene;
get stage() {
return cc.find("Canvas");
}
get bottom() {
return cc.find("Canvas/bottom");
}
get camera() {
return cc.find('Canvas/Main Camera')
}
beforeLoadScene() {
let layers = [].concat(this.sceneStruct.getLayers());
if (!layers || layers.length == 0) return;
layers.forEach(layerName => {
this.removeLayer(layerName, true);
})
}
//py [-loadScene(${1:sceneName})-]
loadScene(sceneName, data, prepareFunc) {
// pg.loading.releaseAllRes();
return new Promise((resolve, reject) => {
if (this.nameScene == sceneName) {
resolve();
return console.warn("加载重复的scene->" + sceneName);
}
// this.beforeLoadScene();
setTimeout(() => {
this.sceneStruct.clearLayer();
// if (sceneName != "coclub" && sceneName != "cohall_login") {
// pg.loading.releaseAddAssetList();
// }
// pg.loading.releaseAddAssetList();
// if (!cc.game.isPaused()) {
// cc.game.pause();
// cc.loader.releaseAll();
// }
prepareFunc && prepareFunc();
cc.director.loadScene(sceneName, () => {
// cc.game.resume();
this.beforeLoadScene();//等待加载完成再移除当前场景 3.11 王林
this.nameScene = sceneName;
this.sceneStruct.addScene(sceneName);
event.call(sceneName + "_open", data);
resolve();
});
}, 0);
})
}
preloadScene(sceneName) {
// cc.isValid 判断节点是否被销毁。
return cc.director.preloadScene(sceneName);
}
preLoadLayer(layerName) {
return new Promise((resolve, reject) => {
loading.loadPrefab(layerName).then(prefab => {
resolve();
})
})
}
/*
!#zh
添加子层,并且可以修改该层的层级顺序和名字。
@param layerName 层的预制文件名称(路径在loadPrefab中自动填写)
@param zIndex 层级|zIndex.bottom /zIndex.login
@param data layerName_opn|传输得值
@example
```js
sceneManager.addLayer('login_layer', 1);
```
*/
//py [-addLayer(${1:layerName},${2:pg.scene.zIndex.},${3:data})-]
addLayer(layerName, zIndex, data, forceRepeat = false, path = "") {
return new Promise((resolve, reject) => {
if (!zIndex && zIndex != 0) {
console.warn("addLayer warn->" + "未添加zIndex:" + layerName);
zIndex = this.zIndex.top;
}
if (!forceRepeat && this.sceneStruct.getLayers().some(ln => { return ln == layerName })) {
event.call(layerName + "_open_repeat", data);
return resolve(log.w("addLayer warn->" + "重复添加界面:" + layerName));
}
let uuid = this.stage && this.stage.uuid ? this.stage.uuid : 0;
loading.loadPrefab(layerName, path).then(prefab => {
if (window.game_center.isLoadingGame || window.game_center.isRunningGame) {//|| !window.isInHall
return reject(log.w("dating ..."));
}
if (!this.stage) return reject(log.w("addLayer warn->" + "场景已切换:" + layerName));
if (uuid && uuid != this.stage.uuid) return reject(log.w("addLayer warn->" + "场景已切换:" + layerName));
if (this.sceneStruct.getLayers().indexOf(layerName) != -1) return resolve(log.w("addLayer warn->" + "多次添加界面:" + layerName));
if (zIndex == this.zIndex.bottom) {
this.bottom && this.bottom.addChild(prefab, zIndex, layerName);
// this.sceneStruct.addLayer(layerName);
} else {
this.stage.addChild(prefab, zIndex, layerName);
}
event.call(layerName + "_open", data);
this.sceneStruct.addLayer(layerName);
resolve(prefab);
})
})
}
//py [-removeLayer(${1:layerName})-]
removeLayer(layerName, isRelease = false) {
// if (layerName == "cohall_WaitLayer") {
// console.log("请求移除等待界面");
// }
if (!this.stage) return console.log("removeLayer warn->" + "找不到当前stage")
let node = this.stage.getChildByName(layerName);
if (!node && this.bottom) node = this.bottom.getChildByName(layerName);
if (!node) return (layerName != "cohall_WaitLayer" && layerName != "cohall_SceneWaitLayer") && console.log("removeLayer warn->" + "当前stage找不到“" + layerName + "");
node.removeFromParent(false);
node.destroy();
// if (layerName == "cohall_WaitLayer") {
// console.log("等待界面移除成功");
// }
this.sceneStruct.removeLayer(layerName);
if (isRelease) loading.releasePrefab(layerName, isRelease);
}
backLayer(layerName, isVisible = false) {
return new Promise((resolve, reject) => {
let layer = this.getLayerByName(layerName);
if (!layer) {
pg.scene.addLayer(layerName, pg.scene.zIndex.bottom, {}, false, false).then(layer => {
layer.active = isVisible;
return resolve();
});
return;
}
layer.parent = this.bottom;
layer.zIndex = this.zIndex.bottom;
layer.active = isVisible;
return resolve();
})
}
frontLayer(layerName) {
return new Promise((resolve, reject) => {
let layer = this.getLayerByName(layerName);
if (!layer) {
pg.scene.addLayer(layerName, pg.scene.zIndex.hall).then(layer => {
layer.active = true;
return resolve();
});
return;
} else {
layer.parent = this.stage;
layer.zIndex = this.zIndex.hall;
layer.active = true;
}
return resolve();
})
}
//py [-getLayerByName(${1:layerName})-]
getLayerByName(layerName) {
let node = this.stage.getChildByName(layerName);
if (!node) node = this.bottom.getChildByName(layerName);
return node;
}
clearLayer() {
this.sceneStruct.clearLayer();
}
//py [-isHaveLayer(${1:layerName})-]
isHaveLayer(layerName) {
return !!this.getLayerByName(layerName);
}
getSceneName() {
return this.nameScene;
}
}
/**音频播放部分
*
*
*
*/
let KEY_MUSIC_VOL = "music_vol";
let KEY_EFFECT_VOL = "effect_vol";
class AudioUtil {
static instance;
static getInstance() {
if (!AudioUtil.instance) {
AudioUtil.instance = new AudioUtil();
}
return AudioUtil.instance;
}
constructor() {
this.bgm_volume = 1.0;
this.sfx_volume = 1.0;
this.sfx_button = "button";
this.cur_bgm = "";
this.updateVolume();
// cc.game.on(cc.game.EVENT_HIDE, function () {
// cc.audioEngine.pauseAll();
// });
// cc.game.on(cc.game.EVENT_SHOW, function () {
// cc.audioEngine.resumeAll();
// });
}
updateVolume() {
let vvol = cc.sys.localStorage.getItem(KEY_MUSIC_VOL);
if (vvol != null) {
this.bgm_volume = parseFloat(vvol);
}
let evol = cc.sys.localStorage.getItem(KEY_EFFECT_VOL);
if (evol != null) {
this.sfx_volume = parseFloat(evol);
}
}
get_audio_url(url) {
return url;
}
getSfxVolume() {
return this.sfx_volume;
}
getBgmVolume() {
return this.bgm_volume;
}
clickButton() {
this.playSFX(this.sfx_button);
}
playBGM(url, ispath) {
this.updateVolume();
let us = url.split("/");
let len = us.length;
if (len < 1) return;
let surl = us[len - 1];
if (this.cur_bgm == surl) return;
let audioUrl = ispath ? url : this.get_audio_url(url);
this.load(audioUrl).then((audio) => {
if (this.bgm_audio_id >= 0) {
cc.audioEngine.stop(this.bgm_audio_id);
}
this.bgm_audio_id = cc.audioEngine.play(audio, true, this.bgm_volume);
this.cur_bgm = surl;
})
}
playSFX(url, ispath) {
return new Promise((resolve, reject) => {
let audioUrl = ispath ? url : this.get_audio_url(url);
if (this.sfx_volume > 0) {
this.load(audioUrl).then((audio) => {
let audioId = cc.audioEngine.play(audio, false, this.sfx_volume);
cc.audioEngine.setFinishCallback(audioId, () => {
resolve(audio);
});
})
}
})
}
stopAll() {
cc.audioEngine.stopAll();
this.bgm_audio_id = -1;
this.cur_bgm = "";
}
setSFXVolume(v) {
v = Number(v);
if (this.sfx_volume != v) {
cc.sys.localStorage.setItem("sfxVolume_hbhall", "" + v);
this.sfx_volume = v;
}
}
setBGMVolume(v, force) {
v = Number(v);
if (this.bgm_audio_id >= 0) {
if (v > 0) {
cc.audioEngine.resume(this.bgm_audio_id);
}
else {
cc.audioEngine.pause(this.bgm_audio_id);
}
if (this.bgm_volume != v || force) {
cc.sys.localStorage.setItem("bgmVolume_hbhall", "" + v);
this.bgm_volume = v;
cc.audioEngine.setVolume(this.bgm_audio_id, v);
}
}
}
pauseAll() {
cc.audioEngine.pauseAll();
}
resumeAll() {
cc.audioEngine.resumeAll();
}
load(audioUrl) {
return new Promise((resolve, reject) => {
cc.resources.load(audioUrl, cc.AudioClip, (err, audio) => {
if (err) {
return cc.warn("音效加载失败->" + audioUrl);
}
if (!audio) return cc.warn("音效加载失败->" + audioUrl);
resolve(audio);
});
})
}
playAudioByUrl(audio_url) {
return new Promise((resolve, reject) => {
if (!audio_url) return resolve(null);
cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
const audioId = cc.audioEngine.play(audioClip, false, 0.8);
cc.audioEngine.setFinishCallback(audioId, () => {
resolve(audioClip);
});
});
});
}
}
pg.event = Emitter.getInstance();
pg.audio = AudioUtil.getInstance();
pg.scene = SceneManager.getInstance();
export default pg;
// window.pg = pg;
//EVENT CONFIG DATA NET
//SYSTEM——MANAGER ---配置文件管理,网络管理,事件管理,数据管理
//VIEW——MANAGER ---界面管理,网络数据本地同步,界面事件推送
let pg = {};
//打印
pg.logger = {
d: (str) => {
cc.log(str);
},
w: function (str) {
cc.warn(str);
}
}
const log = pg.logger;
//显示常用
pg.view = {
//显示隐藏
//添加节点
//删除节点
//加载网络节点
touchEnable(item, isEnable) {
if (!item) return pg.logger.w("设置按钮响应失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node) return pg.logger.w("设置按钮响应失败,传入了错误的item");
let btn = node.getComponent(cc.Button);
if (!btn) return pg.logger.w("当前节点没有添加button->" + node.name);
btn.interactable = isEnable;
return true;
},
touchOn(item, callback, target) {
if (!item) return pg.logger.w("添加按钮响应失败,传入了错误的item");
if (!callback || !target) return pg.logger.w("添加按钮响应失败,传入了空回调");
let node = item.node ? item.node : item;
node.on(cc.Node.EventType.TOUCH_END, callback, target);
return true;
},
touchOff(item, callback, target) {
if (!item) return log.w("移除按钮响应失败,传入了错误的item");
if (!callback || !target) return log.w("移除按钮响应失败,传入了空回调");
let node = item.node ? item.node : item;
if (!node || !node.parent) return log.w("节点已移除");
node.off(cc.Node.EventType.TOUCH_END, callback, target);
return true;
},
//更换图片
setImg(item, res) {
return new Promise((resolve, reject) => {
if (!item) return log.w("图片更换失败,传入了错误的item");
if (!res) return log.w("图片更换失败,传入了错误的res");
pg.load.loadImg(res).then((spriteFrame) => {
if (!cc.isValid(item)) return log.i("节点已销毁");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.i("节点已销毁");
let component = node.getComponent(cc.Sprite);
let { width, height } = spriteFrame._rect;
component.spriteFrame = spriteFrame;
resolve({ width, height });
})
})
},
setNetImg(item, res) {
return new Promise((resolve, reject) => {
if (!item) return log.w("图片更换失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!res) {
node.active = false;
return log.w("图片更换失败,传入了错误的res");
}
if (!node) return log.w("图片更换失败,传入了错误的item");
if (node.net_url == res) return;
let w = node.width;
let h = node.height;
node.active = false;//
pg.load.loadNetImg(res).then((texture) => {
if (!cc.isValid(node)) return log.i("节点已销毁");
let nw = node.width = texture.width;
let nh = node.height = texture.height;
let component = node.getComponent(cc.Sprite);
let spriteFrame = new cc.SpriteFrame(texture);
component.spriteFrame = spriteFrame;
node.net_url = res;
let a = w / nw;//100 2000 0.05
let b = h / nh;//100 1000 0.1
if (a < b) {
node.width = a * nw;
node.height = a * nh;
} else {
node.width = b * nw;
node.height = b * nh;
}
node.active = true;
resolve({ w: nw, h: nh });
})
})
},
visible(item, isVisible) {
if (!item) return log.w("节点显示失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node || !node.parent) return log.w("节点已移除");
node.active = isVisible;
return true;
},
setString(item, text, count = 0) {
if (!item) return log.w("节点text失败,传入了错误的item");
if (count > 0) {
function parse_str(str, count) {
if (!str) return "";
var segmants = str.split('+');
str = segmants.join('');
var len = 0;
var idx = 0;
for (var i = 0; i < str.length; i++) {
var p = /[^x00-xff]/g;
var a = str.charAt(i);
if (p.test(a)) {
len += 2;
idx++;
}
else {
len += 1;
idx++;
}
if (len >= count * 2)
break;
}
return str.substr(0, idx);
}
text = parse_str(text, count);
}
let node = item.node ? item.node : item;
if (!node) return;
let component = node.getComponent(cc.Label);//组件功能 非node的功能
component.string = text;
return true;
},
setColor(item, color, outlineWidth = -1) {
if (!item) return log.w("setColor warn->传入了错误的item");
let RGB = this.colorRgb(color);
if (!RGB || RGB.length == 0) return log.w("color ->传入了错误的color");
item.color = new cc.Color(RGB[0], RGB[1], RGB[2]);
if (outlineWidth < 0) return;
let LabelOutline = item.getComponent(cc.LabelOutline);
if (!LabelOutline) return log.w("LabelOutline warn->未添加描边");
LabelOutline.width = outlineWidth;
},
colorRgb(color) {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var sColor = color;
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return sColorChange;
} else {
return sColor;
}
},
find(item, childPath) {
if (typeof item == "string") {
childPath = item;
item = null;
}
if (!childPath || childPath == '' || typeof childPath != 'string') return log.w("findChildByPath error->" + "请传入路径");
let child = null;
if (item) {
let node = item.node ? item.node : item;
if (!node.children || node.children.length == 0) return log.w("findChild error->" + "找不到此节点,请检查层级路径:" + childPath);
child = cc.find(childPath, node);
} else {
child = cc.find(childPath);
}
if (!child) return log.w("findChildByPath error->" + "找不到此节点,请检查层级路径:" + childPath);
return child;
},
addChild(item, child, zIndex) {
if (!child) return console.log("addChild error ->请传入子节点");
if (!item) return console.log("addChild error ->请传入父节点");
let node = item.node ? item.node : item;
if (!node) return console.log("addChild error ->请传入父节点");
if (child.parent)
return log.w("此节点已经有父节点->" + child.name);
if (zIndex >= 0) {
node.addChild(child, zIndex)
} else {
node.addChild(child);
}
return true;
},
removeSelf(item) {
if (!item) return log.w("节点移除失败,传入了错误的item");
let node = item.node ? item.node : item;
node.removeFromParent();
node.destroy();
},
removChildren(item) {
if (!item) return log.w("节点remove失败,传入了错误的item");
let node = item.node ? item.node : item;
if (!node.parent) return log.w("节点remove失败,传入了错误的item");
node.removeAllChildren();
return true;
},
removeChild(item, child) {
if (!item) return log.w("节点remove失败,传入了错误的item");
let node = item.node ? item.node : item;
if (child.parent && child.parent == node) {
node.removeChild(child);
node.destroy();
}
return true;
},
playSpineAnimation(item, aniName, loop) {
if (!item || !cc.isValid(item)) return log.w("动画播放失败,传入了错误的item");
if (!aniName) return log.w("动画播放失败,传入了错误的aniName");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.w("节点已销毁");
let skl = node.getComponent(sp.Skeleton);
skl.setAnimation(0, aniName, loop);
return skl;
},
playDragonBone(item, aniName, loop) {
if (!item || !cc.isValid(item)) return log.w("动画播放失败,传入了错误的item");
if (!aniName) return log.w("动画播放失败,传入了错误的aniName");
let node = item.node ? item.node : item;
if (!cc.isValid(node)) return log.w("节点已销毁");
let dba = node.getComponent(dragonBones.ArmatureDisplay);
dba.playAnimation(aniName, loop);
return dba;
},
cloneNode(node) {
return cc.instantiate(node);
}
}
//加载 未封装bundle
pg.load = {
loadRes: function (res, type, bundleName) {
// cc.assetManager.loadBundle('hall', (err, bundle) => {
// if (err) return cc.error(err);
// cc.director.loadScene("hall", () => { });
// });
// cc.assetManager.loadBundle('chess', (err, bundle) => {
// if (err) return cc.error(err);
// cc.director.loadScene("chess", () => {
// // //清理hall的资源
// // let hallBundle = cc.assetManager.getBundle(`hall`);
// // hallBundle.releaseAll();
// // cc.assetManager.removeBundle(hallBundle);
// });
// });
//此处需要二次封装,新的存在assetbundle
return new Promise((resolve, reject) => {
cc.loader.loadRes(res, type, (err, data) => {
if (err && !data) return resolve(pg.logger.d('loading loadRes error-> ', res));
resolve(data);
});
})
},
loadImg: function () {
return new Promise((resolve, reject) => {
this.loadRes(url, cc.SpriteFrame).then((data) => {
if (!data || data.length == 0) return;
resolve(data);
})
})
},
loadPrefab: function (path = "") {
return new Promise((resolve, reject) => {
url = "/prefabs/" + path;
this.loadRes(url, cc.Prefab).then((data) => {
if (!data || data.length == 0) return reject();
return resolve(cc.instantiate(data));
})
})
},
loadNetImg: function (url) {
return new Promise((resolve, reject) => {
cc.loader.load({ url }, (err, texture) => {
if (err && !data) return resolve(pg.logger.w('loading loadRes warn-> ', res));
resolve(texture);
});
})
},
}
//本地存储
pg.localStorage = {
setItem: function (key, val) {
cc.sys.localStorage.setItem(key, val);
},
getItem: function (key, defVal) {
return cc.sys.localStorage.getItem(key) || defVal;
}
}
//HTTP网络请求
pg.http = {
send: function (type = "GET", url, data, callback) {
let xhr = cc.loader.getXMLHttpRequest();
xhr.timeout = 5000;
xhr.responseType = "text";
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 300) {
try {
let resp = xhr.responseText;
pg.logger.d("resp->" + JSON.stringify(resp));
callback(resp);
} catch (e) {
}
}
else {
}
};
xhr.onerror = (e) => {
pg.logger.w("onerror->" + url);
};
xhr.ontimeout = (e) => {
pg.logger.w("ontimeout->" + url);
};
xhr.send(data);
}
}
/**事件监听部分
*
*
*
*/
class Emitter {
static instance;
static getInstance() {
if (!Emitter.instance) {
Emitter.instance = new Emitter();
}
return Emitter.instance;
}
constructor() {
this._callbacks = {};
return this;
}
on(event, fn) {
(this._callbacks[event] = this._callbacks[event] || []).push(fn);
};
once(event, fn) {
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
};
off(event, fn) {
// all
if (0 == arguments.length) {
this._callbacks = {};
return;
}
// specific event
let callbacks = this._callbacks[event];
if (!callbacks) return;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return;
}
// remove specific handler
let cb;
for (let i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return;
}
emit(event, ...args) {
this._callbacks = this._callbacks || {};
// let args = [].slice.call(arguments, 1);
let callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (let i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
}
listeners(event) {
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
hasListeners(event) {
return !!this.listeners(event).length;
};
}
class SceneStruct {
constructor() {
this.nowScene = "hb_login";
this.sceneObject = {};
this.sceneObject[this.nowScene] = [];
}
addScene(sceneName) {
this.nowScene = sceneName;
//if (!this.sceneObject[this.nowScene])
this.sceneObject[this.nowScene] = [];
}
addLayer(layerName) {
if (!this.sceneObject[this.nowScene]) return console.log("sceneStruct err->scene未初始化:" + this.nowScene)
if (!this.sceneObject[this.nowScene].includes(layerName)) {
this.sceneObject[this.nowScene].push(layerName);
}
}
removeLayer(layerName) {
if (!this.sceneObject[this.nowScene]) return console.log("sceneStruct err->scene未初始化:" + this.nowScene)
let arr = this.sceneObject[this.nowScene];
let isSuccess = false;
for (let i = arr.length - 1; i >= 0; i--) {
let laName = arr[i];
if (layerName == laName) {
isSuccess = true;
arr.splice(i, 1);
}
}
if (!isSuccess) {
console.log("sceneStruct err->scene没有对应layer:" + this.nowScene + ">" + layerName);
}
}
clearLayer() {
this.sceneObject[this.nowScene] = [];
}
getLayers() {
return this.sceneObject[this.nowScene] || [];
}
}
class SceneManager {
static debug = true;
static instance;
static getInstance() {
if (!SceneManager.instance) {
SceneManager.instance = new SceneManager();
}
return SceneManager.instance;
}
//py [-zIndex.bottom-]
//py [-zIndex.login-]
//py [-zIndex.hall-]
//py [-zIndex.club-]
//py [-zIndex.clubPop-]
//py [-zIndex.game-]
//py [-zIndex.game_1-]
//py [-zIndex.game_2-]
//py [-zIndex.game_3-]
//py [-zIndex.notice-]
//py [-zIndex.tip-]
//py [-zIndex.tips-]
//py [-zIndex.top-]
constructor() {
this.sceneStruct = new SceneStruct();
//addLayer之前和之后要对scene进行一次对比,如果异常,不进行添加。 继续游戏能看到大厅的bug。
this.zIndex = {
bottom: 0,
login: 1,
hall: 2,
game: 5,
notice: 9,
tip: 10,
top: 12,
webView: 90,//webView 会在最上层,防止出现无法关闭活动界面
}
}
nameScene;
scene;
get stage() {
return cc.find("Canvas");
}
get bottom() {
return cc.find("Canvas/bottom");
}
get camera() {
return cc.find('Canvas/Main Camera')
}
beforeLoadScene() {
let layers = [].concat(this.sceneStruct.getLayers());
if (!layers || layers.length == 0) return;
layers.forEach(layerName => {
this.removeLayer(layerName, true);
})
}
//py [-loadScene(${1:sceneName})-]
loadScene(sceneName, data, prepareFunc) {
// pg.loading.releaseAllRes();
return new Promise((resolve, reject) => {
if (this.nameScene == sceneName) {
resolve();
return console.warn("加载重复的scene->" + sceneName);
}
// this.beforeLoadScene();
setTimeout(() => {
this.sceneStruct.clearLayer();
// if (sceneName != "coclub" && sceneName != "cohall_login") {
// pg.loading.releaseAddAssetList();
// }
// pg.loading.releaseAddAssetList();
// if (!cc.game.isPaused()) {
// cc.game.pause();
// cc.loader.releaseAll();
// }
prepareFunc && prepareFunc();
cc.director.loadScene(sceneName, () => {
// cc.game.resume();
this.beforeLoadScene();//等待加载完成再移除当前场景 3.11 王林
this.nameScene = sceneName;
this.sceneStruct.addScene(sceneName);
event.call(sceneName + "_open", data);
resolve();
});
}, 0);
})
}
preloadScene(sceneName) {
// cc.isValid 判断节点是否被销毁。
return cc.director.preloadScene(sceneName);
}
preLoadLayer(layerName) {
return new Promise((resolve, reject) => {
loading.loadPrefab(layerName).then(prefab => {
resolve();
})
})
}
/*
!#zh
添加子层,并且可以修改该层的层级顺序和名字。
@param layerName 层的预制文件名称(路径在loadPrefab中自动填写)
@param zIndex 层级|zIndex.bottom /zIndex.login
@param data layerName_opn|传输得值
@example
```js
sceneManager.addLayer('login_layer', 1);
```
*/
//py [-addLayer(${1:layerName},${2:pg.scene.zIndex.},${3:data})-]
addLayer(layerName, zIndex, data, forceRepeat = false, path = "") {
return new Promise((resolve, reject) => {
if (!zIndex && zIndex != 0) {
console.warn("addLayer warn->" + "未添加zIndex:" + layerName);
zIndex = this.zIndex.top;
}
if (!forceRepeat && this.sceneStruct.getLayers().some(ln => { return ln == layerName })) {
event.call(layerName + "_open_repeat", data);
return resolve(log.w("addLayer warn->" + "重复添加界面:" + layerName));
}
let uuid = this.stage && this.stage.uuid ? this.stage.uuid : 0;
loading.loadPrefab(layerName, path).then(prefab => {
if (window.game_center.isLoadingGame || window.game_center.isRunningGame) {//|| !window.isInHall
return reject(log.w("dating ..."));
}
if (!this.stage) return reject(log.w("addLayer warn->" + "场景已切换:" + layerName));
if (uuid && uuid != this.stage.uuid) return reject(log.w("addLayer warn->" + "场景已切换:" + layerName));
if (this.sceneStruct.getLayers().indexOf(layerName) != -1) return resolve(log.w("addLayer warn->" + "多次添加界面:" + layerName));
if (zIndex == this.zIndex.bottom) {
this.bottom && this.bottom.addChild(prefab, zIndex, layerName);
// this.sceneStruct.addLayer(layerName);
} else {
this.stage.addChild(prefab, zIndex, layerName);
}
event.call(layerName + "_open", data);
this.sceneStruct.addLayer(layerName);
resolve(prefab);
})
})
}
//py [-removeLayer(${1:layerName})-]
removeLayer(layerName, isRelease = false) {
// if (layerName == "cohall_WaitLayer") {
// console.log("请求移除等待界面");
// }
if (!this.stage) return console.log("removeLayer warn->" + "找不到当前stage")
let node = this.stage.getChildByName(layerName);
if (!node && this.bottom) node = this.bottom.getChildByName(layerName);
if (!node) return (layerName != "cohall_WaitLayer" && layerName != "cohall_SceneWaitLayer") && console.log("removeLayer warn->" + "当前stage找不到“" + layerName + "");
node.removeFromParent(false);
node.destroy();
// if (layerName == "cohall_WaitLayer") {
// console.log("等待界面移除成功");
// }
this.sceneStruct.removeLayer(layerName);
if (isRelease) loading.releasePrefab(layerName, isRelease);
}
backLayer(layerName, isVisible = false) {
return new Promise((resolve, reject) => {
let layer = this.getLayerByName(layerName);
if (!layer) {
pg.scene.addLayer(layerName, pg.scene.zIndex.bottom, {}, false, false).then(layer => {
layer.active = isVisible;
return resolve();
});
return;
}
layer.parent = this.bottom;
layer.zIndex = this.zIndex.bottom;
layer.active = isVisible;
return resolve();
})
}
frontLayer(layerName) {
return new Promise((resolve, reject) => {
let layer = this.getLayerByName(layerName);
if (!layer) {
pg.scene.addLayer(layerName, pg.scene.zIndex.hall).then(layer => {
layer.active = true;
return resolve();
});
return;
} else {
layer.parent = this.stage;
layer.zIndex = this.zIndex.hall;
layer.active = true;
}
return resolve();
})
}
//py [-getLayerByName(${1:layerName})-]
getLayerByName(layerName) {
let node = this.stage.getChildByName(layerName);
if (!node) node = this.bottom.getChildByName(layerName);
return node;
}
clearLayer() {
this.sceneStruct.clearLayer();
}
//py [-isHaveLayer(${1:layerName})-]
isHaveLayer(layerName) {
return !!this.getLayerByName(layerName);
}
getSceneName() {
return this.nameScene;
}
}
/**音频播放部分
*
*
*
*/
let KEY_MUSIC_VOL = "music_vol";
let KEY_EFFECT_VOL = "effect_vol";
class AudioUtil {
static instance;
static getInstance() {
if (!AudioUtil.instance) {
AudioUtil.instance = new AudioUtil();
}
return AudioUtil.instance;
}
constructor() {
this.bgm_volume = 1.0;
this.sfx_volume = 1.0;
this.sfx_button = "button";
this.cur_bgm = "";
this.updateVolume();
// cc.game.on(cc.game.EVENT_HIDE, function () {
// cc.audioEngine.pauseAll();
// });
// cc.game.on(cc.game.EVENT_SHOW, function () {
// cc.audioEngine.resumeAll();
// });
}
updateVolume() {
let vvol = cc.sys.localStorage.getItem(KEY_MUSIC_VOL);
if (vvol != null) {
this.bgm_volume = parseFloat(vvol);
}
let evol = cc.sys.localStorage.getItem(KEY_EFFECT_VOL);
if (evol != null) {
this.sfx_volume = parseFloat(evol);
}
}
get_audio_url(url) {
return url;
}
getSfxVolume() {
return this.sfx_volume;
}
getBgmVolume() {
return this.bgm_volume;
}
clickButton() {
this.playSFX(this.sfx_button);
}
playBGM(url, ispath) {
this.updateVolume();
let us = url.split("/");
let len = us.length;
if (len < 1) return;
let surl = us[len - 1];
if (this.cur_bgm == surl) return;
let audioUrl = ispath ? url : this.get_audio_url(url);
this.load(audioUrl).then((audio) => {
if (this.bgm_audio_id >= 0) {
cc.audioEngine.stop(this.bgm_audio_id);
}
this.bgm_audio_id = cc.audioEngine.play(audio, true, this.bgm_volume);
this.cur_bgm = surl;
})
}
playSFX(url, ispath) {
return new Promise((resolve, reject) => {
let audioUrl = ispath ? url : this.get_audio_url(url);
if (this.sfx_volume > 0) {
this.load(audioUrl).then((audio) => {
let audioId = cc.audioEngine.play(audio, false, this.sfx_volume);
cc.audioEngine.setFinishCallback(audioId, () => {
resolve(audio);
});
})
}
})
}
stopAll() {
cc.audioEngine.stopAll();
this.bgm_audio_id = -1;
this.cur_bgm = "";
}
setSFXVolume(v) {
v = Number(v);
if (this.sfx_volume != v) {
cc.sys.localStorage.setItem("sfxVolume_hbhall", "" + v);
this.sfx_volume = v;
}
}
setBGMVolume(v, force) {
v = Number(v);
if (this.bgm_audio_id >= 0) {
if (v > 0) {
cc.audioEngine.resume(this.bgm_audio_id);
}
else {
cc.audioEngine.pause(this.bgm_audio_id);
}
if (this.bgm_volume != v || force) {
cc.sys.localStorage.setItem("bgmVolume_hbhall", "" + v);
this.bgm_volume = v;
cc.audioEngine.setVolume(this.bgm_audio_id, v);
}
}
}
pauseAll() {
cc.audioEngine.pauseAll();
}
resumeAll() {
cc.audioEngine.resumeAll();
}
load(audioUrl) {
return new Promise((resolve, reject) => {
cc.resources.load(audioUrl, cc.AudioClip, (err, audio) => {
if (err) {
return cc.warn("音效加载失败->" + audioUrl);
}
if (!audio) return cc.warn("音效加载失败->" + audioUrl);
resolve(audio);
});
})
}
playAudioByUrl(audio_url) {
return new Promise((resolve, reject) => {
if (!audio_url) return resolve(null);
cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
const audioId = cc.audioEngine.play(audioClip, false, 0.8);
cc.audioEngine.setFinishCallback(audioId, () => {
resolve(audioClip);
});
});
});
}
}
pg.event = Emitter.getInstance();
pg.audio = AudioUtil.getInstance();
pg.scene = SceneManager.getInstance();
export default pg;
// window.pg = pg;
//EVENT CONFIG DATA NET
//SYSTEM——MANAGER ---配置文件管理,网络管理,事件管理,数据管理
//VIEW——MANAGER ---界面管理,网络数据本地同步,界面事件推送
//VIEW ---界面效果,滚动等等
\ No newline at end of file
class CalculativeResize {
static resizeInfo() {
//0.设计尺寸
let baseSize = cc.size(1920, 1080);
//1.获取屏幕尺寸
let canvasSize = cc.view.getCanvasSize();
//2.将屏幕宽高 以高度对齐的方式 换算出场景 宽度
let sumSize = cc.size(canvasSize.width * baseSize.height / canvasSize.height, baseSize.height)
//3.计算场景宽度与设计宽度比率
let scaleX = sumSize.width / baseSize.width;
let posX = sumSize.width - baseSize.width;
//高屏幕适配
if (scaleX <= 1) {
let sumSize = cc.size(baseSize.width, canvasSize.height * baseSize.width / canvasSize.width)
let scaleY = sumSize.height / baseSize.height;
let posY = sumSize.height - baseSize.height;
// let posY = sumSize.height * (1 - 1 / scaleX);
return { scaleX: 1, scaleY: scaleY, posX: 0, orgX: 0, posY: posY, orgY: - posY / 2 }
}
//需要拓展的宽度缩放比
return { scaleX: scaleX, scaleY: 1, posX: posX, orgX: - posX / 2, posY: 0, orgY: 0 };
}
}
//关于齐刘海的适配方案。
//1.需要获取对应的手机型号
//2.需要写上安全间距标记(主要是中间部分)
//3.不同的手机安全间距可能不同。(主要适配iPhone X)
cc.Class({
extends: cc.Component,
properties: {
r_width: 1,
r_height: 1,
r_top: 0,
r_bottom: 0,
p_left: 0,
p_right: 0,
p_top: 0,
p_bottom: 0,
black: 0,//用于不能直接缩放的图片(如引导),两边补齐黑边
noHead: 0,
debug: 0,
},
// LIFE-CYCLE CALLBACKS:
onLoad() {
let { scaleX, posX, scaleY, posY } = CalculativeResize.resizeInfo();
this.resizeScaleX = scaleX;
this.resizeScaleY = scaleY;
this.posX = posX;
this.posY = posY;
let { width, height, x, y } = this.node;
this.nodeWidth = width;
this.nodeHeight = height;
this.nodeX = x;
this.nodeY = y;
//增加一个resize的监听,当屏幕出现宽高比变化的时候,进行一次重新适配。
//主要用于刘海屏的重置,以及动态屏幕变化的控制(虚拟按键屏)。
},
start() {
this.resize();
},
update(dt) {
},
onDestroy() {
if (this.black1)
pg.view.removChildren(this.black1);
if (this.black2)
pg.view.removChildren(this.black2);
this.black1 = null;
this.black2 = null;
},
resize() {
if (!this.resizeScaleX && !this.nodeWidth) {
console.warn("手动调用此方法时,不能再onLoad中使用");
return;
}
this.resizeHeight();
this.resizeWidth();
},
//高屏幕适配
resizeHeight() {
if (this.resizeScaleY <= 1.05) return;
let scaleY = this.resizeScaleY;
let posY = this.posY;
let nodeWidth = this.nodeWidth;
let nodeHeight = this.nodeHeight;
let nodeX = this.nodeX;
let nodeY = this.nodeY;
if (this.debug == 1) {
console.log("断点调试点");
}
//宽度拉伸
if (this.r_width == 1) {
this.node.width = nodeWidth * scaleY;
}
//高度拉升
if (this.r_height == 1) {
this.node.height = nodeHeight * scaleY;
// //高度拉伸后,图片顶部齐边【坐标下移】 y坐标下移
// if (this.r_top == 1) {
// this.node.y = nodeY - nodeHeight * (scaleY - 1) / 2;
// }
// //高度拉伸后,图片底部齐边【坐标上移】 y坐标上移
// if (this.r_bottom == 1) {
// this.node.y = nodeY + nodeHeight * (scaleY - 1) / 2;
// }
}
// //如果是刘海屏,减去对应的刘海屏的宽度
// let lhpSize = { top: 0, bottom: 0 };
// //动态左移
// if (this.p_left == 1) {
// this.node.x = nodeX - posX / 2 + lhpSize.top;
// }
// //动态右移
// if (this.p_right == 1) {
// this.node.x = nodeX + posX / 2 - lhpSize.bottom;
// }
//动态上移
if (this.p_top == 1) {
this.node.y = nodeY + posY / 2 *0.75
}
//动态下移
if (this.p_bottom == 1) {
this.node.y = nodeY - posY / 2 *0.75
}
},
//长屏幕适配
resizeWidth() {
if (this.resizeScaleX <= 1.05) return;
let resizeScaleX = this.resizeScaleX;
let posX = this.posX;
let nodeWidth = this.nodeWidth;
let nodeHeight = this.nodeHeight;
let nodeX = this.nodeX;
let nodeY = this.nodeY;
if (this.debug == 1) {
console.log("断点调试点");
}
//宽度拉伸
if (this.r_width == 1) {
this.node.width = nodeWidth * resizeScaleX;
}
//高度拉升
if (this.r_height == 1) {
this.node.height = nodeHeight * resizeScaleX;
//高度拉伸后,图片顶部齐边【坐标下移】 y坐标下移
if (this.r_top == 1) {
this.node.y = nodeY - nodeHeight * (resizeScaleX - 1) / 2;
}
//高度拉伸后,图片底部齐边【坐标上移】 y坐标上移
if (this.r_bottom == 1) {
this.node.y = nodeY + nodeHeight * (resizeScaleX - 1) / 2;
}
}
if (this.black == 1) {
let baseSize = cc.size(1280, 720);
this.black1 = this.createBalck();
this.black2 = this.createBalck();
let curWidth = nodeWidth * resizeScaleX;
let curHeight = nodeHeight * resizeScaleX;
let blackWidth = (curWidth - baseSize.width) / 2;
let blackHeight = curHeight;
this.black1.width = blackWidth;
this.black1.height = blackHeight;
this.black2.width = blackWidth;
this.black2.height = blackHeight;
this.black1.x = - baseSize.width / 2 - this.black1.width / 2;
this.black2.x = baseSize.width / 2 + this.black1.width / 2;
this.black1.y = this.black2.y = nodeY;
pg.view.addChild(this.node, this.black1);
pg.view.addChild(this.node, this.black2);
this.black1.active = false;
this.black2.active = false;
if (this.node.nodeData && (this.node.nodeData.bg != "" && this.node.nodeData.bg != "rect")) {
this.black1.active = true;
this.black2.active = true;
}
}
//如果是刘海屏,减去对应的刘海屏的宽度
let lhpSize = { top: 0, bottom: 0 };
if (!this.noHead && posX != 0) lhpSize = { top: 44 * 1.5, bottom: 34 * 1.5 };
//动态左移
if (this.p_left == 1) {
this.node.x = nodeX - posX / 2 + lhpSize.top;
}
//动态右移
if (this.p_right == 1) {
this.node.x = nodeX + posX / 2 - lhpSize.bottom;
}
},
//屏幕适配--end
createBalck() {
let black = cc.instantiate(cc.find('Canvas/blackBg'));
return black;
},
setBlackActive(val) {
if (this.black1)
this.black1.active = val;
if (this.black2)
this.black2.active = val;
}
});
class CalculativeResize {
static resizeInfo() {
//0.设计尺寸
let baseSize = cc.size(1920, 1080);
//1.获取屏幕尺寸
let canvasSize = cc.view.getCanvasSize();
//2.将屏幕宽高 以高度对齐的方式 换算出场景 宽度
let sumSize = cc.size(canvasSize.width * baseSize.height / canvasSize.height, baseSize.height)
//3.计算场景宽度与设计宽度比率
let scaleX = sumSize.width / baseSize.width;
let posX = sumSize.width - baseSize.width;
//高屏幕适配
if (scaleX <= 1) {
let sumSize = cc.size(baseSize.width, canvasSize.height * baseSize.width / canvasSize.width)
let scaleY = sumSize.height / baseSize.height;
let posY = sumSize.height - baseSize.height;
// let posY = sumSize.height * (1 - 1 / scaleX);
return { scaleX: 1, scaleY: scaleY, posX: 0, orgX: 0, posY: posY, orgY: - posY / 2 }
}
//需要拓展的宽度缩放比
return { scaleX: scaleX, scaleY: 1, posX: posX, orgX: - posX / 2, posY: 0, orgY: 0 };
}
}
//关于齐刘海的适配方案。
//1.需要获取对应的手机型号
//2.需要写上安全间距标记(主要是中间部分)
//3.不同的手机安全间距可能不同。(主要适配iPhone X)
cc.Class({
extends: cc.Component,
properties: {
r_width: 1,
r_height: 1,
r_top: 0,
r_bottom: 0,
p_left: 0,
p_right: 0,
p_top: 0,
p_bottom: 0,
black: 0,//用于不能直接缩放的图片(如引导),两边补齐黑边
noHead: 0,
debug: 0,
},
// LIFE-CYCLE CALLBACKS:
onLoad() {
let { scaleX, posX, scaleY, posY } = CalculativeResize.resizeInfo();
this.resizeScaleX = scaleX;
this.resizeScaleY = scaleY;
this.posX = posX;
this.posY = posY;
let { width, height, x, y } = this.node;
this.nodeWidth = width;
this.nodeHeight = height;
this.nodeX = x;
this.nodeY = y;
//增加一个resize的监听,当屏幕出现宽高比变化的时候,进行一次重新适配。
//主要用于刘海屏的重置,以及动态屏幕变化的控制(虚拟按键屏)。
},
start() {
this.resize();
},
update(dt) {
},
onDestroy() {
if (this.black1)
pg.view.removChildren(this.black1);
if (this.black2)
pg.view.removChildren(this.black2);
this.black1 = null;
this.black2 = null;
},
resize() {
if (!this.resizeScaleX && !this.nodeWidth) {
console.warn("手动调用此方法时,不能再onLoad中使用");
return;
}
this.resizeHeight();
this.resizeWidth();
},
//高屏幕适配
resizeHeight() {
if (this.resizeScaleY <= 1.05) return;
let scaleY = this.resizeScaleY;
let posY = this.posY;
let nodeWidth = this.nodeWidth;
let nodeHeight = this.nodeHeight;
let nodeX = this.nodeX;
let nodeY = this.nodeY;
if (this.debug == 1) {
console.log("断点调试点");
}
//宽度拉伸
if (this.r_width == 1) {
this.node.width = nodeWidth * scaleY;
}
//高度拉升
if (this.r_height == 1) {
this.node.height = nodeHeight * scaleY;
// //高度拉伸后,图片顶部齐边【坐标下移】 y坐标下移
// if (this.r_top == 1) {
// this.node.y = nodeY - nodeHeight * (scaleY - 1) / 2;
// }
// //高度拉伸后,图片底部齐边【坐标上移】 y坐标上移
// if (this.r_bottom == 1) {
// this.node.y = nodeY + nodeHeight * (scaleY - 1) / 2;
// }
}
// //如果是刘海屏,减去对应的刘海屏的宽度
// let lhpSize = { top: 0, bottom: 0 };
// //动态左移
// if (this.p_left == 1) {
// this.node.x = nodeX - posX / 2 + lhpSize.top;
// }
// //动态右移
// if (this.p_right == 1) {
// this.node.x = nodeX + posX / 2 - lhpSize.bottom;
// }
//动态上移
if (this.p_top == 1) {
this.node.y = nodeY + posY / 2 *0.75
}
//动态下移
if (this.p_bottom == 1) {
this.node.y = nodeY - posY / 2 *0.75
}
},
//长屏幕适配
resizeWidth() {
if (this.resizeScaleX <= 1.05) return;
let resizeScaleX = this.resizeScaleX;
let posX = this.posX;
let nodeWidth = this.nodeWidth;
let nodeHeight = this.nodeHeight;
let nodeX = this.nodeX;
let nodeY = this.nodeY;
if (this.debug == 1) {
console.log("断点调试点");
}
//宽度拉伸
if (this.r_width == 1) {
this.node.width = nodeWidth * resizeScaleX;
}
//高度拉升
if (this.r_height == 1) {
this.node.height = nodeHeight * resizeScaleX;
//高度拉伸后,图片顶部齐边【坐标下移】 y坐标下移
if (this.r_top == 1) {
this.node.y = nodeY - nodeHeight * (resizeScaleX - 1) / 2;
}
//高度拉伸后,图片底部齐边【坐标上移】 y坐标上移
if (this.r_bottom == 1) {
this.node.y = nodeY + nodeHeight * (resizeScaleX - 1) / 2;
}
}
if (this.black == 1) {
let baseSize = cc.size(1280, 720);
this.black1 = this.createBalck();
this.black2 = this.createBalck();
let curWidth = nodeWidth * resizeScaleX;
let curHeight = nodeHeight * resizeScaleX;
let blackWidth = (curWidth - baseSize.width) / 2;
let blackHeight = curHeight;
this.black1.width = blackWidth;
this.black1.height = blackHeight;
this.black2.width = blackWidth;
this.black2.height = blackHeight;
this.black1.x = - baseSize.width / 2 - this.black1.width / 2;
this.black2.x = baseSize.width / 2 + this.black1.width / 2;
this.black1.y = this.black2.y = nodeY;
pg.view.addChild(this.node, this.black1);
pg.view.addChild(this.node, this.black2);
this.black1.active = false;
this.black2.active = false;
if (this.node.nodeData && (this.node.nodeData.bg != "" && this.node.nodeData.bg != "rect")) {
this.black1.active = true;
this.black2.active = true;
}
}
//如果是刘海屏,减去对应的刘海屏的宽度
let lhpSize = { top: 0, bottom: 0 };
if (!this.noHead && posX != 0) lhpSize = { top: 44 * 1.5, bottom: 34 * 1.5 };
//动态左移
if (this.p_left == 1) {
this.node.x = nodeX - posX / 2 + lhpSize.top;
}
//动态右移
if (this.p_right == 1) {
this.node.x = nodeX + posX / 2 - lhpSize.bottom;
}
},
//屏幕适配--end
createBalck() {
let black = cc.instantiate(cc.find('Canvas/blackBg'));
return black;
},
setBlackActive(val) {
if (this.black1)
this.black1.active = val;
if (this.black2)
this.black2.active = val;
}
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment