更多筆記和源碼請關注:【微信公衆號】 CocosCreator筆記
演示
ps:請注意左上角
技術摘要
大地圖與小地圖座標轉換
更新小地圖中元素及視口位置
拖動小地圖中視口位置/更新Main Camera位置
實現
01
小地圖(圖片)的寬高比例必須和大地圖相等
這樣就可以將大地圖上的元素照搬到小地圖上了
大地圖:
小地圖:
場景中小地圖裏的元素如下:
mini_map:小地圖
player:玩家
monster:怪物
rect:當前視口
rect添加Graphics組件,畫出當前視口矩形
02
座標轉換:
mapToMini(point: cc.Vec2) {
let x = point.x / this.tileMap.node.width * this.miniMap.width;
let y = point.y / this.tileMap.node.height * this.miniMap.height;
return cc.v2(x, y);
}
miniToMap(point: cc.Vec2) {
let x = point.x / this.miniMap.width * this.tileMap.node.width;
let y = point.y / this.miniMap.height * this.tileMap.node.height;
return cc.v2(x, y);
}
小地圖註冊觸摸事件:
this.miniMap.on("touchstart", this.onTouchStart, this);
this.miniMap.on("touchmove", this.onTouchMove, this);
this.miniMap.on("touchend", this.onTouchEnd, this);
this.miniMap.on("touchcancel", this.onTouchEnd, this);
on/off記得要成對出現:
onDestroy() {
this.miniMap.off("touchstart", this.onTouchStart, this);
this.miniMap.off("touchmove", this.onTouchMove, this);
this.miniMap.off("touchend", this.onTouchEnd, this);
this.miniMap.off("touchcancel", this.onTouchEnd, this);
}
在觸摸開始和滑動的時候更新Main Camera和小地圖視口的位置
觸摸結束的時候回到玩家當前視角
touchMiniMap(event: cc.Event.EventTouch) {
let touchLocation = this.miniMap.convertToNodeSpaceAR(event.getLocation());
let position = this.miniToMap(touchLocation);
this.updateCameraPosition(position);
}
onTouchStart(event: cc.Event.EventTouch) {
this.touchMiniMap(event);
}
onTouchMove(event: cc.Event.EventTouch) {
this.touchMiniMap(event);
}
onTouchEnd(event: cc.Event.EventTouch) {
this.updateCameraPosition(this.nodePlayer.position);
}
更新Main Camera位置並限制其邊界
updateCameraPosition(target: cc.Vec2){
if (target.x > this._cameraMaxX) {
target.x = this._cameraMaxX;
}
if (target.x < -this._cameraMaxX) {
target.x = -this._cameraMaxX;
}
if (target.y > this._cameraMaxY) {
target.y = this._cameraMaxY;
}
if (target.y < -this._cameraMaxY) {
target.y = -this._cameraMaxY;
}
this.mainCamera.node.position = target;
this.updateMiniRect();
}
更新小地圖視口位置
updateMiniRect() {
let pointCamera = this.mainCamera.node.position.sub(cc.v2(cc.winSize.width / 2, cc.winSize.height / 2));
pointCamera = this.mapToMini(pointCamera);
this.miniRect.clear();
this.miniRect.rect(pointCamera.x, pointCamera.y, this._miniScreenWidth, this._miniScreenHeight);
this.miniRect.stroke();
}
—END—
聲明:發佈此文是出於傳遞更多知識以供交流學習之目的。若有來源標註錯誤或侵犯了您的合法權益,請作者持權屬證明與我聯繫,我將及時更正、刪除,謝謝。
作者:請容我安眠
更多筆記和源碼請關注:【微信公衆號】 CocosCreator筆記