Thursday, 13 October 2011

Arrays and Hit tests

Today we made something called an Array in flash. An Array is like a big list, each line in the list has a specific number and each line holds information. In our code we used an Array to repeat a code to make a box so we  have more than one but we don't have to write the whole code out.



var blockArray:Array=new Array();
//make a new array called blockArray


for (var i:int = 0; i < 15; i++) {
//Add a line until it has 15
var cube:MovieClip = new box();
//make a varible called cube using box from the library
cube.x=Math.random()*550
//random position along the x axis untill 550 (document size)
cube.y=Math.random()*400
//random position along y axis
addChild(cube);
//adds cube

blockArray[i]=cube;
//fills list with 15 cubes
}


Next we made a quick hit test code


stage.addEventListener(Event.ENTER_FRAME, checkHit);
//listen to the stage on all frames, run a function called checkhit
function checkHit(myevent:Event):void {
for (var i:int = 0;i<15; i++) {
if (blockArray[i].hitTestPoint(mouseX,mouseY, true)) {
//if the cubes in the blockArray get's hit by the mouse either on the x axis or y axis
blockArray[i].alpha=.3;
//the alpha (transparency) goes down to 0.3
}
}
}


We also made a code for two objects on the stage hitting each other.

stage.addEventListener(Event.ENTER_FRAME, checkHit);
//listen to the frame and run a function called checkHit
function checkHit(myevent:Event):void {

Cube1.x+=3


//set cube1 to move right at a speed of 3 pixels

Cube2.x-=3


//Same with cube2 but left

if (Cube2.hitTestPoint(Cube1.x,Cube1.y,true)) {

//if cube 2 gets hit by cube 1 along either the x or y axis


Cube1.alpha=.3;


//The alpha of cube 1 goes down to 0.3

}
}


No comments:

Post a Comment