Sprite layers are disappearing in AS3 drawing code - actionscript-3

I'm building a custom painting application, and I'm running into a problem where the layers I'm adding to the canvas are disappearing after 24 layers get added.
Here is my code for the drawing tools:
//=====================================================================================================================================
// DRAWING FUNCTIONS
//-------------------------------------------------------------------------------------------------------------------------------------
protected function onMouseDown_canvas( evt:MouseEvent ):void
{
var p:Point = new Point( _realView.mouseX, _realView.mouseY );
_log.log( "CanvasViewController :: onMouseDown_canvas() - mouse:" + p );
_realView.addEventListener( MouseEvent.MOUSE_UP, onMouseUp_canvas );
_realView.addEventListener( MouseEvent.MOUSE_OUT, onMouseOut_canvas );
_realView.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove_canvas );
_currentLayer = new Sprite();
_currentLayer.mouseEnabled = false;
_realView.mcContainer.addChild( _currentLayer );
_$clearFirstBrushStroke = false;
switch( _$tool )
{
case ToolType.ERASER:
case ToolType.BRUSH:
case ToolType.PENCIL:
_currentLayer.graphics.beginFill(
( _$tool == ToolType.ERASER ? 0xffffff : _$color ),
( _$tool == ToolType.BRUSH ? .4 : 1 )
);
_currentLayer.graphics.drawCircle( p.x, p.y, _$toolSize/2 )
_currentLayer.graphics.endFill();
_firstPoint = p;
_$clearFirstBrushStroke = true;
if( _$tool == ToolType.BRUSH )
_currentLayer.filters = [ new BlurFilter( 3, 3, 2 ) ];
break;
case ToolType.BRUSH2:
drawGlitter( _currentLayer.graphics, p );
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------
protected function onMouseUp_canvas( evt:MouseEvent ):void
{
var p:Point = new Point( _realView.mouseX, _realView.mouseY );
_log.log( "CanvasViewController :: onMouseUp_canvas() - mouse:" + p );
endDrawing();
}
//-------------------------------------------------------------------------------------------------------------------------------------
protected function onMouseMove_canvas( evt:MouseEvent ):void
{
var p:Point = new Point( _realView.mouseX, _realView.mouseY );
switch( _$tool )
{
case ToolType.ERASER:
case ToolType.BRUSH:
case ToolType.PENCIL:
if( _$clearFirstBrushStroke )
{
_$clearFirstBrushStroke = false;
_currentLayer.graphics.clear();
_currentLayer.graphics.lineStyle(
_$toolSize,
( _$tool == ToolType.ERASER ? 0xffffff : _$color ),
( _$tool == ToolType.BRUSH ? .4 : 1 ),
true,
LineScaleMode.NORMAL,
CapsStyle.ROUND,
JointStyle.ROUND
);
_currentLayer.graphics.moveTo( _firstPoint.x, _firstPoint.y );
}
_currentLayer.graphics.lineTo( p.x, p.y );
break;
case ToolType.BRUSH2:
drawGlitter( _currentLayer.graphics, p );
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------
protected function onMouseOut_canvas( evt:MouseEvent ):void
{
var p:Point = new Point( _realView.mouseX, _realView.mouseY );
_log.log( "CanvasViewController :: onMouseOut_canvas() - mouse:" + p );
endDrawing();
}
//-------------------------------------------------------------------------------------------------------------------------------------
protected function endDrawing():void
{
var p:Point = new Point( _realView.mouseX, _realView.mouseY );
_log.log( "CanvasViewController :: endDrawing() - mouse:" + p );
_realView.removeEventListener( MouseEvent.MOUSE_UP, onMouseUp_canvas );
_realView.removeEventListener( MouseEvent.MOUSE_OUT, onMouseOut_canvas );
_realView.removeEventListener( MouseEvent.MOUSE_MOVE, onMouseMove_canvas );
var bmd:BitmapData = new BitmapData( _realView.width, _realView.height, true, 0x00000000 );
bmd.draw( _currentLayer );
var bmp:Bitmap = new Bitmap( bmd, "auto", true );
_realView.mcContainer.removeChild( _currentLayer );
_realView.mcContainer.addChild( bmp );
_currentLayer = null;
_log.log( " numChildren:" + _realView.mcContainer.numChildren );
}
//-------------------------------------------------------------------------------------------------------------------------------------
protected function drawGlitter( g:Graphics, c:Point, $glitterSize:Number = 2, $density:Number = .5 ):void
{
var $startAngle:Number = NewMath.Random( 0, Math.PI*2 );
var $stepAngle:Number = $startAngle / ( $density * _$toolSize );
for( var $i:int = 0; $i < ( $density * _$toolSize ); $i++ )
{
var $a:Number = $startAngle + ( $i * $stepAngle );
var $r:Number = NewMath.Random( 0, _$toolSize / 2 );
var p:Point = new Point( c.x + Math.cos( $a ) * $r, c.y + Math.sin( $a ) * $r );
g.beginFill( _$color, 1 );
g.drawCircle( p.x, p.y, $glitterSize / 2 );
g.endFill();
}
}
numChildren continues to grow, but once it hits 24 layers in that container, the first layer gets deleted or goes invisible or something. at 25 layers, the second layer disappears, etc.
See this in action here: http://dev.option5.net/CAUS/CAUS14002/index.html
Could it be a masking issue? Can only so many layers be masked : _realView.mcContainer (where new layers are added) is masked by _realView.mcMask?

Related

ActionScript 3 : Particle Collition

I'm working on my school assignment and i got stuck.
So, the idea is i want to make somehing like in this video, particle collision demonstration (https://www.youtube.com/watch?v=wKqpOOgXLzE) but i cant find any tutorial for that. So i tried to find a tutorial that has similar concept with the video, the pong game. I found a tutorial with multiple ball colliding each other (https://www.emanueleferonato.com/2008/06/07/managing-multiple-balls-collisions-with-flash-as3-version/). and i tried to modify the code to make the ball hit the platform, but sadly it did nothing and i cant think of any other solution.
here's the code:
public class BallCollision extends MovieClip
{
private var mcBallContainer:MovieClip;
private var nNumBalls:Number = 15;
private var mcBrickCOntainer:MovieClip;
private var nStageWidth:Number = 200;
private var nStageHeight:Number = 200;
private var brick1: Brick;
var score:Number = 0;
public function BallCollision ( ) : void
{
mcBallContainer = new MovieClip ( ) ;
mcBallContainer.x = 755;
mcBallContainer.y = 408;
stage.addChild(mcBallContainer);
mcBrickCOntainer = new MovieClip();
mcBrickCOntainer.x = 200;
mcBrickCOntainer.y = 250;
stage.addChild(mcBrickCOntainer);
this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler );
for ( var i = 0; i < nNumBalls; i++ )
{
var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 12 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) );
mcBall.x = Math.random() * nStageWidth;
mcBall.y = Math.random() * nStageHeight;
mcBallContainer.addChild ( mcBall );
brick1 = new Brick();
brick1.x = 700;
brick1.y = 350;
mcBrickCOntainer.addChild(brick1);
}
}
private function enterFrameHandler ( E:Event ) : void
{
for ( var i = 0; i < mcBallContainer.numChildren; i++ )
{
var mcBall1:* = mcBallContainer.getChildAt( i );
for ( var j = i + 1; j < mcBallContainer.numChildren; j++ )
{
var mcBall2:* = mcBallContainer.getChildAt( j );
var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
if ( nDistance < 20 )
{
solveBalls ( mcBall1, mcBall2 );
score += 1;
trace(score);
}
}
}
scoreCounter.text = String(score);
//brickCalling();
}
/*public function brickCalling(){
}*/
private function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip) : void
{
var nX1:Number = MCBallA.x;
var nY1:Number = MCBallA.y;
var nDistX:Number = MCBallB.x - nX1;
var nDistY:Number = MCBallB.y - nY1;
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
var nRadiusA:Number = MCBallA.width/2;
var nRadiusB:Number = MCBallB.width/2;
//var nRadius:Number = 10;
var nNormalX:Number = nDistX/nDistance;
var nNormalY:Number = nDistY/nDistance;
var nMidpointX:Number = ( nX1 + MCBallB.x )/2;
var nMidpointY:Number = ( nY1 + MCBallB.y )/2;
MCBallA.x = nMidpointX - nNormalX * nRadiusA;
MCBallA.y = nMidpointY - nNormalY * nRadiusA;
MCBallB.x = nMidpointX + nNormalX * nRadiusB;
MCBallB.y = nMidpointY + nNormalY * nRadiusB;
var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY );
var nVelX:Number = nVector * nNormalX;
var nVelY:Number = nVector * nNormalY;
MCBallA.nSpeedX -= nVelX;
MCBallA.nSpeedY -= nVelY;
MCBallB.nSpeedX += nVelX;
MCBallB.nSpeedY += nVelY;
}
}
}
I hope someone can guide me, Thanks!
Have you considered using a physics engine, like box2D?
https://www.box2dflash.org

HTML5 canvas drawing, allow multiple touch inputs

I would like to create an web based guestbook for an 84" multi-touch device. I know how to create a canvas which allows a user to draw, but I wonder if the same is possible for multiple users? I have found some information on html5 multi-touch input, but all of it is related to gestures.
Since the surface is large enough and the device supports it, ideally I would like for several users to draw something onto the canvas simultaneously.
Here is whole program. There is no nothing to allow multiple touch inputs.
You only need to access event.changedTouches
Navigate with mobile device and test demo.
I made also button click detection example (HUB BUTTON).
Source: https://github.com/zlatnaspirala/multi-touch-canvas-handler/blob/master/index.html
function MOBILE_CONTROL () {
this.X = null;
this.Y = null;
this.LAST_X_POSITION = null;
this.LAST_Y_POSITION = null;
this.MULTI_TOUCH = 'NO';
this.MULTI_TOUCH_X1 = null;
this.MULTI_TOUCH_X2 = null;
this.MULTI_TOUCH_X3 = null;
this.MULTI_TOUCH_X4 = null;
this.MULTI_TOUCH_X5 = null;
this.MULTI_TOUCH_Y1 = null;
this.MULTI_TOUCH_Y2 = null;
this.MULTI_TOUCH_Y3 = null;
this.MULTI_TOUCH_Y4 = null;
this.MULTI_TOUCH_Y5 = null;
this.MULTI_TOUCH_X6 = null;
this.MULTI_TOUCH_X7 = null;
this.MULTI_TOUCH_X8 = null;
this.MULTI_TOUCH_X9 = null;
this.MULTI_TOUCH_X10 = null;
this.MULTI_TOUCH_Y6 = null;
this.MULTI_TOUCH_Y7 = null;
this.MULTI_TOUCH_Y8 = null;
this.MULTI_TOUCH_Y9 = null;
this.MULTI_TOUCH_Y10 = null;
this.MULTI_TOUCH_INDEX = 1;
this.SCREEN = [window.innerWidth , window.innerHeight];
this.SCREEN.W = this.SCREEN[0];
this.SCREEN.H = this.SCREEN[1];
//Application general
this.AUTOR = "Nikola Lukic";
this.APPLICATION_NAME = "TestApplication";
this.SET_APPLICATION_NAME = function (value) {
if (typeof value != 'string')
throw 'APPLICATION_NAME must be a string!';
if (value.length < 2 || value.length > 20)
throw 'APPLICATION_NAME must be 2-20 characters long!';
this.APPLICATION_NAME = value;
};
this.APP = function(){/*construct*/};
this.APP.BODY = document.getElementsByTagName('body')[0];
this.APP.BODY.SET_STYLE = function (string) {this.style = string;}
this.APP.BODY.SET_BACKGROUND_COLOR = function (color) {this.style.backgroundColor = color;}
this.APP.BODY.SET_COLOR = function (color) {this.style.Color = color;}
this.APP.BODY.ADD_DIV = function (id , style , innerHTML) {
var n = document.createElement('div');
var divIdName = id;
n.setAttribute('id',divIdName);
n.setAttribute('style',style);
n.innerHTML = innerHTML;
this.appendChild(n);
};
this.APP.BODY.ADD_2DCANVAS = function (id,width_,height_) {
var n = document.createElement('canvas');
var divIdName = id;
n.setAttribute('id',divIdName);
n.setAttribute('width',width_);
n.setAttribute('height',height_);
//n.innerHTML = 'Element is here';
this.appendChild(n);
};
console.log('<MOBILE_CONTROL JavaScript class>');
console.log('status:MOBILE_CONTROL FINISH LOADING');
console.log('EASY_IMPLEMENTATION!');
}
function CANVAS_DRAW() {
var run = true;
var timer = null;
window.addEventListener('touchstart', MDPORT, false);
function MDPORT(){
if (run) {
clearInterval(timer);
run = false;
} else {
timer = setInterval(makeHarmonograph, 1);
run = true;
}
}
var A1 = 200, f1 = 2, p1 = 1/16, d1 = 0.02;
var A2 = 10, f2 = 4, p2 = 3 / 2, d2 = 0.0315;
var A3 = 200, f3 = 4, p3 = 13 / 15, d3 = 0.00012;
var A4 = 10, f4 = 4, p4 = 1, d4 = 0.012;
var r = 10, g =10, b = 0;
var UPDOWN = 1,CONTROL_WIDTH = 0;
var ctx = document.getElementById("canvas").getContext("2d");
setInterval(randomColor, 5000);
timer = setInterval(makeHarmonograph, 1);
function randomColor() {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
}
function makeHarmonograph() {
f1 = (f1 / 10) % 10;
f2 = (f2 / 40) % 10;
f3 = (f3 + Math.random() / 80) % 10;
f4 = (f4 + Math.random() / 411) % 10;
p1 += 0.5 % (Math.PI*2)
drawHarmonograph();
}
function drawHarmonograph() {
ctx.clearRect(0, 0, 850, 450);
ctx.save();
ctx.fillStyle = "#000000";
ctx.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect(0, 0, 1100, 400);
ctx.translate(511, 0);
ctx.rotate(1.57);
///////////
// Draw guides
ctx.strokeStyle = '#09f';
ctx.lineWidth = A1 ;
ctx.translate(111, 1);
ctx.rotate(0.01);
if (CONTROL_WIDTH == 0) { UPDOWN=UPDOWN+1;}
if (UPDOWN>51){CONTROL_WIDTH=1; }
if (CONTROL_WIDTH == 0) { UPDOWN=UPDOWN-0.1;}
if (UPDOWN<1){CONTROL_WIDTH=0; }
// Set line styles
ctx.strokeStyle = '#099909';
ctx.lineWidth = UPDOWN;
// check input
ctx.miterLimit = UPDOWN;
// Draw lines
ctx.beginPath();
ctx.moveTo(111,100);
for (i=0;i<121;i++){
var dy = i%2==0 ? 25 : -25 ;
ctx.lineTo(Math.pow(i,1.5)*2,75+dy);
}
ctx.stroke();
return false;
ctx.translate(444, 333);
ctx.fillStyle='lime';
ctx.font="30px Arial";
ctx.fillText("Overlapping harmonics with JavaScript, wait secund.",5,25);
ctx.stroke();
}
}
function CANVAS_DRAW_1(){
var run = true;
var timer = null;
timer = setInterval(makeHarmonograph, 1);
run = true;
var A1 = 200, f1 = 2, p1 = 1/16, d1 = 0.02;
var A2 = 10, f2 = 4, p2 = 3 / 2, d2 = 0.0315;
var A3 = 200, f3 = 4, p3 = 13 / 15, d3 = 0.00012;
var A4 = 10, f4 = 4, p4 = 1, d4 = 0.012;
var r = 10, g =10, b = 0;
var UPDOWN = 1,CONTROL_WIDTH = 0;
var ctx = document.getElementById("canvas_1").getContext("2d");
setInterval(randomColor, 5000);
timer = setInterval(makeHarmonograph, 1);
function randomColor() {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
}
function makeHarmonograph() {
f1 = (f1 / 10) % 10;
f2 = (f2 / 40) % 10;
f3 = (f3 + Math.random() / 80) % 10;
f4 = (f4 + Math.random() / 411) % 10;
p1 += 0.5 % (Math.PI*2)
drawHarmonograph();
}
function drawHarmonograph() {
ctx.clearRect(0, 0, 850, 450);
ctx.save();
ctx.fillStyle = "#000000";
ctx.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect(0, 0, 800, 400);
ctx.translate(0, 250);
ctx.beginPath();
if (A1 > 100) {}
for (var t = 0; t < 100; t+=0.1) {
var x = A1 * Math.sin(f1 * t + Math.PI * p1) * Math.exp(-d1 * t) + A2 * Math.sin(f2 * t + Math.PI * p2) * Math.exp(-d2 * t);
var y = A3 * Math.sin(f3 * t + Math.PI * p1) * Math.exp(-d3 * t) + A4 * Math.sin(f4 * t + Math.PI * p4) * Math.exp(-d4 * t);
//ctx.lineTo(x*x, y/x);
ctx.lineTo(x*x+1, y+1/x);
}
ctx.stroke();
ctx.translate(A1, 0);
ctx.rotate(1.57);
ctx.beginPath();
for (var t = 0; t < 100; t+=0.1) {
var x = A1 * A3* Math.sin(f1 * t + Math.PI * p1) * Math.exp(-d1 * t) + A2 * Math.sin(f2 * t + Math.PI * p2) * Math.exp(-d2 * t);
var y = A3 * Math.sin(f3 * t + Math.PI * p1) * Math.exp(-d3 * t) + A4 * Math.sin(f4 * t + Math.PI * p4) * Math.exp(-d4 * t);
ctx.lineTo(x*x+1, y+1/x);
}
ctx.stroke();
ctx.restore();
// Draw guides
ctx.strokeStyle = '#09f';
ctx.lineWidth = A1;
if (CONTROL_WIDTH == 0) { UPDOWN=UPDOWN+1;}
if (UPDOWN>51){CONTROL_WIDTH=1; }
if (CONTROL_WIDTH == 0) { UPDOWN=UPDOWN-0.1;}
if (UPDOWN<1){CONTROL_WIDTH=0; }
// Set line styles
ctx.strokeStyle = '#099909';
ctx.lineWidth = UPDOWN;
// check input
ctx.miterLimit = 5;
// Draw lines
ctx.beginPath();
ctx.moveTo(0,100);
for (i=0;i<124;i++){
var dy = i%2==0 ? 25 : -25 ;
ctx.lineTo(Math.pow(i,1.5)*2,75+dy);
}
ctx.stroke();
return false;
ctx.translate(A1, 210);
ctx.fillStyle='lime';
ctx.font="30px Arial";
ctx.fillText("Overlapping harmonics with JavaScript, wait secund.",5,25);
}
}
function CANVAS_DRAW_2(){
var timer = null;
var A1 = 200, f1 = 2, p1 = 1/16, d1 = 0.02;
var A2 = 10, f2 = 4, p2 = 3 / 2, d2 = 0.0315;
var A3 = 200, f3 = 4, p3 = 13 / 15, d3 = 0.00012;
var A4 = 10, f4 = 4, p4 = 1, d4 = 0.012;
var r = 10, g =10, b = 0;
var ctx = document.getElementById("canvas_2").getContext("2d");
setInterval(randomColor, 5000);
timer = setInterval(t, 1);
function randomColor() {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
}
function t() {
r1();
}
function r1() {
ctx.clearRect(0, 0, CONTROL.SCREEN.W, CONTROL.SCREEN.H);
ctx.save();
ctx.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, CONTROL.SCREEN.W, CONTROL.SCREEN.H);
ctx.beginPath();
var x = CONTROL.X;
var y = CONTROL.Y;
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect(x, y-400, 1, 2500);
ctx.fillRect(x-400, y, 2500, 1);
ctx.fillText(" ( targetX:" + CONTROL.X + " ( targetY: "+ CONTROL.Y + " ) ",x,y);
ctx.fillStyle = "#00FF00";
ctx.font="10px Arial";
ctx.fillText(" JavaScript ",x- CONTROL.SCREEN.W/3,y - CONTROL.SCREEN.H/3.4);
ctx.fillText(" welcome here , canvas example with MOBILE_TOUCH() ",x - CONTROL.SCREEN.W/3,y - CONTROL.SCREEN.H/3.2);
ctx.fillText(" no css files need, pure js ",x - CONTROL.SCREEN.W/3,y - CONTROL.SCREEN.H/3);
if (CONTROL.X > CONTROL.SCREEN.W/2.2 && CONTROL.X < CONTROL.SCREEN.W/2.2 + 300 && CONTROL.Y > CONTROL.SCREEN.H/2.2 && CONTROL.Y < CONTROL.SCREEN.H/2.2 + 100) {
ctx.strokeStyle = "lime";
}
else{
ctx.strokeStyle = "red";
}
ctx.strokeRect( CONTROL.SCREEN.W/2.2, CONTROL.SCREEN.H/2.2, 300, 100);
ctx.fillText(" HUB DETECT ", CONTROL.SCREEN.W/2, CONTROL.SCREEN.H/2);
if (CONTROL.MULTI_TOUCH_X1 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X1 , CONTROL.MULTI_TOUCH_Y1-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X1 -400 , CONTROL.MULTI_TOUCH_Y1 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X2 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X2 , CONTROL.MULTI_TOUCH_Y2-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X2 -400 , CONTROL.MULTI_TOUCH_Y2 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X3 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X3 , CONTROL.MULTI_TOUCH_Y3-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X3 -400 , CONTROL.MULTI_TOUCH_Y3 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X4 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X4 , CONTROL.MULTI_TOUCH_Y4-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X4 -400 , CONTROL.MULTI_TOUCH_Y4 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X5 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X5 , CONTROL.MULTI_TOUCH_Y5-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X5 -400 , CONTROL.MULTI_TOUCH_51 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X6 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X6 , CONTROL.MULTI_TOUCH_Y6-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X6 -400 , CONTROL.MULTI_TOUCH_Y6 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X7 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X7 , CONTROL.MULTI_TOUCH_Y8-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X7 -400 , CONTROL.MULTI_TOUCH_Y8 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X9 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X9 , CONTROL.MULTI_TOUCH_Y9-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X9 -400 , CONTROL.MULTI_TOUCH_Y9 , 2500, 1);
}
if (CONTROL.MULTI_TOUCH_X10 !== 'undefined'){
ctx.fillRect(CONTROL.MULTI_TOUCH_X10 , CONTROL.MULTI_TOUCH_Y10-400 , 1, 2500);
ctx.fillRect(CONTROL.MULTI_TOUCH_X10 -400 , CONTROL.MULTI_TOUCH_Y10 , 2500, 1);
}
// Draw lines
ctx.fillStyle='lime';
ctx.font="30px Arial";
ctx.fillText("MOBILE_TOUCH example ",5,25);
}
}
//definition
var CONTROL = new MOBILE_CONTROL();
//CONTROL.APP.BODY.ADD_2DCANVAS("canvas");
//CONTROL.APP.BODY.ADD_2DCANVAS("canvas_1");
CONTROL.APP.BODY.ADD_2DCANVAS("canvas_2",CONTROL.SCREEN.W,CONTROL.SCREEN.H);
CONTROL.APP.BODY.SET_STYLE('margin-left:-10px;padding:0;border:none;');
//CANVAS_DRAW();
//CANVAS_DRAW_1();
CANVAS_DRAW_2();
//<!-- SCREEN.prototype.sayHello = function(){alert ('hello' + "sss" );}; -->
//###################################################################
//EVENTS
//###################################################################
document.addEventListener('touchstart', function(event)
{
if (CONTROL.MULTI_TOUCH == 'NO') {
var touch = event.touches[0];
CONTROL.X = touch.pageX;
CONTROL.Y = touch.pageY;
console.log('TOUCH START AT:(X' + CONTROL.X + '),(' + CONTROL.Y + ')' );
}
else if (CONTROL.MULTI_TOUCH == 'YES') {
var touches_changed = event.changedTouches;
for (var i=0; i<touches_changed.length;i++) {
//CONTROL.MULTI_TOUCH_X1
console.log("multi touch : x" + CONTROL.MULTI_TOUCH_INDEX + ":(" +touches_changed[i].pageX + ")");
switch(CONTROL.MULTI_TOUCH_INDEX)
{
case 1:
CONTROL.MULTI_TOUCH_X1=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y1=touches_changed[i].pageY;
break;
case 2:
CONTROL.MULTI_TOUCH_X2=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y2=touches_changed[i].pageY;
break;
case 3:
CONTROL.MULTI_TOUCH_X3=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y3=touches_changed[i].pageY;
break;
case 4:
CONTROL.MULTI_TOUCH_X4=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y4=touches_changed[i].pageY;
break;
case 5:
CONTROL.MULTI_TOUCH_X5=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y5=touches_changed[i].pageY;
break;
case 6:
CONTROL.MULTI_TOUCH_X6=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y6=touches_changed[i].pageY;
break;
case 7:
CONTROL.MULTI_TOUCH_X7=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y7=touches_changed[i].pageY;
break;
case 8:
CONTROL.MULTI_TOUCH_X8=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y8=touches_changed[i].pageY;
break;
case 9:
CONTROL.MULTI_TOUCH_X9=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y9=touches_changed[i].pageY;
break;
case 10:
CONTROL.MULTI_TOUCH_X10=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y10=touches_changed[i].pageY;
break;
default:
//code to be executed if n is different from case 1 and 2
}
CONTROL.MULTI_TOUCH_INDEX = CONTROL.MULTI_TOUCH_INDEX + 1;
}
}
CONTROL.MULTI_TOUCH = 'YES';
},false);
////////////////////////////////////////////////////////
document.addEventListener('touchmove', function(event)
{
var touch = event.touches[0];
CONTROL.X = touch.pageX;
CONTROL.Y = touch.pageY;
console.log('TOUCH MOVE AT:(X' + CONTROL.X + '),(' + CONTROL.Y + ')' );
//#############
if (CONTROL.MULTI_TOUCH == 'YES') {
var touches_changed = event.changedTouches;
for (var i=0; i<touches_changed.length;i++) {
//CONTROL.MULTI_TOUCH_X1
console.log("multi touch : x" + CONTROL.MULTI_TOUCH_INDEX + ":(" +touches_changed[i].pageX + ")");
switch(i)
{
case 1:
CONTROL.MULTI_TOUCH_X1=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y1=touches_changed[i].pageY;
break;
case 2:
CONTROL.MULTI_TOUCH_X2=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y2=touches_changed[i].pageY;
break;
case 3:
CONTROL.MULTI_TOUCH_X3=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y3=touches_changed[i].pageY;
break;
case 4:
CONTROL.MULTI_TOUCH_X4=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y4=touches_changed[i].pageY;
break;
case 5:
CONTROL.MULTI_TOUCH_X5=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y5=touches_changed[i].pageY;
break;
case 6:
CONTROL.MULTI_TOUCH_X6=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y6=touches_changed[i].pageY;
break;
case 7:
CONTROL.MULTI_TOUCH_X7=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y7=touches_changed[i].pageY;
break;
case 8:
CONTROL.MULTI_TOUCH_X8=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y8=touches_changed[i].pageY;
break;
case 9:
CONTROL.MULTI_TOUCH_X9=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y9=touches_changed[i].pageY;
break;
case 10:
CONTROL.MULTI_TOUCH_X10=touches_changed[i].pageX;
CONTROL.MULTI_TOUCH_Y10=touches_changed[i].pageY;
break;
default:
//code to be executed if n is different from case 1 and 2
}
}}
//#############
event.preventDefault();
},false);
////////////////////////////////////////////////////////
document.addEventListener('touchend', function(event)
{
CONTROL.LAST_X_POSITION = CONTROL.X;
CONTROL.LAST_Y_POSITION = CONTROL.Y;
CONTROL.MULTI_TOUCH = 'NO';
CONTROL.MULTI_TOUCH_INDEX = 1;
CONTROL.MULTI_TOUCH_X1 = null;
CONTROL.MULTI_TOUCH_X2 = null;
CONTROL.MULTI_TOUCH_X3 = null;
CONTROL.MULTI_TOUCH_X4 = null;
CONTROL.MULTI_TOUCH_X5 = null;
CONTROL.MULTI_TOUCH_X6 = null;
CONTROL.MULTI_TOUCH_X7 = null;
CONTROL.MULTI_TOUCH_X8 = null;
CONTROL.MULTI_TOUCH_X9 = null;
CONTROL.MULTI_TOUCH_X10 = null;
CONTROL.MULTI_TOUCH_Y1 = null;
CONTROL.MULTI_TOUCH_Y2 = null;
CONTROL.MULTI_TOUCH_Y3 = null;
CONTROL.MULTI_TOUCH_Y4 = null;
CONTROL.MULTI_TOUCH_Y5 = null;
CONTROL.MULTI_TOUCH_Y6 = null;
CONTROL.MULTI_TOUCH_Y7 = null;
CONTROL.MULTI_TOUCH_Y8 = null;
CONTROL.MULTI_TOUCH_Y9 = null;
CONTROL.MULTI_TOUCH_Y10 = null;
console.log('LAST TOUCH POSITION AT:(X' + CONTROL.X + '),(' + CONTROL.Y + ')' );
},false);
////////////////////////////////////////////////////////
document.addEventListener("touchcancel", function(event)
{
console.log('BREAK - LAST TOUCH POSITION AT:(X' + CONTROL.X + '(,(' + CONTROL.Y + ')' );
}, false);
////////////////////////////////////////////////////////

How can I use this code on frame

I trying to make bouncing balls.I use this example:
But I don't work on class files, and I'm trying to use as frame code.Here is what I do so far.
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import Ball;
var nSpeedX:Number;
var nSpeedY:Number;
var nStageWidth:Number = 500;
var nStageHeight:Number = 400;
var NSpeedX:Number;
var NSpeedY:Number;
var mcBallContainer:MovieClip;
var MCBallA:MovieClip;
var MCBallB:MovieClip;
var nNumBalls:Number = 1;
stage.addEventListener(Event.ENTER_FRAME,BallCollision);
function BallCollision(oly:Event) {
mcBallContainer = new MovieClip ( ) ;
mcBallContainer.x = mcBallContainer.y = 0;
stage.addChild(mcBallContainer);
this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler );
for (var i = 0; i < nNumBalls; i++)
{
var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 1 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) );
mcBall.x = Math.random() * nStageWidth;
mcBall.y = Math.random() * nStageHeight;
mcBallContainer.addChild ( mcBall );
}
stage.removeEventListener(Event.ENTER_FRAME,BallCollision) //Fixed
}
function enterFrameHandler(oly:Event) {
for ( var i = 0; i < mcBallContainer.numChildren; i++ )
{
var mcBall1:* = mcBallContainer.getChildAt( i );
for ( var j = i + 1; j < mcBallContainer.numChildren; j++ )
{
var mcBall2:* = mcBallContainer.getChildAt( j );
var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
if ( nDistance < 20 )
{
solveBalls ( mcBall1, mcBall2 );
}
}
}
//
function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip ) : void{
var nX1:Number = MCBallA.x;
var nY1:Number = MCBallA.y;
var nDistX:Number = MCBallB.x - nX1;
var nDistY:Number = MCBallB.y - nY1;
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
var nRadiusA:Number = MCBallA.width/2;
var nRadiusB:Number = MCBallB.width/2;
//var nRadius:Number = 10;
var nNormalX:Number = nDistX/nDistance;
var nNormalY:Number = nDistY/nDistance;
var nMidpointX:Number = ( nX1 + MCBallB.x )/2;
var nMidpointY:Number = ( nY1 + MCBallB.y )/2;
MCBallA.x = nMidpointX - nNormalX * nRadiusA;
MCBallA.y = nMidpointY - nNormalY * nRadiusA;
MCBallB.x = nMidpointX + nNormalX * nRadiusB;
MCBallB.y = nMidpointY + nNormalY * nRadiusB;
var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY );
var nVelX:Number = nVector * nNormalX;
var nVelY:Number = nVector * nNormalY;
MCBallA.nSpeedX -= nVelX;
MCBallA.nSpeedY -= nVelY;
MCBallB.nSpeedX += nVelX;
MCBallB.nSpeedY += nVelY;
}
}
My code is working but balls number More than it should be.And balls is not collision each other. What is wrong of my code ??
UPDATED Thanks #Organis

as3 multidimensional array

Im trying to make a multidimensional array but I obtain an error ("TypeError: Error #1010: A term is undefined and has no properties.").
var matriz:Array = new Array();
for(var p:Number = 0; p<2;p++ ){
for(var q:Number = 0; q<2;q++ ){
matriz[p][q] = 0;
}
}
what am I doing wrong?
Thanks in advance!
You need to create an array within matriz[p] before you can add an array (or anything else) into it.
You can achieve what you're attempting without errors like this:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++)
{
// Create an array at matriz[p] if undefined.
if(matriz[p] == undefined) matriz[p] = [];
for(var q:Number = 0; q<2; q++)
{
matriz[p][q] = 0;
}
}
Essentially you were trying to do the same as this:
var object:Object = {};
object.nonexistantProperty.value = 10;
What Marty has said is correct, however I prefer removing the if condition and changing the code to the following:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++) {
matriz[p] = [];
for(var q:Number = 0; q<2; q++) {
matriz[p][q] = 0;
}
}
public class cArray
{
private var DIM1CAP:uint=0;
private var DIM2CAP:uint=1;
private var DIM3CAP:uint=2;
private var DIM4CAP:uint=3;
private var DIM5CAP:uint=4;
public function cArray():void
{
// avoid the noid
}
// returns empty array of args.length dimensions
// 1st argument is dim 1 capacity; 2nd is dim 2, etc.
public function getArray ( ... args ):Array
{
var arr = new Array();
if ( paramsNotValid(args) )
{
return null;
}
switch (args.length)
{
case 2:
arr = get2DArray ( args[0], args[1] );
break;
case 3:
arr = get3DArray ( args[0], args[1], args[2] );
break;
case 4:
arr = get4DArray ( args[0], args[1], args[2], args[3] );
break;
case 5:
arr = get5DArray ( args[0], args[1], args[2], args[3], args[4] );
break;
default:
break;
}
return arr;
}
// returns empty 2d array of parameter specified capacity
private function get2DArray ( _1stDimCapacity:uint, _2ndDimCapacity:uint ):Array
{
var arr2d:Array = [];
var arr1d = new Array();
for ( var i:uint=0; i<_1stDimCapacity; i++ )
{
arr1d[_2ndDimCapacity-1] = undefined;
arr2d.push(arr1d);
arr1d = new Array();
}
return arr2d;
}
// returns empty 3d array of parameter specified capacity
private function get3DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint ):Array
{
var arr3d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr3d.push ( get2DArray ( dim2Cap, dim3Cap ) );
}
return arr3d;
}
// returns empty 4d array of parameter specified capacity
private function get4DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint):Array
{
var arr4d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr4d.push ( get3DArray ( dim2Cap, dim3Cap, dim4Cap ) );
}
return arr4d;
}
// returns empty 5d array of parameter specified capacity
private function get5DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint,
dim5Cap:uint):Array
{
var arr5d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr5d.push ( get4DArray ( dim2Cap, dim3Cap, dim4Cap, dim5Cap ) );
}
return arr5d;
}
//////////////////////////////////////////////////////
private function paramsNotValid ( args:Array ):Boolean
{
if ( args.length<2 || args.length>5 )
{
return true;
}
for ( var i:uint=0; i<args.length; i++ )
{
if ( ! ( args[i]>0 ) )
{
break;
}
}
if ( i < args.length )
{
return true;
}
return false;
}
}
}
public class cMain extends MovieClip
{
var cArr:cArray = new cArray;
public function cMain():void
{
var arr2d:Array;
var arr3d:Array;
var chessBrd_4d:Array;
var arr5d:Array;
// capacity of 10 games; 150 moves/gm; white's mv or black's;
// - piece positions; move in chess notation (index 32 of
// - last dimension); commentary (index 33 of last dimension)
chessBrd_4d = cArr.getArray(10,150,2,34);
// adding data
// - 4th game, 8th move, white's move, positions of pieces
chessBrd_4d[3][7][0][0] = 'd8';
chessBrd_4d[3][7][0][1] = 'b1';
// ...
// - positions of pieces up to last one
// ...
// - last piece pos
chessBrd_4d[3][7][0][31] = 'captured';
// - actual move in chess notation
chessBrd_4d[3][7][0][32] = 'nC4';
// - annotation
chessBrd_4d[3][7][0][33] = 'blocks b pawn, ' +
'opens diag for c1 bishop, ' +
'Justin Beiber is a putz, ' +
'the president is liar'
trace ( 'piece 0 is on square ' + chessBrd_4d[3][7][0][0]);
trace ( 'piece 1 is on square ' + chessBrd_4d[3][7][0][1]);
trace ( ' ... ' )
trace ( 'piece 31 has been ' + chessBrd_4d[3][7][0][31]);
trace ( 'move: ' + chessBrd_4d[3][7][0][32]);
trace ( chessBrd_4d[3][7][0][33]);
/*
trace results:
piece 0 is on square d8
piece 1 is on square b1
...
piece 31 has been captured
move: nC4
blocks b pawn, opens diag for c1 bishop,
Justin Beiber is a putz, the president is liar
*/
/*
trace ( chessBrd_4d.length ); = 10
trace ( chessBrd_4d [ 2 ].length ); = 150
trace ( chessBrd_4d [ 2 ] [ 4 ].length ); = 2
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 1 ].length ); = 34
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 0 ] .length); = 34
*/
}
}

Iterating each pixel of a Bitmap image in ActionScript

Is it possible to iterate each pixel of a bitmap image? Eventually what I'm trying to achieve is that I need to get the coordinate values of each pixel of a bitmap image and change the color of those pixels according to their coordinate values. As I see it, I need to use the getPixels() method but I still did not understand exactly what I should do.
( too slow :) )
so this is the sae as above with a linear loop instead of 2 nested loops.
//creates a new BitmapData, with transparency, white 0xFFFFFF
var bd:BitmapData = new BitmapData( 100, 100, false, 0xFFFFFF );
//stores the width and height of the image
var w:int = bd.width;
var h:int = bd.height;
var i:int = w * h;
var x:int, y:int, col;
//decremental loop are said to be faster :)
while ( i-- )
{
//this is the position of each pixel in x & y
x = i % w;
y = int( i / w );
//gets the current color of the pixel ( 0xFFFFFF )
col = bd.getPixel( x, y );
//assign the 0xFF0000 ( red ) color to the pixel
bd.setPixel( x, y, 0xFF0000 );
}
addChild( new Bitmap( bd ) );//a nice red block
note that if you're using a bitmapData with an alpha channel (say if you load the image, the alpha will be turned on automatically ) you 'll have to use
bd.getPixel32( x, y );// returns a uint : 0xFF000000
//and
bd.setPixel32( x, y, UINT );// 0xFF000000
EDIT : I 've done a quick bench :
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.utils.getTimer;
public class pixels extends Sprite
{
private var bd:BitmapData = new BitmapData( 100, 100, false, 0xFFFFFF );
public function pixels()
{
var i:int, total:int = 100, t:int = 0;
t = getTimer();
i = total;
while( i-- )
{
whileLoop( bd );
}
trace( 'while:', getTimer() - t );
t = getTimer();
i = total;
while( i-- )
{
forLoop( bd );
}
trace( 'for:', getTimer() - t );
}
private function forLoop( bd:BitmapData ):void
{
var i:int, j:int;
var col:int;
for ( i = 0; i < bd.width; i++ )
{
for ( j = 0; j < bd.height; j++ )
{
col = bd.getPixel( i, j ); // +/- 790 ms
}
}
//for ( i = 0; i < bd.width; i++ ) for ( j = 0; j < bd.height; j++ ) col = bd.getPixel( i, j ); // +/-530 ms
//var w:int = bd.width;
//var h:int = bd.height;
//for ( i = 0; i < w; i++ ) for ( j = 0; j < h; j++ ) col = bd.getPixel( i, j ); // +/-250 ms
}
private function whileLoop( bd:BitmapData ):void
{
var w:int = bd.width;
var h:int = bd.height;
var i:int = w * h;
var col:int;
while ( i-- )
{
col = bd.getPixel( i % w, int( i / w ) ); // +/- 580 ms
}
//while ( i-- ) col = bd.getPixel( i % w, int( i / w ) ); // +/- 330 ms
}
}
}
for 100 * ( 100 * 100 ) getPixel, the fastest (on my machine) is the one-line for loop with local variables. ( +/- 250 ms ) then the one-line while( +/- 330 ms ) :)
storing local variables w and h for width and height makes the for loops twice faster :)
good to know
If, as you say, you are only setting the pixels based on their x and y, you need neither getPixel() nor getPixels()!
myBitmapData.lock();
for( var j:int = 0; j < myBitmapData.height; j++ )
{
for( var i:int = 0; i < myBitmapData.width; i++ )
{
var alpha:uint = 0xFF000000; // Alpha is always 100%
var red:uint = 0x00FF0000 * ( i / myBitmapData.width ); // Set red based on x
var green:uint = 0x0000FF00 * ( j / myBitmapData.height ); // Set green based on y
var newColor:uint = alpha + red + green; // Add the components
// Set the new pixel value (setPixel32() includes alpha, e.g. 0xFFFF0000 => alpha=FF, red=FF, green=00, blue=00)
myBitmapData.setPixel32( i, j, newColor );
}
}
myBitmapData.unlock();
If, however, you want to read the pixels' current value, let me join the speed competition.
In addition to earlier answers, here's much more speed increase!
Instead of numerous calls to getPixel(), you can use getPixels() to get a byteArray of the pixel data.
myBitmapData.lock();
var numPixels:int = myBitmapData.width * myBitmapData.height;
var pixels:ByteArray = myBitmapData.getPixels( new Rectangle( 0, 0, myBitmapData.width, myBitmapData.height ) );
for( var i:int = 0; i < numPixels; i++ )
{
// Read the color data
var color:uint = pixels.readUnsignedInt();
// Change it if you like
// Write it to the pixel (setPixel32() includes alpha, e.g. 0xFFFF0000 => alpha=FF, red=FF, green=00, blue=00)
var theX:int = i % myBitmapData.width;
myBitmapData.setPixel32( theX, ( i - theX ) / myBitmapData.width, color );
}
myBitmapData.unlock();
You need a BitmapData object. Then, it's a simple straight-forward nested loop :
var pix : int; //AS3 uses int even for uint types
for (var x:int = 0; x < myBitmapData.width; x++)
{
for (var y:int = 0; y < myBitmapData.height; y++)
{
// This'll get you the pixel color as RGB
pix = myBitmapData.getPixel(x,y);
// To change the color, use the setPixel method + the uint corresponding
// to the new color.
}
}