在《Cocos 2.x-Hello World 飛機大戰游戲》,簡單實現了一個Cocos 2.x Hello World 程序,但是在不同的機型的運行效果,會出現黑邊的情況,在查看Cocos Creator的手冊之后,發現了一個簡單的解決方案,這里記錄一下處理過程。
1. 環境搭建
為了不對原來的代碼進行大的調整,這里單獨創建了一個新的游戲場景進行測試,相關場景資源如下:

2. 多分辨率適配方案
在多分辨率適配方案中,官方文檔提供了方案說明:
https://docs.cocos.com/creator/2.4/manual/zh/ui/multi-resolution.html
總結一下主要有兩點吧:
- 設計分辨率寬高比大于屏幕分辨率,適配高度避免黑邊
- 設計分辨率寬高比小于屏幕分辨率,適配寬度避免黑邊
這里的設計分辨率就是Canvas中的Design Resolution獲取得到,至于屏幕分辨率,目前還不是很熟悉API,暫時使用cc.winSize獲取。
在上圖的游戲腳本中,新增了一個GameSettingCC用于動態調整上訴的兩種方案:
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameSettingCC extends cc.Component {
onLoad() {
const canvas = this.node.getComponent(cc.Canvas);
const dr = canvas.designResolution.width / canvas.designResolution.height;
const wr = cc.winSize.width / cc.winSize.height;
if (dr > wr) {
canvas.fitHeight = true;
canvas.fitWidth = false;
} else {
canvas.fitHeight = false;
canvas.fitWidth = true;
}
cc.log("dr=" + dr, "wr=" + wr);
cc.log("fitHeigh=" + canvas.fitHeight, "fitWidth=" + canvas.fitWidth);
}
}
這個腳本掛在Canvas上,這樣可以初步解決不同機型(分辨率不同)顯示出現黑邊的問題。
3. 對齊策略
通過簡單地通過調整fitHeight或fitWidth可以適配不同分辨率的問題,但是無法解決UI元素在Canvas中的相對位置,在官方文檔中發現對其策略,可以用來解決這個問題,官方文檔地址:
https://docs.cocos.com/creator/2.4/manual/zh/ui/widget-align.html
在飛機大戰游戲中,分數這個UI元素就需要通過這種策略,來適配不同的分辨率問題:
給score這個Label UI元素加上Widget組件,并調整其Top和Left為25px,

通過Widget配置邊距,就可以解決不同分別率下,score這個Label的位置錯亂問題。
4. 位置計算
在新的游戲場景中,將所有節點元素都作為Canvas的子節點,一些計算需要調整一下,主要是坐標中心變了。
const { ccclass, property } = cc._decorator;
@ccclass
export default class PlayerCC extends cc.Component {
minX: number;
maxX: number;
minY: number;
maxY: number;
moving: boolean = false;
onLoad() {
const size = cc.winSize;
cc.log(size.width, size.height);
this.maxX = size.width / 2;
this.minX = -this.maxX;
this.maxY = size.height / 2;
this.minY = -this.maxY;
}
start() {
this.initializeTouchEvent();
}
initializeTouchEvent() {
this.node.on(cc.Node.EventType.TOUCH_START, () => (this.moving = true));
this.node.on(cc.Node.EventType.TOUCH_END, () => (this.moving = false));
this.node.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Event.EventTouch) => {
if (this.moving) {
let x = e.getLocationX() - this.maxX;
let y = e.getLocationY() - this.maxY;
cc.log(e.getLocationX(), e.getLocationY());
x = Math.max(this.minX + this.node.width / 2, x);
x = Math.min(this.maxX - this.node.width / 2, x);
y = Math.max(this.minY + this.node.height / 2, y);
y = Math.min(this.maxY - this.node.height / 2, y);
this.node.setPosition(x, y);
}
});
}
}
這里可能還有更好的解決方案,但就目前對Cocos2.x的了解還不是很多,后續在慢慢閱讀文檔繼續完善。
浙公網安備 33010602011771號