文档章节

ccc切割刚体

o
 osc_y8yehimr
发布于 2019/03/20 11:33
字数 806
阅读 10
收藏 0

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

// http://www.emanueleferonato.com/2011/08/05/slicing-splitting-and-cutting-objects-with-box2d-part-4-using-real-graphics/

const EPSILON = 0.1;
const POINT_SQR_EPSILON = 5;

function compare(a, b) {
    if (a.fraction > b.fraction) {
        return 1;
    } else if (a.fraction < b.fraction) {
        return -1;

    }
    return 0;
}

function equals (a, b, epsilon) {
    epsilon = epsilon === undefined ? EPSILON : epsilon;
    return Math.abs(a-b) < epsilon;
}

function equalsVec2(a,b, epsilon) {
    return equals(a.x, b.x, epsilon) && equals(a.y, b.y, epsilon);
}

function pointInLine (point, a, b) {
    return cc.Intersection.pointLineDistance(point, a, b, true) < 1;
}

cc.Class({
    extends: cc.Component,

    onEnable: function () {
        this.debugDrawFlags = cc.director.getPhysicsManager().debugDrawFlags;
        cc.director.getPhysicsManager().debugDrawFlags = 
            cc.PhysicsManager.DrawBits.e_jointBit |
            cc.PhysicsManager.DrawBits.e_shapeBit
            ;
    },

    onDisable: function () {
        cc.director.getPhysicsManager().debugDrawFlags = this.debugDrawFlags;
    },

    // use this for initialization
    onLoad: function () {
        var canvas = cc.find('Canvas');
        canvas.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        canvas.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        canvas.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);

        this.ctx = this.getComponent(cc.Graphics);
    },

    onTouchStart: function (event) {
        this.touching = true;
        this.r1 = this.r2 = this.results = null;
        this.touchStartPoint = this.touchPoint = cc.v2( event.touch.getLocation() );
    },

    onTouchMove: function (event) {
        this.touchPoint = cc.v2( event.touch.getLocation() );
    },

    onTouchEnd: function (event) {
        this.touchPoint = cc.v2( event.touch.getLocation() );
        this.recalcResults();
        this.touching = false;

        let point = cc.v2( event.touch.getLocation() );
        if ( equals(this.touchStartPoint.sub(point).magSqr(), 0) ) return;

        // recalculate fraction, make fraction from one direction
        this.r2.forEach(r => {
            r.fraction = 1 - r.fraction;
        });

        let results = this.results;

        let pairs = [];
        
        for (let i = 0; i < results.length; i++) {
            let find = false;
            let result = results[i];

            for (let j = 0; j < pairs.length; j++) {
                let pair = pairs[j];
                if (pair[0] && result.collider === pair[0].collider) {
                    find = true;

                    // one collider may contains several fixtures, so raycast may through the inner fixture side
                    // we need remove them from the result
                    let r = pair.find((r) => {
                        return r.point.sub(result.point).magSqr() <= POINT_SQR_EPSILON;
                    });

                    if (r) {
                        pair.splice(pair.indexOf(r), 1);
                    }
                    else { 
                        pair.push(result);
                    }

                    break;
                }
            }

            if (!find) {
                pairs.push([result]);
            }
        }

        for (let i = 0; i < pairs.length; i++) {
            let pair = pairs[i];
            if (pair.length < 2) {
                continue;
            }

            // sort pair with fraction
            pair = pair.sort(compare);

            let splitResults = [];

            // first calculate all results, not split collider right now
            for (let j = 0; j < (pair.length - 1); j +=2) {
                let r1 = pair[j];
                let r2 = pair[j+1];

                if (r1 && r2) {
                    this.split(r1.collider, r1.point, r2.point, splitResults);
                }
            }

            if (splitResults.length <= 0) {
                continue;
            }

            let collider = pair[0].collider;

            let maxPointsResult;
            for (let j = 0; j < splitResults.length; j++) {
                let splitResult = splitResults[j];

                for (let k = 0; k < splitResult.length; k++) {
                    if (typeof splitResult[k] === 'number') {
                        splitResult[k] = collider.points[splitResult[k]];
                    }
                }

                if (!maxPointsResult || splitResult.length > maxPointsResult.length) {
                    maxPointsResult = splitResult;
                }
            }

            if (maxPointsResult.length < 3) {
                continue;
            }

            // keep max length points to origin collider
            collider.points = maxPointsResult;
            collider.apply();

            let body = collider.body;

            for (let j = 0; j < splitResults.length; j++) {
                let splitResult = splitResults[j];

                if (splitResult.length < 3) continue;
                if (splitResult == maxPointsResult) continue;

                // create new body
                let node = new cc.Node();
                node.position = body.getWorldPosition();
                node.rotation = body.getWorldRotation();
                node.parent = cc.director.getScene();
                
                node.addComponent(cc.RigidBody);
                
                let newCollider = node.addComponent(cc.PhysicsPolygonCollider);
                newCollider.points = splitResult;
                newCollider.apply();
            }
            
        }
    },

    split: function (collider, p1, p2, splitResults) {
        let body = collider.body;
        let points = collider.points;


        // The manager.rayCast() method returns points in world coordinates, so use the body.getLocalPoint() to convert them to local coordinates.
        p1 = body.getLocalPoint(p1);
        p2 = body.getLocalPoint(p2);


        let newSplitResult1 = [p1, p2];
        let newSplitResult2 = [p2, p1];

        let index1, index2;
        for (let i = 0; i < points.length; i++) {
            let pp1 = points[i];
            let pp2 = i === points.length - 1 ? points[0] : points[i+1];
          
            if (index1 === undefined && pointInLine(p1, pp1, pp2)) {
                index1 = i;
            }
            else if (index2 === undefined && pointInLine(p2, pp1, pp2)) {
                index2 = i;
            }

            if (index1 !== undefined && index2 !== undefined) {
                break;
            }
        }

        // console.log(index1 + ' : ' + index2);

        if (index1 === undefined || index2 === undefined) {
            debugger
            return;
        }

        let splitResult, indiceIndex1 = index1, indiceIndex2 = index2;
        if (splitResults.length > 0) {
            for (let i = 0; i < splitResults.length; i++) {
                let indices = splitResults[i];
                indiceIndex1 = indices.indexOf(index1);
                indiceIndex2 = indices.indexOf(index2);

                if (indiceIndex1 !== -1 && indiceIndex2 !== -1) {
                    splitResult = splitResults.splice(i, 1)[0];
                    break;
                }
            }
        }

        if (!splitResult) {
            splitResult = points.map((p, i) => {
                return i;
            });
        }

        for (let i = indiceIndex1 + 1; i !== (indiceIndex2+1); i++) {
            if (i >= splitResult.length) {
                i = 0;
            }

            let p = splitResult[i];
            p = typeof p === 'number' ? points[p] : p;
            
            if (p.sub(p1).magSqr() < POINT_SQR_EPSILON || p.sub(p2).magSqr() < POINT_SQR_EPSILON) {
                continue;
            }

            newSplitResult2.push(splitResult[i]);
        }

        for (let i = indiceIndex2 + 1; i !== indiceIndex1+1; i++) {
            if (i >= splitResult.length) {
                i = 0;
            }

            let p = splitResult[i];
            p = typeof p === 'number' ? points[p] : p;
            
            if (p.sub(p1).magSqr() < POINT_SQR_EPSILON || p.sub(p2).magSqr() < POINT_SQR_EPSILON) {
                continue;
            }

            newSplitResult1.push(splitResult[i]);
        }

        splitResults.push(newSplitResult1);
        splitResults.push(newSplitResult2);
    },

    recalcResults: function () {
        if (!this.touching) return;

        let startPoint = this.touchStartPoint;
        let point = this.touchPoint;

        this.ctx.clear();
        this.ctx.moveTo(this.touchStartPoint.x, this.touchStartPoint.y);
        this.ctx.lineTo(point.x, point.y);
        this.ctx.stroke();

        let manager = cc.director.getPhysicsManager();

        // manager.rayCast() method calls this function only when it sees that a given line gets into the body - it doesnt see when the line gets out of it.
        // I must have 2 intersection points with a body so that it can be sliced, thats why I use manager.rayCast() again, but this time from B to A - that way the point, at which BA enters the body is the point at which AB leaves it!
        let r1 = manager.rayCast(this.touchStartPoint, point, cc.RayCastType.All);
        let r2 = manager.rayCast(point, this.touchStartPoint, cc.RayCastType.All);

        let results = r1.concat(r2);

        for (let i = 0; i < results.length; i++) {
            let p = results[i].point;
            this.ctx.circle(p.x, p.y, 5);
        }  
        this.ctx.fill();

        this.r1 = r1;
        this.r2 = r2;
        this.results = results;
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        // body maybe moving, need calc raycast results in update
        this.recalcResults();
    },
});

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
CocosCreator之KUOKUO带你做物理切割(第一部分)

摘要 有趣的物理小游戏总能让小伙伴们爱不释手,而 CocosCreator 的内置物理引擎让其开发变得更加简单。今天 KUOKUO 就为大家带来物理切割,从零开始做出切割单个物体! 正文 使用版本 Coco...

白玉无冰
05/07
0
0
CocosCreator之KUOKUO带你做物理切割(第一部分)

摘要 有趣的物理小游戏总能让小伙伴们爱不释手,而 CocosCreator 的内置物理引擎让其开发变得更加简单。今天 KUOKUO 就为大家带来物理切割,从零开始做出切割单个物体! 正文 使用版本 Coco...

一枚小工
03/30
0
0
为何你的弹球如丝般顺滑?不停歇的球!技术分享!源码相送!

三行代码搞定!在 2.0.9 之前版本使用 tween!cocos creator ! 附源代码! https://github.com/caochao/cocoscreatorproj_base 抖音、头条一个都不放过,字节小游戏上线攻略! 我就知道你“在...

白玉无冰
2019/12/18
0
0
姿态角

机器人、传感器都会用到姿态角的相关知识,近期实习也在接触了这些东西,同时自己对这些也非常感兴趣,故进行梳理一下。 前提 本文提到作如下定义: 旋转矩阵:这是用于坐标系转换变换的矩阵...

osc_jb8w6ufb
2018/08/03
2
0
仿射变换及其变换矩阵的理解

博客:blog.shinelee.me | 博客园 | CSDN [toc] 写在前面 2D图像常见的坐标变换如下图所示:这篇文章不包含透视变换(projective/perspective transformation),而将重点放在仿射变换(aff...

osc_urm28qtx
2019/05/30
6
0

没有更多内容

加载失败,请刷新页面

加载更多

VB语言基础重要知识点12

我们课程,我们做一些针对于考试的简要讲解。 一、有关考试的几个问题 首先,提问:考试最重要的是什么? 答案其实很简单:得分!!!!! 想要得分,就要做到基本的保存。 保存哪些文件呢?...

刘金玉编程
2019/10/30
0
0
全网最全JAVA、Python电子书!限时领取,过时不候!

给大家整理了最全的入门+进阶书籍!!! 免费领取,无套路! 加微信发送“电子书” 秒通过,秒发资源! 本文分享自微信公众号 - Python进击者(JAVAandPythonJun)。 如有侵权,请联系 supp...

kuls
01/16
0
0
原创356--免费还是付费

最近得有一个星期,被一个录屏软件(record it)烦到了,本来免费版可以无限制录制,只能720p,GIF不支持,高清不支持,没有剪辑功能。 之前调研了好几种,用起来还是这个方便,就一直用了。...

八音弦
04/24
0
0
数字IC技术讨论群,设计和验证、前端和后端,总有你感兴趣的话题。快满了,需要的抓紧加入。

本文分享自微信公众号 - 白山头讲IC(gray_mount)。 如有侵权,请联系 support@oschina.cn 删除。 本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。...

白山头
04/29
0
0
how to install mongodb in centos7

[root@xtwj88 ~]# cat /etc/yum.repos.d/mongodb-org-4.2.repo [mongodb-org-4.2]name=MongoDB Repositorybaseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86......

qwfys
10分钟前
13
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部