如题,我现在用画笔随便一画,怎么判断这个画的东西和一个小球的碰撞,或者不规则物体的碰撞检测问题?
不规则物体碰撞实际就是多边形碰撞,当然是可以的检测,只是你随手画的一个东西,如果想参与碰撞检测,你必须把你随手画出的东西转化为一堆顶点,然后用box2d生成一个多边形刚体,才能和小球碰撞
我写了一段代码,基本实现了,但是有点问题:
const { ccclass, property } = cc._decorator;
const NAME = 'drawNode'
@ccclass
export default class extends cc.Component{
// use this for initialization
onLoad () {
if (cc.director.setClearColor) {
cc.director.setClearColor( cc.Color.WHITE );
}
cc.director.setDisplayStats(false)
this.initEvent()
}
initEvent () {
const { width, height } = cc.director.getWinSize()
const pList = []
this.node.parent.on(cc.Node.EventType.TOUCH_START, (event) => {
this.drawNode = new cc.Node(NAME)
this.graphics = this.drawNode.addComponent(cc.Graphics)
this.graphics.lineWidth = 10;
const { x, y } = this.getPoint(event.touch.getLocation())
pList.push({x, y})
this.graphics.strokeColor = cc.hexToColor('#ff0000');
this.graphics.lineCap = cc.Graphics.LineCap.ROUND;
this.node.addChild(this.drawNode)
this.graphics.moveTo(x, y)
})
this.node.parent.on(cc.Node.EventType.TOUCH_MOVE, (event) => {
const { x, y } = this.getPoint(event.touch.getLocation())
this.graphics.lineTo(x, y)
this.graphics.stroke()
pList.push({x, y})
})
this.node.parent.on(cc.Node.EventType.TOUCH_END, (event) => {
this.graphics.close()
const rigidBody = this.drawNode.addComponent(cc.RigidBody)
rigidBody.density = 5
rigidBody.allowSleep = false
rigidBody.gravityScale = 3
const collider = this.drawNode.addComponent(cc.PhysicsPolygonCollider)
collider.points = pList.map(({x, y}) => cc.p(x, y))
collider.apply()
})
}
getPoint ({ x, y }) {
const { width, height } = cc.director.getWinSize()
return { x: x - width/2, y: y - height/2 }
}
draw () {
}
}
apply方法经常报错,原因是随手画的点里面经常会有重合的地发,导致报错:
Uncaught TypeError: Cannot read property 'x' of undefined
at Area (CCPolygonSeparator.js:312)
at Right (CCPolygonSeparator.js:194)
at Reflex (CCPolygonSeparator.js:182)
at ConvexPartition (CCPolygonSeparator.js:52)
at Object.ConvexPartition (CCPolygonSeparator.js:129)
at cc_PhysicsPolygonCollider._createShape (CCPhysicsPolygonCollider.js:55)
at cc_PhysicsPolygonCollider.__init (CCPhysicsCollider.js:169)
at CCClass.pushDelayEvent (CCPhysicsManager.js:172)
at cc_PhysicsPolygonCollider._init (CCPhysicsCollider.js:151)
at cc_PhysicsPolygonCollider.start (CCPhysicsCollider.js:143)
不知道如何处理这个问题?
例子我都看过了,能看看我代码的问题吗?
看看我的代码那个错误如何解决,谢谢!
你的这个问题解决没,我也遇到这个问题了