I have a loop to see if a given shape collides with any other in a KineticJS program. Below is pseudocode for the situation
function hasCollision(shape, index) {
var children = layer.children;
for(var i = 0, l = children.length; i < l; i++) {
if(i === index) continue; // Only check other shapes
if(collision(shape, children[i]))
return true;
}
return false;
}
What I don't like about this approach is that I have to save the index for each shape somewhere in my code. Additionally, the code will break if I remove elements from the array.
I read the documentation and couldn't find anything about comparing shapes etc., but I might have overlooked something. Does KineticJS already have a way to uniquely identify/compare instance of shapes? If not, is it OK to append custom data to a Node? Will it still work with serialization? Is doing this likely to break things with current or future versions of KineticJS?
EDIT: To be clear, this is the solution I'm considering
shape.uid = uid_factory++;
...
function hasCollision(shape) {
var children = layer.children;
for(var i = 0, l = children.length; i < l; i++) {
var other = children[i];
if(other.uid === shape.uid) continue; // Only check other shapes
if(collision(shape, other))
return true;
}
return false;
}
Yes.
You can assign a unique id to any Kinetic Node (shape, text, etc):
var shape123 = new Kinetic.Circle({
id:(nextShapeId),
...
And you can get any node's id like this:
anyNode.getId();
And you can ask the stage to get you a reference to that node like this:
// use stage.find to fetch all nodes with an id == theId
var nodes = stage.find("#"+theId);
// nodes is a collection, so grab the first element
var myNode = nodes[0];