CocosCreator 游戏小地图/地图雷达

更多笔记和源码请关注:【微信公众号】 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笔记

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章