最近接到一個任務要開發消消樂小遊戲,固然首先就想到樂cocosCreator來做爲開發工具。 開發自己倒沒有多少難點。消消樂的開發官網發行的書上有專門講到。下面主要總結一下開發中遇到的問題以及解決方法node
因爲設計尺寸是750*1336,若是適應高度,則在iphonX下,內容會超出屏幕寬度。按寬適應,iphon4下內容會超出屏幕高度。因此就須要根據屏幕比例來動態設置適配策略。nginx
onLoad() {
var canvas = this.canvas
var designResolution = canvas.designResolution
var viewSize = cc.view.getFrameSize()
if (viewSize.width/viewSize.height > designResolution.width/designResolution.height)
{
canvas.fitHeight = true
}
else{
canvas.fitWidth = true
}
}
複製代碼
因爲微信頭像顯示涉及到跨域問題,因此我在咱們遊戲所在服務器上用nginx設置了反向代理來解決跨域問題,並把獲取到的微信頭像地址域名替換成服務器所在域名npm
let url = userObj.headimgurl.replace('http://thirdwx.qlogo.cn',
'咱們的服務器域名');
cc.loader.load({ url, type: 'png' }, (err, res) => {
Message.hide();
this.node.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(res);
});
複製代碼
因爲要根據動態地址生成二維碼這裏用到QR.js+graphics來實現。首先引入QR.js(npm上能夠找到)並設置爲插件引入。 在所在節點上添加Graphics。而後用以下代碼生成二維碼canvas
//生成二維碼
createrQR() {
const urlString = 'http://xxxxxx';
const graphics = this.qrNode.getComponent(cc.Graphics);
// return
graphics.clear();
//背景色
graphics.fillColor = cc.Color.WHITE;
//let rect = this.node.getBoundingBox();
let width = this.qrNode.width;
graphics.rect(0 - width * 0.5, 0 - width * 0.5, width, width);
graphics.fill();
graphics.close();
//生成二維碼數據
let qrcode = new QRCode(-1, 2);
qrcode.addData(urlString);
qrcode.make();
graphics.fillColor = cc.Color.BLACK;
let size = width - 10 * 2;
let num = qrcode.getModuleCount();
let tileW = size / num;
let tileH = size / num;
let w = Math.ceil(tileW);
let h = Math.ceil(tileH);
for (let row = 0; row < num; row++) {
for (let col = 0; col < num; col++) {
if (qrcode.isDark(row, col)) {
graphics.rect(10 + col * tileW - width * 0.5, size - tileH - Math.round(row * tileH) + 10 - width * 0.5, w, h);
graphics.fill();
}
}
}
}
複製代碼
//截屏
capture() {
cc.director.on(cc.Director.EVENT_AFTER_DRAW, this.callback.bind(this));
}
callback() {
let canvas = document.getElementById("GameCanvas") as HTMLCanvasElement;
let baseUrl = canvas.toDataURL("imagea/png");
cc.director.off(cc.Director.EVENT_AFTER_DRAW);
this.showImgDiv(baseUrl)
}
複製代碼
在初始場景上添加一個節點,節點的層級要比場景的canvas高才能看的到音樂圖標。而後在節點上添加一個Sprite,把音樂圖標加入上面。在該節點上添加以下代碼將該節點設置爲常駐節點,並控制其播放暫停。跨域
@ccclass
export default class NewClass extends cc.Component {
@property({
type: cc.AudioClip
})
bgAudio: cc.AudioClip;
audioid;
playState: boolean = true;
action;
onEnable() {
cc.game.addPersistRootNode(this.node);
this.autoAudioPlay();
}
autoAudioPlay = () => {
if(typeof this.audioid ==="undefined"){
this.audioid = cc.audioEngine.play(this.bgAudio, true, 1)
}
this.action = cc.repeatForever(cc.rotateBy(3, 360));
this.node.runAction(this.action);
}
playSwitch = () => {
console.log(this.playState)
if (this.playState) {
this.playState = false;
// 中止一個動做
this.node.stopAction(this.action);
cc.audioEngine.pause(this.audioid)
} else {
this.playState = true;
// 執行動做
this.node.runAction(this.action);
cc.audioEngine.resume(this.audioid);
}
}
onDestroy() {
}
}
複製代碼