move object within given perimeter only - actionscript-3

I'm creating a game(not exactly) for kids. It's to illustrate we can make infinite triangles with fixed length of thread, pin board and three pins. Like below:
Students can move any pin. Doing so will create new triangle but the perimeter of the triangle should be of given length. I used the following code:
var xMax:Number = drawBoard.x + drawBoard.width;
var xMin:Number = drawBoard.x;
var yMax:Number = drawBoard.y + drawBoard.height;
var yMin:Number = drawBoard.y;
var isDragging1:Boolean = false;
var isDragging2:Boolean = false;
var isDragging3:Boolean = false;
drawBoard.x = xMin;
drawBoard.y = yMin;
var lines:Shape = new Shape();
addChild(lines);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseUpdate);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
pin1.addEventListener(MouseEvent.MOUSE_DOWN, startDragging1);
pin2.addEventListener(MouseEvent.MOUSE_DOWN, startDragging2);
pin3.addEventListener(MouseEvent.MOUSE_DOWN, startDragging3);
function mouseUpdate(evt:MouseEvent):void
{
if (isDragging1)
{
pin1.x = validX(evt.stageX);
pin1.y = validY(evt.stageY);
lines.graphics.clear();
drawLines();
}
if (isDragging2)
{
pin2.x = validX(evt.stageX);
pin2.y = validY(evt.stageY);
lines.graphics.clear();
drawLines();
}
if (isDragging3)
{
pin3.x = validX(evt.stageX);
pin3.y = validY(evt.stageY);
lines.graphics.clear();
drawLines();
}
evt.updateAfterEvent();
}
function validX(thisX:Number):Number
{
if (thisX < xMin)
{
return (xMin);
}
if (thisX > (xMax))
{
return (xMax);
}
return (thisX);
}
function validY(thisY:Number):Number
{
if (thisY < yMin)
{
return (yMin);
}
if (thisY > (yMax))
{
return (yMax);
}
return thisY;
}
function drawLines():void
{
lines.graphics.lineStyle(1, 0xFF0000);
lines.graphics.moveTo(pin1.x, pin1.y);
lines.graphics.lineTo(pin2.x, pin2.y);
lines.graphics.lineTo(pin3.x, pin3.y);
lines.graphics.lineTo(pin1.x, pin1.y);
lines.filters = [new DropShadowFilter()];
}
function startDragging1(evt:MouseEvent):void
{
isDragging1 = true;
}
function startDragging2(evt:MouseEvent):void
{
isDragging2 = true;
}
function startDragging3(evt:MouseEvent):void
{
isDragging3 = true;
}
function stopDragging(evt:MouseEvent):void
{
isDragging1 = false;
isDragging2 = false;
isDragging3 = false;
}
function DistanceTwoPoints(x1:Number, x2:Number, y1:Number, y2:Number):Number
{
var dx:Number = x1 - x2;
var dy:Number = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
It does the half part. I can move any pin and it will create triangle. But the perimeter is different everytime. I tried to restrict it by calculating the distance between three sides. The problem with that is, I can move pin anywhere which makes it difficult to get exact perimeter. As a result, it makes it difficult to move pins smoothly. So, my question is, is it possible to move the pins only to valid location instead of moving along mouse? Any help would be appreciated.

Related

Action Script 3.0: how can I type other languages in the array or how can I use the other languages in grids

Here is my code. This is my word search game ...In word list array ...these are my questions to find in grid in the game...my questions how can I type other languages in the array or how can I use the other languages in grids
import flash.display.*;
import flash.text.*;
import flash.geom.Point;
import flash.events.*;
import flash.net.FileFilter;
import flash.filters.GlowFilter;
const puzzleSize:uint = 20;
const spacing:Number = 24;
const outlineSize:Number = 20;
const offsetoint = new Point(162.9,179.7);
const offsettoint = new Point(300,265);
const spacingg:Number = 36;
const letterFormat:TextFormat = new TextFormat("Bamini",18,0x000000,true,false,false,null,null,TextFormatAlign.CENTER);
// words and grid
var wordList:Array;
var usedWords:Array;
var grid:Array;
// game state
var dragModetring;
var startPoint,endPointoint;
var numFound:int;
// sprites
var gameSpriteprite;
var outlineSpriteprite;
var oldOutlineSpriteprite;
var letterSpritesprite;
var wordsSpriteprite;
startWordSearch();
function startWordSearch() {
**// word list**
wordList = ("Lion,Tiger,Cheetah,Panther".split(",";
// set up the sprites
gameSprite = new Sprite();
addChild(gameSprite);
oldOutlineSprite = new Sprite();
gameSprite.addChild(oldOutlineSprite);
outlineSprite = new Sprite();
gameSprite.addChild(outlineSprite);
letterSprites = new Sprite();
gameSprite.addChild(letterSprites);
wordsSprite = new Sprite();
gameSprite.addChild(wordsSprite);
// array of letters
var letters:Array = placeLetters();
// array of sprites
grid = new Array();
for(var x:int=0;x<puzzleSize;x++) {
grid[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
// create new letter field and sprite
var newLetter:TextField = new TextField();
newLetter.defaultTextFormat = letterFormat;
newLetter.x = x*spacing + offset.x;
newLetter.y = y*spacing + offset.y;
newLetter.width = spacing;
newLetter.height = spacing;
newLetter.text = letters[x][y];
newLetter.selectable = false;
var newLetterSpriteprite = new Sprite();
newLetterSprite.addChild(newLetter);
letterSprites.addChild(newLetterSprite);
grid[x][y] = newLetterSprite;
// add event listeners
newLetterSprite.addEventListener(MouseEvent.MOUSE_DOWN, clickLetter);
newLetterSprite.addEventListener(MouseEvent.MOUSE_OVER, overLetter);
}
}
// stage listener
stage.addEventListener(MouseEvent.MOUSE_UP, mouseRelease);
// create word list fields and sprites
for(var i:int=0;i<usedWords.length;i++) {
//var myglow:GlowFilter=new GlowFilter();
//myglow.color = 0x0000FF;
//myglow.blurX=5;
//myglow.blurY=5;
//myglow.strength=200;
var newWord:TextField = new TextField();
newWord.defaultTextFormat = letterFormat;
newWord.x = 700;
newWord.y = i*spacingg+offsett.y;
newWord.width =140;
newWord.height =spacing;
newWord.text = usedWords[i];
//newWord.filters=[myglow];
newWord.selectable = false;
wordsSprite.addChild(newWord);
}
// set game state
dragMode = "none";
numFound = 0;
}
// place the words in a grid of letters
function placeLetters():Array {
// create empty grid
var letters:Array = new Array();
for(var x:int=0;x<puzzleSize;x++) {
letters[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
letters[x][y] = "*";
}
}
// make copy of word list
var wordListCopy:Array = wordList.concat();
usedWords = new Array();
// make 1000 attempts to add words
var repeatTimes:int = 1000;
repeatLoop:while (wordListCopy.length > 0) {
if (repeatTimes-- <= 0) break;
// pick a random word, location and direction
var wordNum:int = Math.floor(Math.random()*wordListCopy.length);
var wordtring = wordListCopy[wordNum].toUpperCase();
x = Math.floor(Math.random()*puzzleSize);
y = Math.floor(Math.random()*puzzleSize);
var dx:int = Math.floor(Math.random()*3)-1;
var dy:int = Math.floor(Math.random()*3)-1;
if ((dx == 0) && (dy == 0)) continue repeatLoop;
// check each spot in grid to see if word fits
letterLoop:for (var j:int=0;j<word.length;j++) {
if ((x+dx*j < 0) || (y+dy*j < 0) || (x+dx*j >= puzzleSize) || (y+dy*j >= puzzleSize)) continue repeatLoop;
var thisLettertring = letters[x+dx*j][y+dy*j];
if ((thisLetter != "*" && (thisLetter != word.charAt(j))) continue repeatLoop;
}
// insert word into grid
insertLoop:for (j=0;j<word.length;j++) {
letters[x+dx*j][y+dy*j] = word.charAt(j);
}
// remove word from list
wordListCopy.splice(wordNum,1);
usedWords.push(word);
}
// fill rest of grid with random letters
for(x=0;x<puzzleSize;x++) {
for(y=0;y<puzzleSize;y++) {
if (letters[x][y] == "*" {
letters[x][y] = String.fromCharCode(65+Math.floor(Math.random()*26));
}
}
}
return letters;
}
// player clicks down on a letter to start
function clickLetter(event:MouseEvent) {
var lettertring = event.currentTarget.getChildAt(0).text;
startPoint = findGridPoint(event.currentTarget);
dragMode = "drag";
}
// player dragging over letters
function overLetter(event:MouseEvent) {
if (dragMode == "drag" {
endPoint = findGridPoint(event.currentTarget);
// if valid range, show outline
outlineSprite.graphics.clear();
if (isValidRange(startPoint,endPoint)) {
drawOutline(outlineSprite,startPoint,endPoint,0x66CCFF);
}
}
}
// mouse released
function mouseRelease(event:MouseEvent) {
if (dragMode == "drag" {
dragMode = "none";
outlineSprite.graphics.clear();
// get word and check it
if (isValidRange(startPoint,endPoint)) {
var word = getSelectedWord();
checkWord(word);
}
}
}
// when a letter is clicked, find and return the x and y location
function findGridPoint(letterSpritebject)oint {
// loop through all sprites and find this one
for(var x:int=0;x<puzzleSize;x++) {
for(var y:int=0;y<puzzleSize;y++) {
if (grid[x][y] == letterSprite) {
return new Point(x,y);
}
}
}
return null;
}
// determine if range is in the same row, column, or a 45 degree diagonal
function isValidRange(p1,p2oint):Boolean {
if (p1.x == p2.x) return true;
if (p1.y == p2.y) return true;
if (Math.abs(p2.x-p1.x) == Math.abs(p2.y-p1.y)) return true;
return false;
}
// draw a thick line from one location to another
function drawOutline(sprite,p1,p2oint,c:Number) {
var offoint = new Point(offset.x+spacing/2, offset.y+spacing/2);
s.graphics.lineStyle(outlineSize,c);
s.graphics.moveTo(p1.x*spacing+off.x ,p1.y*spacing+off.y);
s.graphics.lineTo(p2.x*spacing+off.x ,p2.y*spacing+off.y);
}
// find selected letters based on start and end points
function getSelectedWord()tring {
// determine dx and dy of selection, and word length
var dx = endPoint.x-startPoint.x;
var dy = endPoint.y-startPoint.y;
var wordLength:Number = Math.max(Math.abs(dx),Math.abs(dy))+1;
// get each character of selection
var wordtring = "";
for(var i:int=0;i<wordLength;i++) {
var x = startPoint.x;
if (dx < 0) x -= i;
if (dx > 0) x += i;
var y = startPoint.y;
if (dy < 0) y -= i;
if (dy > 0) y += i;
word += grid[x][y].getChildAt(0).text;
}
return word;
}
// check word against word list
function checkWord(wordtring) {
// loop through words
for(var i:int=0;i<usedWords.length;i++) {
// compare word
if (word == usedWords[i].toUpperCase()) {
foundWord(word);
}
// compare word reversed
var reverseWordtring = word.split("".reverse().join("";
if (reverseWord == usedWords[i].toUpperCase()) {
foundWord(reverseWord);
}
}
}
// word found, remove from list, make outline permanent
function foundWord(wordtring) {
// draw outline in permanent sprite
drawOutline(oldOutlineSprite,startPoint,endPoint,0xE01212);
// find text field and set it to gray
for(var i:int=0;i<wordsSprite.numChildren;i++) {
if (TextField(wordsSprite.getChildAt).text.toUpperCase() == word) {
TextField(wordsSprite.getChildAt).textColor = 0xFF0000;
}
}
// see if all have been found
numFound++;
if (numFound ==usedWords.length) {
endGame();
}
}
function endGame() {
gotoAndStop("gameover";
cleanUp();
Timee.stop();
}
function cleanUp() {
removeChild(gameSprite);
gameSprite = null;
grid = null;
vv=null;
}

Trouble with addChild/removeChild and display list order in ActionScript3

I am working on a project, which includes a Lake symbol that the player can throw stones into, which in turn causes octopi to rise out of the lake in the positions that each stone hits the lake.
There is also a symbol for the splash made by the stone which will appear after the stone hits and before the octopus appears.
It is likely that there will be many octopi on the screen at the same time and they need to be ordered in the display list so that the ones that should appear further back are behind the others.
Each instance of these symbols should only play once and then be removed.
My code for this makes use of the different add/remove child method alongside for loops, conditionals and arrays which I have put together with the help of various tutorials and forums.
The problem I have is that when you click on the lake two or more times in quick succession, the stone and the splash symbols aren't removed properly and often keep looping.
Here is the code I am using. Any ideas?
var stone:Stone;
var stoneSplash:StoneSplash;
var octopus1:Octopus1;
var octopus2:Octopus2;
var whichOctopus:Array = [addOctopus1, addOctopus2];
var octopusScale:Number;
var octopusContainer:MovieClip = new MovieClip;
lake.lakeHitArea.addEventListener(MouseEvent.CLICK, onClickLake);
//Add octopusContainer to the stage's display list just above the Lake
addChildAt(octopusContainer,getChildIndex(lake) + 1);
octopusContainer.x = 0;
octopusContainer.y = 0;
function onClickLake(e:MouseEvent):void
{
trace("CLICK");
throwStone(mouseX, mouseY);
}
function throwStone(stonePositionX:int, stonePositionY:int)
{
stone = new Stone();
stone.x = stonePositionX;
stone.y = stonePositionY;
addChild(stone);
addEventListener(Event.ENTER_FRAME, removeStone);
}
function removeStone(e:Event):void
{
var count:int = numChildren;
var children:Array = [count];
//load all the children of the component into an Array
for (var i:int=0; i<count/* -1*/; i++)
{
children[i] = getChildAt(i/* + 1*/);
}
for (i=0; i<count/* - 1*/; i++)
{
if (children[i] is Stone)
{
if (children[i].currentFrameLabel == "Splash")
{
stoneSplash = new StoneSplash();
octopusContainer.addChild(stoneSplash);
stoneSplash.x = children[i].x;
stoneSplash.y = children[i].y;
}
if (children[i].currentFrameLabel == "end")
{
octopusContainer.removeChild(stoneSplash);
var positionX:int = children[i].x;
var positionY:int = children[i].y;
addOctopus(positionX, positionY);
removeChild(children[i]);
}
}
}
}
function addOctopus(positionX, positionY)
{
var o:int = Math.round(randomNumber(0,1));
whichOctopus[o](positionX, positionY);
reorderDisplayList();
addEventListener(Event.ENTER_FRAME, removeOctopus);
}
function addOctopus1(positionX: int, positionY:int):void
{
// if (whichOctopus1 == true)
// {
// var octopus:* = octopus1_1;
// }
// else
// {
// octopus = octopus1_2;
// }
octopus1 = new Octopus1();
var octopus:DisplayObject = octopus1;
octopusContainer.addChild(octopus);
octopus.x = positionX;
octopus.y = positionY;
octopusScale = randomNumber(0.5,0.85);
octopus.scaleX = octopusScale;
octopus.scaleY = octopusScale;
trace("children = " + octopusContainer.numChildren);
testPosition(octopus);
}
function addOctopus2(positionX: int, positionY:int):void
{
// if (whichOctopus2 == true)
// {
// var octopus:* = octopus2_1;
// }
// else
// {
// octopus = octopus2_2;
// }
octopus2 = new Octopus2();
var octopus:DisplayObject = octopus2;
octopusContainer.addChild(octopus);
octopus.x = positionX;
octopus.y = positionY;
octopusScale = randomNumber(0.25,0.5);
octopus.scaleX = octopusScale;
octopus.scaleY = octopusScale;
trace("children = " + octopusContainer.numChildren);
testPosition(octopus);
}
function testPosition(octopus:Object):void
{
trace(octopus)
for (var i:int = 0; i < 200; i++)
{
if (lake.hitTestPoint(octopus.x + octopus.hitTestBox1.x * octopus.scaleX,octopus.y + octopus.hitTestBox1.y * octopus.scaleY,true))
{
break;
}
else
{
octopus.x++;
}
}
for (i = 0; i < 100; i++)
{
if (lake.hitTestPoint(octopus.x + octopus.hitTestBox2.x * octopus.scaleX,octopus.y + octopus.hitTestBox2.y * octopus.scaleY,true))
{
break;
}
else
{
octopus.y--;
}
}
for (i = 0; i < 200; i++)
{
if (lake.hitTestPoint(octopus.x + octopus.hitTestBox3.x * octopus.scaleX,octopus.y + octopus.hitTestBox3.y * octopus.scaleY,true))
{
break;
}
else
{
trace(i);
octopus.x--;
}
}
for (i = 0; i < 100; i++)
{
if (lake.hitTestPoint(octopus.x + octopus.hitTestBox1.x * octopus.scaleX,octopus.y + octopus.hitTestBox1.y * octopus.scaleY,true))
{
break;
}
else
{
octopus.y--;
trace(i);
}
}
}
function randomNumber(min:Number, max:Number):Number
{
return Math.random() * (max - min) + min;
}
function reorderDisplayList():void
{
//the number of children in our component
var count:int = octopusContainer.numChildren;
var children:Array = [count];
//load all the children of the component into an Array
for (var i:int=0; i<count; i++)
{
children[i] = octopusContainer.getChildAt(i);
}
//sort the Array children based on their 'y' property
children.sortOn("y", Array.NUMERIC);
//re-add the children to the component ;
//in the order of the sorted Array we just created.
//When we add the children using 'addChild' it will
//be added at the top of the component's displaylist
//and will automatically be removed from its original position.
for (i=0; i<count/* - 1*/; i++)
{
if (children[i] is Octopus1 || children[i] is Octopus2)
{
// trace("child = " + children[i] + " at i: " + i);
octopusContainer.removeChild(children[i]);
octopusContainer.addChild(children[i]);
}
}
}
function removeOctopus(e:Event):void
{
var count:int = octopusContainer.numChildren;
var children:Array = [count];
//load all the children of the component into an Array
for (var i:int=0; i<count/* -1*/; i++)
{
children[i] = octopusContainer.getChildAt(i/* + 1*/);
}
for (i=0; i<count/* - 1*/; i++)
{
if (children[i] is Octopus1 || children[i] is Octopus2)
{
trace(i);
trace("Is an octopus");
if (children[i].currentFrame >= 202)
{
octopusContainer.removeChild(children[i]);
}
}
}
}
I would greatly appreciate any advice to help me overcome this hurdle and continue with my project.
Thank you in advance.
Chris Collins.
Your issue (or at least one of them) is that your code will only remove the most recent StoneSplash. So if you click a bunch of times in between the splash and end animation , only the last clicked one will get removed.
This is because you are using a global var (stoneSplash) to reference the splash, and it gets overwritten to the new one. You need to either add a splash reference on the stone itself, or create a dictionary so you know which splash goes with which stone.
Here would be one way:
if (children[i].currentFrameLabel == "Splash")
{
stoneSplash = new StoneSplash();
MovieClop(children[i]).stoneSplash = stoneSplash; //add a reference the splash on the stone itself
Then later, instead of octopusContainer.removeChild(stoneSplash); do:
octopusContainer.removeChild(MovieClop(children[i]).stoneSplash);
This way your removing the correct splash that goes with this stone.
Here would be a much cleaner way to architect this instead of using an enter frame handler:
On your Stone class timeline, put the following code on your Splash and End frames respectively:
Splash frame: this.dispatchEvent(new Event("Splash"));
End frame: this.dispatchEvent(new Event("End"));
Listen for those events when you create a new stone instance:
stone = new Stone();
stone.x = stonePositionX;
stone.y = stonePositionY;
stone.addEventListener("Splash", splashHandler,false,0,true);
stone.addEventListener("End",removeStone,false,0,true);
addChild(stone);
Respond to those events appropriately:
function splashHandler(e:Event):void {
var stone:Stone = e.currentTarget as Stone;
stoneSplash = new StoneSplash();
//you need a reference to the splash from the stone class - it would be best to create a class file and add a public property called splashObj and then just use stone.splashObj = new StoneSplash();
MovieClip(stone).stoneSplash = stoneSplash; //so on the end event we can read this var to remove stoneSplash
octopusContainer.addChild(stoneSplash);
stoneSplash.x = stone.x;
stoneSplash.y = stone.y;
}
function removeStone(e:Event):void {
var stone:Stone = e.currentTarget as Stone;
octopusContainer.removeChild(MovieClip(stone).stoneSplash);
addOctopus(stone.x, stone.y);
removeChild(stone);
}

Flip Sprite Horizontally or Render New Sprite on Right/Left Key Down?

"Hero" needs to get flipped horizontally (coordinate or new sprite, doesn't matter) on left/right keyDown. Including draw and keyDown sections. Where exactly would coordinate offset, or new sprite go, when left/right keyDown? Thanks in advance.
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "hero.png";
var owlReady = false;
var owlImage = new Image();
owlImage.onload = function () {
owlReady = true;
};
owlImage.src = "owl.png";
var hero = {
speed: 256,
x: 0,
y: 0
};
var owl = {
x: 0,
y: 0
};
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
var update = function (modifier) {
if (38 in keysDown) {
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) {
hero.y += hero.speed * modifier;
}
if (37 in keysDown) {
hero.x -=hero.speed * modifier;
}
if (39 in keysDown) {
hero.x +=hero.speed * modifier;
}
//collision
if (
hero.x <= (owl.x + 35)
&& owl.x <= (hero.x + 35)
&& hero.y <= (owl.y + 35)
&& owl.y <= (hero.y + 35)
) {
++owlsCaught;
reset();
}
};
//DRAW
var render = function () {
if (bgReady) {
context.drawImage(bgImage, 0, 0);
}
if (heroReady) {
context.drawImage(heroImage, hero.x, hero.y);
}
if (owlReady) {
context.drawImage(owlImage, owl.x, owl.y);
}
//game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
requestAnimationFrame(main);
};
//play
var then = Date.now();
reset();
main();
</script>
Just use the scale() method with negative one to flip the coordinate system. You also need to think "negative" in the sense that you move the character in negative direction with the effect of actually going in positive direction after doing this.
Example:
ctx.scale(-1, 1); // flip hor.
ctx.drawImage(img, -x - img.width, 0); // use neg. position -image width
ctx.scale(-1, 1); // flip back to normal
FIDDLE
You could of course prep the character by creating an off-screen canvas the size of the image, flip the axis, draw the image flipped and use the off-screen canvas as an image source.
Update (for the new code shown)
You could use a flag to know which direction the hero is currently facing:
var flipped = false;
if (37 in keysDown) {
hero.x -=hero.speed * modifier;
flipped = true;
}
if (39 in keysDown) {
hero.x +=hero.speed * modifier;
flipped = false;
}
Then in the render function:
if (heroReady) {
if (flipped) {
context.scale(-1, 1);
context.drawImage(heroImage, -hero.x - heroImage.width, hero.y);
context.scale(-1, 1);
}
else {
context.drawImage(heroImage, hero.x, hero.y);
}
}

How can I turn an AS2 snow effect into a AS3 snow effect?

So I manage to find a snow effect that I like and wanted to use it but I realized it was in AS2 and I need it to be in AS3. Since there isn't a small difference between AS2 and AS3 I'm here to find some in these matter.
As you can see in the fla provided I also want to control the wind and speed by buttons.
Here is a link to the AS2 snow effect: http://www.freeactionscript.com/download/realistic-snow-fall-snowflake-effect.zip
This is the code in AS2:
//settings
var speed:Number = 2;
var wind:Number = -2;
var movieWidth:Number = 550;
var movieHeight:Number = 400;
createSnow(_root, 100);
function createSnow(container:MovieClip, numberOfFlakes:Number):Void
{
//run a for loop based on numberOfFlakes
for (var i = 0; i < numberOfFlakes; i++)
{
//set temporary variable and attach snowflake to it from the library
var tempFlake:MovieClip = container.attachMovie("snow_mc", "snow"+container.getNextHighestDepth(), container.getNextHighestDepth());
//variables that will modify the falling snow
tempFlake.r = 1+Math.random()*speed;
tempFlake.k = -Math.PI+Math.random()*Math.PI;
tempFlake.rad = 0;
//giving each snowflake unique characteristics
var randomScale:Number = random(50)+50;
tempFlake._xscale = randomScale;
tempFlake._yscale = randomScale
tempFlake._alpha = random(100)+50;
tempFlake._x = random(movieWidth);
tempFlake._y = random(movieHeight);
//give the flake an onEnterFrame function to constantly update its properties
tempFlake.onEnterFrame = function()
{
//update flake position
this.rad += (this.k / 180) * Math.PI;
this._x -= Math.cos(this.rad)+wind;
this._y += speed;
//if flake out of bounds, move to other side of screen
if (this._y >= movieHeight) {
this._y = -5;
}
if (this._x >= movieWidth)
{
this._x = 1
}
if (this._x <= 0)
{
this._x = movieWidth - 1;
}
}
}
}
//buttons
//wind
left_btn.onRelease = function()
{
wind = 2;
}
none_btn.onRelease = function()
{
wind = 0;
}
right_btn.onRelease = function()
{
wind = -2;
}
//speed
slow_btn.onRelease = function()
{
speed = .5;
}
normal_btn.onRelease = function()
{
speed = 1
}
fast_btn.onRelease = function()
{
speed = 3
}
It's going to be really quite similar.
The first thing would be, instead of:
var tempFlake:MovieClip = container.attachMovie("snow_mc", "snow"+...
you want something like:
var tempFlake = new snow_mc();
container.addChild(tempFlake);
Then convert all the property names such as _x etc to their AS3 equivalents (no underscore, scaleX in place f _xscale etc), Math.random() * 50 in place of random(50).
Replace all onRelease with addEventListener(MouseEvent.CLICK, function() {})
Finally instead of tempFlake.onEnterFrame you'll need one frame loop something like:
function onFrame(event: Event): void {
foreach(var child: MovieClip in container) {
child.rad += ... etc
}
}
addEventListener(Event.ENTER_FRAME, onFrame);
These steps should be sufficient to get it working as AS3. Once it's running, you could go further to make it more AS3 by creating a SnowFlake class that encapsulates all the properties and updates for one snowflake.

How can I use a function parameter to refer to a variable?

Sorry if this question is a bit vague, but this has been driving me nuts recently. It's nothing too complicated, but all I want to do is have the variable 'targetVariable' be affected by a formula. The actual problem lies in the fact that the referenced variable, being 'masterVolume' in this case, is not getting affected by the formula, but rather 'targetVariable' instead. I run the 'makeSlider' function at the bottom of the script. Here's the code:
var masterVolume:Number = 0;
var panning:Number = 0;
function makeSlider(sliderType, X, Y, targetVariable) {
var sliderHandle:MovieClip = new sliderType();
addChild(sliderHandle);
sliderHandle.x = X;
sliderHandle.y = Y;
var dragging:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, updateSlider);
function updateSlider(e:Event):void {
panning = (mouseX/(stage.stageWidth/2))-1;
targetVariable = ((sliderHandle.x-bar.x)/bar.width);
output.text = masterVolume.toString();
if (dragging == true && mouseX >= bar.x && mouseX <= (bar.x + bar.width)) {
sliderHandle.x = mouseX;
}
}
sliderHandle.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(e:MouseEvent):void {
dragging = true;
}
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
function endDrag(e:MouseEvent):void {
dragging = false;
}
}
function playSound(target, intensity:Number, pan:Number) {
var sound:Sound = new target();
var transformer:SoundTransform = new SoundTransform(intensity, pan);
var channel:SoundChannel = new SoundChannel();
channel=sound.play();
channel.soundTransform = transformer;
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, make);
function make(e:MouseEvent):void {
playSound(test, masterVolume, panning);
}
makeSlider(SliderHandle, bar.x, bar.y, masterVolume);
Okay, so I studied the Object class and found out that I could reference the variable by making it an object in the function. Here's the updated, working script:
var panning:Number = 0;
var masterVolume:Number = 0;
function makeSlider(sliderType, barType, soundType, hitBoxScale:Number, X, Y, targetVariable) {
var reference:Object = { targetVariable: 0 };
var slider:MovieClip = new sliderType;
var newBar:MovieClip = new barType;
addChild(newBar);
newBar.x = X;
newBar.y = Y;
addChild(slider);
slider.x = X;
slider.y = Y;
var dragging:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, updateSlider);
function updateSlider(e:Event):void {
panning = (mouseX/(stage.stageWidth/2))-1;
reference.targetVariable = (slider.x-newBar.x)/newBar.width;
if (dragging == true && mouseX >= newBar.x && mouseX <= (newBar.x + newBar.width)) {
slider.x = mouseX;
}
if (reference.targetVariable <= 0.01) {
output.text = ("None");
}
if (reference.targetVariable >= 0.99) {
output.text = ("Max");
}
if (reference.targetVariable > 0.01 && reference.targetVariable < 0.99) {
output.text = (Math.round((reference.targetVariable*100))+"%").toString();
}
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(e:MouseEvent):void {
if (mouseY >= newBar.y-hitBoxScale && mouseY <= (newBar.y + newBar.height)+hitBoxScale) {
dragging = true;
}
}
slider.addEventListener(MouseEvent.MOUSE_DOWN, beginDragFromSlider);
function beginDragFromSlider(e:MouseEvent):void {
dragging = true;
}
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
function endDrag(e:MouseEvent):void {
if (dragging == true) {
playSound(soundType, reference.targetVariable, 0);
}
dragging = false;
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, make);
function make(e:MouseEvent):void {
if (dragging == false) {
playSound(test, reference.targetVariable, panning);
}
}
}
function playSound(target, intensity:Number, pan:Number) {
var sound:Sound = new target();
var transformer:SoundTransform = new SoundTransform(intensity, pan);
var channel:SoundChannel = new SoundChannel();
channel=sound.play();
channel.soundTransform = transformer;
}
makeSlider(defaultSlider, defaultBar, volumeIndicator, 10, 134, 211, masterVolume);