Detecting Intersection of Objects?

842 views
Skip to first unread message

Ed Hebert

unread,
Nov 18, 2013, 10:19:52 AM11/18/13
to pap...@googlegroups.com
Hi-

I'm a student in a dynamic web apps class, and we're exploring various JS tools and techniques. I chose to attempt a project with Paper.js and begin exploring some of the organic motion techniques outlined in Dan Shiffman's "Nature of Code" book. My goal will eventually be to create a swimming fish or similar aquatic creature, and allow the user to feed the fish some food via mouse clicks. 

I'm at the point where I've roughed out some primitive shapes and have the general functionality of my program established. The rough draft of my project can be seen here 

My question is about how to detect an intersection/overlap of different paper.js objects (or certain points and/or segments within those objects). Ideally, I'd like my fish to detect and swim to its closest food particles, and have those particles be removed from the screen when the "mouth" of my fish intersects with the food object. While I've seen the "intersections" information on the Paper.js reference and examples, I'm not quite sure how to apply that functionality to a conditional statement...like "if fish mouth intersects food, remove food".

I should also note that I am using paper.js through JavaScript directly rather than using the paperscript approach. In this way I could conform to the requirements of the assignment.

I'm sorry if these questions are a bit elementary, but I suppose we all start somewhere. Thanks for any help or tips you can provide!


Ed

Ed Hebert

unread,
Nov 18, 2013, 2:25:11 PM11/18/13
to pap...@googlegroups.com
OK, after a little more tweaking, I think that hitResult is probably a better job for my needs that an intersection detection. That said, I'm still having issues getting the "hit" to detect. I'm obviously not understanding how to use hitTest properly. 

Here's my code snippet. I'm trying to detect when the "mouth" point hits my "food" object's path. My console.log() returns a valid mouth point value, but hitResult is always undefined, even when the mouth and food path clearly overlap/intersect:

    this.eat = function() {

        // if there's a food object, compare it against location of mouth point
        if (typeof food != "undefined")
            var hitResult = food.path.hitTest(mouth);
            
        console.log('mouth: ' + mouth +', ' + 'hitResult: ' + hitResult);

        // if fish mouth hits food, do stuff
        if (hitResult)
            console.log('Yum!');
    }

Any ideas?
Reply all
Reply to author
Forward
0 new messages