cocos creator touch事件移动中防止碰撞穿透

最近在学习cocos creator, 在实现一个手指移动物体与其他物体碰撞的场景时,缓慢移动不会出现问题,当快速移动时,碰撞检测不会生效, 使用刚体的bullet也解决不了(这个感觉好像是物品自移动场景下使用的,没进行验证),尝试在touchMove中对快速移动产生的长距离进行分步检测, 未出现碰撞穿透的现象,代码实现如下:


    touchMove(event: cc.Event.EventTouch) {    
        if(this.isTouchStart) {
            let delta = event.getDelta();            
            let mag = Math.round(delta.mag());//防止碰撞穿透,分步检测碰撞
            if(mag > 5) {
                mag = mag/5 //防止过长,以5为最大步长
            }

            let stepx = delta.x/mag;
            let stepy = delta.y/mag;

            for (let index = 0; index < mag; index++) {
       
                //检测边界
                let tmpX = this.node.x + stepx
                let tmpY = this.node.y + stepy;
                let halfNodeSize = this.node.width/2;
                let maxX = this.node.parent.width - halfNodeSize;
                let maxY = this.node.parent.height - halfNodeSize;
                if(tmpX >= halfNodeSize && tmpX <= maxX) {
                    this.node.x = tmpX;
                }else if(tmpX < halfNodeSize) {
                    this.node.x = halfNodeSize;
                }else if(tmpX > maxX) {
                    this.node.x = maxX;
                }
                if(tmpY >= halfNodeSize && tmpY <= maxY) {
                    this.node.y = tmpY;
                }else if(tmpY < halfNodeSize) {
                    this.node.y = halfNodeSize;
                }else if(tmpY > maxY) {
                    this.node.y = maxY;
                }
                        
                this.cmupdate();//检测碰撞
            }
        }
    }
    
    cmupdate() {
        let cm:any = cc.director.getCollisionManager();        
        cm.update();
    }

你可能感兴趣的:(cocos,creator)