Cocoss2d-js Create the coloring effect by revealing the bottom layer - cocos2d-x

I have an Android app for kids that has a coloring screen, and I am trying to convert it to Cocos2d-js. The way I implemented this in Android is to have two pictures on top of each other: a colored one at the bottom, and a grayscale on top. When a touch is detected, the gray scale picture on top is erased on that location revealing the bottom picture.
I am looking at RenderTexture for coloring effect, and ClippingNode for revealing the bottom layer, but when I set the RenderTexture as the stencil for the ClippingNode, the top image is completely transparent (stencil is opaque?)
This is my code so far (top layer only, as the bottom layer is just a sprite that covers the entire screen):
var GrayScaleLayer = cc.Layer.extend({
winsize: null,
_brushs:null,
_target:null,
_lastLocation:null,
ctor:function () {
this._super();
this.init();
},
init:function () {
if ('touches' in cc.sys.capabilities){
cc.eventManager.addListener({
event: cc.EventListener.TOUCH_ALL_AT_ONCE,
onTouchesMoved:function (touches, event) {
event.getCurrentTarget().drawInLocation(touches[0].getLocation());
}
}, this);
} else if ('mouse' in cc.sys.capabilities)
cc.eventManager.addListener({
event: cc.EventListener.MOUSE,
onMouseDown: function(event){
event.getCurrentTarget()._lastLocation = event.getLocation();
},
onMouseMove: function(event){
if(event.getButton() == cc.EventMouse.BUTTON_LEFT)
event.getCurrentTarget().drawInLocation(event.getLocation());
}
}, this);
// Get the screen size of your game canvas
this.winsize = cc.director.getWinSize();
this._brushs = [];
this._lastLocation = cc.p(this.winsize.width, this.winsize.height);
// Create the RenderTexture object
var stencil = this.erase();
stencil.setPosition(cc.p(this.winsize.width/2, this.winsize.height/2));
// Create the clippingNode and add the RenderTexture as a stencil
var clipper = new cc.ClippingNode();
clipper.setPosition(cc.p(0,0));
clipper.stencil = stencil;
clipper.setInverted(true);
this.addChild(clipper);
// Create gray scale image and add it to the Clipping node
var grayItem = new cc.Sprite(res.image_gs_png);
var grayScale = this.winsize.width/grayItem.width;
grayItem.setScale(grayScale, grayScale);
grayItem.setPosition(cc.p(this.winsize.width/2, this.winsize.height/2));
clipper.addChild(grayItem);
},
erase:function () {
var target = new cc.RenderTexture(this.winsize.width, this.winsize.height);
this._target = target;
return target;
},
drawInLocation:function (location) {
var distance = cc.pDistance(location, this._lastLocation);
if (distance > 1) {
var locLastLocation = this._lastLocation;
this._target.begin();
this._brushs = [];
for(var i = 0; i < distance; ++i) {
var diffX = locLastLocation.x - location.x;
var diffY = locLastLocation.y - location.y;
var delta = i / distance;
var sprite = new cc.Sprite(res.brush_png);
sprite.attr({
x: location.x + diffX * delta,
y: location.y + diffY * delta,
rotation: Math.random() * 360,
color: cc.color(Math.random() * 255, 255, 255),
scale: Math.random() + 0.25,
opacity: 20
});
sprite.retain();
this._brushs.push(sprite);
}
for (var i = 0; i < distance; i++) {
this._brushs[i].visit();
}
this._target.end();
}
this._lastLocation = location;
},
onExit:function () {
for(var i in this._brushs){
this._brushs[i].release();
}
this._super();
}
});
I tried using the .clear(rgba) function on the RenderTexture to no avail.
I noticed that the ClippingNode example in the js-tests is adding a DrawNode object as a stencil, is there a way to "convert" the RenderTexture to a DrawNode?

You don't need to use clippingNode for this,
simply have the colored layer on bottom, and a greyscale rendertexture on top,
when touched, you erase the transparency by drawing a sprite onto the rendertexture with this blend func {src: gl_ZERO, dst: gl_ONE_MINUS_SRC_ALPHA}

Related

How can i add an svg image and a label to a custom shape dynamically mxgraph

`function Domain() {
mxCylinder.call(this);
}
/*
The next lines use an mxCylinder instance to augment the
prototype of the shape ("inheritance") and reset the
constructor to the topmost function of the c'tor chain.
*/
mxUtils.extend(Domain, mxCylinder);
Domain.prototype.redrawPath = function (
path: any,
x: any,
y: any,
w: any,
h: any
) {
var dy = this.extrude * this.scale;
var dx = this.extrude * this.scale;
path.moveTo(0, dy);
path.lineTo(dx, 0);
path.lineTo(w, 0);
path.lineTo(w, h - dy);
path.lineTo(w, h);
path.lineTo(0, h);
path.lineTo(0, dy);
path.lineTo(dx, 0);
path.close();
};
mxCellRenderer.registerShape("Domain", Domain);
export function main(container: any) {
if (!mxClient.isBrowserSupported()) {
mxUtils.error("Browser is not supported!", 200, false);
} else {
mxEvent.disableContextMenu(container);
var graph = new mxGraph(container);
graph.setCellsCloneable(true);
graph.setHtmlLabels(true);
graph.setPanning(true);
graph.setEnabled(false);
graph.centerZoom = false;
new mxRubberband(graph);
configureStylesheet(graph);
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try {
var v1 = graph.insertVertex(
parent,
null,
"RAN",
20,
20,
240,
120,
// 'image;image=icons/secure-gdpr-user-svgrepo-com.svg;selectable=0;connectable=0;editable=0;movable=0;fillColor=hsl(36deg 98% 51%)'
//here i'm regestering my shape how can i add an image and a label inside the shape "shape=Domain;startSize=30;fillColor=hsl(36deg 98% 51%);spacingLeft=10;align=left;fontColor=#FFFFFF;fontSize=18;shadow=0;strokeColor=none;whiteSpace=wrap;img;"
);
} finally {
// Updates the display
graph.getModel().endUpdate();
}
}
}
i Used configure style sheet to add the image to the shape but when i do this
// style[mxConstants.STYLE_SHAPE] = "Domain";
the image disappears and i get only the sape
export function configureStylesheet(graph: any) {
var style: any = new Object();
style = mxUtils.clone(style);
// style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
// style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL;
// style[mxConstants.STYLE_SHAPE] = "Domain";
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP;
style[mxConstants.STYLE_IMAGE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_IMAGE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP;
style[mxConstants.STYLE_IMAGE] = "icons/secure-gdpr-user-svgrepo-com.svg";
style[mxConstants.STYLE_IMAGE_WIDTH] = "48";
style[mxConstants.STYLE_IMAGE_HEIGHT] = "48";
style[mxConstants.STYLE_SPACING_TOP] = "80";
style[mxConstants.STYLE_SPACING] = "8";
graph.getStylesheet().putCellStyle("img", style);
Here's the approach i'm trying to do but the thing is that the image is overwriting the shape and not able to display the image in my customised shape. i need to have that custom shape taking the label and the image and dynamically for it to be implemented more than once`

canvas elements aren't shown

I draw 3 elements on my canvas and it works fine on my page (https://lodysreizen.nl/route2.html). But when I implement that page in a index page(https://lodysreizen.nl/ route2 button), where I load in into a div, only the outline that I draw in my html code are shown.
The other 2 lines and the dot don't show. What am I doing wrong?
I changed the order of the code(first script and then html and the other way around)
function draw() {
var canvas = document.getElementById('japan_canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "red";
<!--2 lijnen-->
ctx.beginPath();
ctx.moveTo(125, 125); <!--tekst-->
ctx.lineTo(125, 45);
ctx.lineTo(45, 125);
ctx.lineTo(63, 200);
ctx.lineTo(200, 210);
<!--ctx.closePath(); dit trekt een lijn vanaf het laatste punt naar het begin punt-->
ctx.lineWidth = 2; <!--dikte van de lijn-->
ctx.lineJoin = "round" <!--hoe de lijn er uitziek waar ze een knik maakt.-->
ctx.stroke();
<!--de circels-->
ctx.strokeStyle = "red"; <!--deze kleur werkt nog niet-->
ctx.beginPath();
ctx.arc(125, 45, 5, 0, 2 * Math.PI); <!--circel met centrumpunt 125,45)-->
ctx.fill(); <!--de circel vullen-->
<!--Path2D-->
}
}
canvas {
border: 1px solid black;
}
<body onload="draw();">
<canvas id="japan_canvas" width="300" height="300"></canvas></body>
function createPaint(parent) {
var canvas = elt('canvas', {});
var cx = canvas.getContext('2d');
var toolbar = elt('div', {class: 'toolbar'});
// calls the every function in controls, passing in context,
// then appending the returned results to the toolbar
for (var name in controls)
toolbar.appendChild(controls[name](cx));
var panel = elt('div', {class: 'picturepanel'}, canvas);
parent.appendChild(elt('div', null, panel, toolbar));
}
/************************************************************************
* helper functions
***********************************************************************/
// creates an element with a name and object (attributes)
// appends all further arguments it gets as child nodes
// string arguments create text nodes
// ex: elt('div', {class: 'foo'}, 'Hello, world!');
function elt(name, attributes) {
var node = document.createElement(name);
if (attributes) {
for (var attr in attributes)
if (attributes.hasOwnProperty(attr))
node.setAttribute(attr, attributes[attr]);
}
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
// if this argument is a string, create a text node
if (typeof child == 'string')
child = document.createTextNode(child);
node.appendChild(child);
}
return node;
}
// figures out canvas relative coordinates for accurate functionality
function relativePos(event, element) {
var rect = element.getBoundingClientRect();
return {x: Math.floor(event.clientX - rect.left),
y: Math.floor(event.clientY - rect.top)};
}
// registers and unregisters listeners for tools
function trackDrag(onMove, onEnd) {
function end(event) {
removeEventListener('mousemove', onMove);
removeEventListener('mouseup', end);
if (onEnd)
onEnd(event);
}
addEventListener('mousemove', onMove);
addEventListener('mouseup', end);
}
// loads an image from a URL and replaces the contents of the canvas
function loadImageURL(cx, url) {
var image = document.createElement('img');
image.addEventListener('load', function() {
var color = cx.fillStyle, size = cx.lineWidth;
cx.canvas.width = image.width;
cx.canvas.height = image.height;
cx.drawImage(image, 0, 0);
cx.fillStyle = color;
cx.strokeStyle = color;
cx.lineWidth = size;
});
image.src = url;
}
// used by tools.Spray
// randomly positions dots
function randomPointInRadius(radius) {
for (;;) {
var x = Math.random() * 2 - 1;
var y = Math.random() * 2 - 1;
// uses the Pythagorean theorem to test if a point is inside a circle
if (x * x + y * y <= 1)
return {x: x * radius, y: y * radius};
}
}
/************************************************************************
* controls
***********************************************************************/
// holds static methods to initialize the various controls;
// Object.create() is used to create a truly empty object
var controls = Object.create(null);
controls.tool = function(cx) {
var select = elt('select');
// populate the tools
for (var name in tools)
select.appendChild(elt('option', null, name));
// calls the particular method associated with the current tool
cx.canvas.addEventListener('mousedown', function(event) {
// is the left mouse button being pressed?
if (event.which == 1) {
// the event needs to be passed to the method to determine
// what the mouse is doing and where it is
tools[select.value](event, cx);
// don't select when user is clicking and dragging
event.preventDefault();
}
});
return elt('span', null, 'Tool: ', select);
};
// color module
controls.color = function(cx) {
var input = elt('input', {type: 'color'});
// on change, set the new color style for fill and stroke
input.addEventListener('change', function() {
cx.fillStyle = input.value;
cx.strokeStyle = input.value;
});
return elt('span', null, 'Color: ', input);
};
// save
controls.save = function(cx) {
// MUST open in a new window because of iframe security stuff
var link = elt('a', {href: 'currentTab'}, 'Save');
function update() {
try {
link.href = cx.canvas.toDataURL();
} catch(e) {
// some browsers choke on big data URLs
// also, if the server response doesn't include a header that tells the browser it
// can be used on other domains, the script won't be able to look at it;
// this is in order to prevent private information from leaking to a script;
// pixel data, data URL or otherwise, cannot be extracted from a "tainted canvas"
// and a SecurityError is thrown
if (e instanceof SecurityError)
link.href = 'javascript:alert(' +
JSON.stringify('Can\'t save: ' + e.toString()) + ')';
else
window.alert("Nope.");
throw e;
}
}
link.addEventListener('mouseover', update);
link.addEventListener('focus', update);
return link;
};
/************************************************************************
* tools
***********************************************************************/
// drawing tools
var tools = Object.create(null);
// line tool
// onEnd is for the erase function, which uses it to reset
// the globalCompositeOperation to source-over
tools.Line = function(event, cx, onEnd) {
cx.lineCap = 'round';
// mouse position relative to the canvas
var pos = relativePos(event, cx.canvas);
trackDrag(function(event) {
cx.beginPath();
// move to current mouse position
cx.moveTo(pos.x, pos.y);
// update mouse position
pos = relativePos(event, cx.canvas);
// line to updated mouse position
cx.lineTo(pos.x, pos.y);
// stroke the line
cx.stroke();
}, onEnd);
};
// erase tool
tools.Erase = function(event, cx) {
// globalCompositeOperation determines how drawing operations
// on a canvas affect what's already there
// 'destination-out' makes pixels transparent, 'erasing' them
// NOTE: this has been deprecated
cx.globalCompositeOperation = 'destination-out';
tools.Line(event, cx, function() {
cx.globalCompositeOperation = 'source-over';
});
};
// initialize the app
var appDiv = document.querySelector('#paint-app');
createPaint(appDiv);
canvas {
border: 1px solid black;
}
<div id="paint-app"></div>

Modifying Paperjs canvas example Moving Multiple Items

On the Paperjs site, there is an example of Moving Multiple Items on this page http://paperjs.org/tutorials/animation/creating-animations/ The moving items are floating circles going left to right continuously. I am trying to modify this example to get the circles floating from the bottom to the top continuously. So far, I have managed to get them to float from the bottom to the top but for some reason, it is not continuous.
The other modification that I am trying to do with the example is to get the circles to have random colors based on a given array of colors. So far, the random color is only generated each time the page is refreshed and loaded.
How can I get the circles to float from bottom to top CONTINUOUSLY?
How can I get the circles to be randomly colored in the animation and not just on page load?
Here is my MODIFIED code:
// The amount of circles we want to make:
var count = 50;
/*random colors for circles*/
var circleColors = new Array();
circleColors[0] = "#2ab4e4";//BLUE
circleColors[1] = "#a2a7a6";//GREY
circleColors[2] = "#ef7047";//ORANGE
circleColors[3] = "#ffffff";//WHITE
/*end random colors for circles*/
// Create a symbol, which we will use to place instances of later:
var path = new Path.Circle({
center: [0, 0],
radius: 35,
fillColor: circleColors[Math.floor(Math.random() * circleColors.length)]
});
var symbol = new Symbol(path);
// Place the instances of the symbol:
for (var i = 0; i < count; i++) {
// The center position is a random point in the view:
var center = Point.random() * view.size;
var placedSymbol = symbol.place(center);
placedSymbol.scale(i / count);
}
// The onFrame function is called up to 60 times a second:
function onFrame(event) {
// Run through the active layer's children list and change
// the position of the placed symbols:
for (var i = 0; i < count; i++) {
var item = project.activeLayer.children[i];
// Move the item 1/20th of its width to the right. This way
// larger circles move faster than smaller circles:
item.position.y -= item.bounds.height / 20;
// If the item has left the view on the right, move it back
// to the left:
if (item.bounds.bottom > view.size.height) {
item.position.y = -item.bounds.height;
}
}
}
Here is the ORIGINAL code from Paperjs:
// The amount of circles we want to make:
var count = 150;
// Create a symbol, which we will use to place instances of later:
var path = new Path.Circle({
center: [0, 0],
radius: 10,
fillColor: 'white',
strokeColor: 'black'
});
var symbol = new Symbol(path);
// Place the instances of the symbol:
for (var i = 0; i < count; i++) {
// The center position is a random point in the view:
var center = Point.random() * view.size;
var placedSymbol = symbol.place(center);
placedSymbol.scale(i / count);
}
// The onFrame function is called up to 60 times a second:
function onFrame(event) {
// Run through the active layer's children list and change
// the position of the placed symbols:
for (var i = 0; i < count; i++) {
var item = project.activeLayer.children[i];
// Move the item 1/20th of its width to the right. This way
// larger circles move faster than smaller circles:
item.position.x += item.bounds.width / 20;
// If the item has left the view on the right, move it back
// to the left:
if (item.bounds.left > view.size.width) {
item.position.x = -item.bounds.width;
}
}
}
The origin of the paper.js coordinate system is at the top left corner of the canvas. To put an item below the viewport's bounds, you need to add the view's height to that of the item.
if (item.bounds.bottom < 0) {
item.position.y = view.size.height+item.bounds.height;
}
As for random colors, you'll have to use pathItems, not placedSymbols to vary the color style across objects. Instead of this:
var path = new Path.Circle({
center: [0, 0],
radius: 35,
fillColor: circleColors[Math.floor(Math.random() * circleColors.length)]
});
var symbol = new Symbol(path);
// Place the instances of the symbol:
for (var i = 0; i < count; i++) {
// The center position is a random point in the view:
var center = Point.random() * view.size;
var placedSymbol = symbol.place(center);
placedSymbol.scale(i / count);
}
You'll need something more like:
// Place the instances of the symbol:
for (var i = 0; i < count; i++) {
var path = new Path.Circle({
center: Point.random() * view.size,
radius: i / count,
fillColor: circleColors[Math.floor(Math.random() * circleColors.length)]
});
See this post for details:
Does all Paths in a Swarm need to have the same fillColor?

Chromakey'd HTML webcam wont save with transparancy

I have set up a green screen with a webcam, HTML5 video and canvas. I took an idea from MDN on creating a chroma key (green screen). But with a live webcam instead of a prerecorded video. Everything works as expected except when I go to save the image, the chroma key area is white instead of transparent. There is a background of the ocean. When the webcam is on and a person is standing in front of it, it looks like the person is in the ocean. Again, saving that image just gives me a white box with myself in the middle of it. The webcam dimensions are 640 x 480 and the canvas dimensions are 1600 x 800.
Edit: I changed the chroma key tolerance to be anything dark greyish and above. Now if you put something white in front of your camera, it should, in theory, show the entire background image. But its left with a 640x480 box the same color as the <body>.
Here is a demo Doesn't really work unless you have some green in the background. Webkit only.
Webcam chroma key:
var processor = {
timerCallback: function() {
if (this.webcam.paused || this.webcam.ended) {
return;
}
this.computeFrame();
var self = this;
setTimeout(function () {
self.timerCallback();
}, 0);
},
doLoad: function() {
this.webcam = document.getElementById("webcam");
this.c1 = document.getElementById("c1");
this.ctx1 = this.c1.getContext("2d");
this.c2 = document.getElementById("c2");
this.ctx2 = this.c2.getContext("2d");
var self = this;
this.webcam.addEventListener("play", function() {
self.width = 640;
self.height = 480;
self.timerCallback();
}, false);
},
computeFrame: function() {
this.ctx1.drawImage(this.webcam, 0, 0, 640, 480); //draw webcam to canvas
var frame = this.ctx1.getImageData(0, 0, 640, 480); //capture a frame
var l = frame.data.length / 4;
for (var i = 0; i < l; i++) { //loop through pixels
var r = frame.data[i * 4 + 0];
var g = frame.data[i * 4 + 1];
var b = frame.data[i * 4 + 2];
if (g > 100 && r < 95 && b > 60 && b < 160 ){
frame.data[i * 4 + 3] = 0;
}
}
this.ctx2.putImageData(frame, 480, 300); //place chroma video over bg img
return;
}
};
script.js
processor.doLoad();
//more stuff runs
takePicture();
function takepicture() {
var canv = document.getElementById('c2');
var photo = document.querySelector('#inptPhoto');
var data = canv.toDataURL('image/png');
photo.setAttribute('src', data);
}
I came across another SO post that suggested my image might not in fact be transparent, but white in the background, which is consistent with my results. Is there another way to do this?

HTML5 / kineticJS getIntersection function implementation

I am learning kineticjs through tutorials provided at http://www.html5canvastutorials.com, things are good and easy to understand but, I am having issue in understanding the getIntersection function that i want to use among different objects while dragging to detect collision / overlapping objects.
As far as I have understood the example the getIntersection function expects a position and checks if its intersecting with any other object or not..
Though I got them but with some issues.
I am unable to accomplish this..
Below is the code that I have tried up to now..
<script>
var stage = new Kinetic.Stage({
container: 'container',
width: 1000,
height: 500,
opacity: 0.5
});
var layer = new Kinetic.Layer();
var previous_position;
var new_position;
var collision = false;
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
var yellowBox = null;
for(var n = 0; n < 6; n++) {
// anonymous function to induce scope
(function() {
var i = n;
if(n < 3){
y = 50;
x = i * 100 + i * 10;
}else{
y = 150;
x = (i - 3) * 100 + (i - 3) * 10 ;
if(n == 3){
x = 0;
}
}
var box = new Kinetic.Rect({
x: x,
y: y,
width: 100,
height: 50,
fill: colors[i],
stroke: 'black',
strokeWidth: 4,
draggable: true,
name: colors[i]
});
box.on('dragstart', function() {
previous_position = {
x: this.attrs.x,
y: this.attrs.y
};
});
box.on('dragend', function() {
if(collision){
//this.setPosition(previous_position);
layer.draw();
collision = false;
}else{
//this.setPosition(new_position);
layer.draw();
}
});
box.on("dragmove", function(evt) {
console.log(layer.children.length);
if(layer.children.length > 1){
console.log('dragging');
new_position = {x: this.attrs.x,
y: this.attrs.y};
// var posBL = {x: this.attrs.x,
// y: this.attrs.height + this.attrs.y};
// var posTR = {x: this.attrs.x + this.attrs.width,
// y: this.attrs.y};
var posBR = {x: this.attrs.x + this.attrs.width,
y: this.attrs.y + this.attrs.height };
var collisionTL = this.getStage().getIntersections(new_position);
// var collisionBL = this.getStage().getIntersections(posBL);
// var collisionTR = this.getStage().getIntersections(posTR);
// var collisionBR = this.getStage().getIntersections(posBR);
console.log(collisionTL);
console.log(collisionTL.shapes);
// if(collisionTL.length > 1 || collisionBL.length > 0 || collisionTR.length > 0 || collisionBR.length > 0){
if(collisionTL.length > 1){
console.log(collisionTL.shapes);
collision = true;
}else{ //if(collisionBR.length > 0){
collision = true;
}
// for(i=0; i < collision.length; i++){
// // console.log(collision[i]._id);
// }
}
});
if(colors[i] === 'yellow') {
yellowBox = box;
}
layer.add(box);
})();
}
stage.add(layer);
</script>
in the dragmove event you guyz can see I get the four corner positions of the dragging box {commented right now} and with this I was able to detect the overlap / collision but it has 2 issues:
1. very slow with only 3 objects in my test
2. if non of the corner points intersect it didn't fire the collision stuff {for this one box can be bigger so it can cover the other entirely}
I would highly apreciate if anyone can please help me accomplish this stuff..
[A] Any object dragging if by any mean overlaps any other object I want it to show collision.
[B] If possible make getIntersection to work on a particular layer group whichever is possible
[C] any other workaround beside kineticJS to accomplish the above task
Regards
Ok, the developer of KineticJS is working on improving the .getIntersections() function... or at least he said he is. But until the function is improved you have to make your own collision detection function. Assuming that your objects are rectangles or can be broken into a series of points you should go with something like this:
Create a function which determines if a point is in a shape (if the corner of a rectangle is inside another rectangle) like so:
function checkCollide(pointX, pointY, objectx, objecty, objectw, objecth) { // pointX, pointY belong to one rectangle, while the object variables belong to another rectangle
var oTop = objecty;
var oLeft = objectx;
var oRight = objectx+objectw;
var oBottom = objecty+objecth;
if(pointX > oLeft && pointX < oRight){
if(pointY > oTop && pointY < oBottom ){
return 1;
}
}
else
return 0;
};
then you can do a big loop which iterates through all objects in a layer to check collision, like so:
var children = layer.getChildren();
for( var i=0; i<children.length; i++){ // for each single shape
for( var j=0; j<children.length; j++){ //check each other shape
if(i != j){ //skip if shape is the same
if(checkCollide(children[i].getX(), children[i].getY(), children[j].getX(), children[j].getY(), children[j].getWidth(), children[j].getHeight()))
alert('top left corner collided');
}
}
}
the checkCollide function I provided only checks the collision for the top left corner on each shape, so you have to modify the function to check all corners, it's not a long rewrite, and there are plenty tutorials even here on stackoverflow which deal with 'bounding rectangles collision detection'
This may seem like it is a very heavy function, but surprisingly it is still faster than .getIntersections(). Also, you should throw in extra if statements so that the function doesn't run through all the checks all the time.
I created a game myself and was using .intersects() and was having a lot of slow down. I switched over to this type of 'simpler' collision detection and now my game runs around 60FPS. http://cs.neiu.edu/~tsam/physics/index.phtml (test/test) if you want to check it out. You can view page source to see how I structured the collision detection to be more efficient (such as in checkIntersectsGoal() function.