核心代码:
cc.Intersection.polygonPolygon(points2, points)
拖拽物品拖到多个目标位置判定,取最近的:
getTargetItem(collider2: cc.PolygonCollider, touchPos: cc.Vec2, targetRoot: cc.Node) {let length = 99999;let target = null;//collider2 拖拽物 需要添加cc.PolygonCollider作为判定范围//targetRoot子节点为拖拽目标节点,需要添加cc.PolygonCollider作为判定范围targetRoot.children.forEach(element => {let collider = element.getComponent(cc.PolygonCollider);let points = [];collider.points.forEach(point => {let ws = collider.node.convertToWorldSpaceAR(cc.v2(this.node.position));points.push(cc.v2(ws))//转换到世界坐标});let points2 = []collider2.points.forEach(point => {let ws = collider2.node.convertToWorldSpaceAR(cc.v2(this.node.position));points2.push(cc.v2(ws))//转换到世界坐标});let isIn = cc.Intersection.polygonPolygon(points2, points)if (isIn) {//拖拽到了目标物品内const pos = targetRoot.convertToNodeSpaceAR(cc.v2(touchPos));let dis = pos.sub(cc.v2(element.position)).mag();if (dis <= length) {//取出拖拽位置距离目标物体最近的target = elementlength = dis}}})return target;}