Commit a318d934 authored by Tt's avatar Tt

OP15

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