核心代碼:
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;}