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

本文介绍了如何在Cocos Creator中,当用户点击不规则区域(使用polygoncollider)时,检测点击并生成一个位于该区域内随机位置的方法。通过onTouchEvent监听触摸开始事件,结合pointInPolygon函数判断点是否在区域内,并利用while循环不断生成随机点,直到找到位于区域内的点。最后讨论了如何优化,确保随机点不会超出区域边缘。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值