cocos creator 不规则区域生成一个随机点

1.检测点是否在区域内

this.node.on(cc.Node.EventType.TOUCH_START, (touch, event) => {

var touchLoc = touch.getLocation();

// console.log("触摸点坐标touchLoc:", touchLoc);

if(cc.Intersection.pointInPolygon(touchLoc, collider.world.points)) {

// console.log("点击了一下");

var randomPos = this.getRandomPos(touchLoc, collider);

}

}, this);     //结尾的this  或者设为this.node要慎用,大多数情况都是this

 

2.获取随机点 这里用的while循环

getRandomPos: function(point, collider) {

var aabb = collider.world.aabb;

var width = aabb.width;

var height = aabb.height;

while (true) {

//获取随机点, width和height可以看情况自己设置还是直接用aabb里的属性,尽量缩小区域

var posInRect = this.getRandomPosInRect(point, width, height);  

//判断新生成的随机点posInrect是否在区域内

if(cc.Intersection.pointInPolygon(posInRect, collider.world.points)) {

return posInRect;

}

}

},

getRandomPosInRect: function(point, width, height) {

var minX = point.x - (width / 2);

var maxX = point.x + (width / 2);

var x = Math.random() * (maxX - minX + 1) + minX;

 

var minY = point.y - (height / 2);

var maxY = point.y + (height / 2);

var y = Math.random() * (maxY - minY + 1) + minY;

return new cc.Vec2(x, y);

},

 

//后续优化 将图形的边缘也显示在区域内 这种写法可能边缘会超出区域外

你可能感兴趣的:(随笔)