AS3 child issue with if statements - actionscript-3

Alright, can someone explain what is wrong with my code below, there is no errors, but it's not doing what I want it to do. I need it to display a movieclip on the screen when a variable called "randint", which is generated by random, is greater than or equal to 0.5. If it's not then it doesn't get displayed. Code:
addEventListener(Event.ENTER_FRAME, char_coll);
function char_coll(ev : Event) : void
{
if(currentFrame==2)
{
if (randint >= 0.5){
var w1:woman1 = new woman1();
randint = Math.random();
if(w1.hitTestObject(stand)){
w1.gotoAndPlay(1);
cash1 = cash1 + 1;
}
}
}
};

randint is set inside the if statement. This means that randint always is undefiend, because it has to be >= 0.5 to be set to any value (kind of a catch 22).
This code should work:
addEventListener(Event.ENTER_FRAME, char_coll);
function char_coll(ev : Event) : void
{
if(currentFrame==2)
{
var randint:Number = Math.random();
if (randint >= 0.5){
var w1:woman1 = new woman1();
stage.addChild(w1);
if(w1.hitTestObject(stand)){
w1.gotoAndPlay(1);
cash1 = cash1 + 1;
}
}
}
};
Then of course you have to add w1 to the stage using addChild() as you can se below var w1:woman1 = new woman1();
hope it helps!

Related

Removing an Object when it hits another object AS3

Beginner here. I have a symbol on the timeline with an instance name of 'island', so basically I want to remove the cells that hits the 'island'
if (cell.hitTestObject (island)) {
if(stage.contains(cell))
removeChild (cell);
}
I tried this one under the moveCell function but it only removes one cell instead of every cell that hits the island. Thanks everyone!
Here's my code so far:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Main extends MovieClip {
public var cell:Cell;
public var group:Array;
public var gameTimer:Timer;
public function Main() {
cell = new Cell (400, -15);
addChild (cell);
group = new Array();
var newCell = new Cell (100, -15);
group.push ( newCell);
addChild(newCell);
gameTimer = new Timer (25);
gameTimer.addEventListener(TimerEvent.TIMER,moveCell);
gameTimer.start();
}
public function moveCell (timerEvent:TimerEvent):void {
if (Math.random() < 0.01) {
var randomX:Number = Math.random() * 700;
var newCell:Cell = new Cell (randomX, -15);
group.push (newCell);
addChild(newCell);
}
for each(var i:MovieClip in group) {
if (i.hitTestObject(island)) {
i.visible = false;
//i.parent.removeChild(i);
var score:int = 0;
score ++;
scoreOutPut.text = score.toString();
}
}
}
}
}`
You got the "Cannot access a property or method of a null object reference" because you've removed the Cell object from the DisplayObjectContainer (its parent) but not from the group array, so in the next iteration of your for loop, that object didn't exist anymore and that error will be fired.
To avoid that you can do like this :
for(var i:int = 0; i < group.length; i++)
{
var cell:Cell = Cell(group[i]);
if (cell.hitTestObject(island))
{
cell.parent.removeChild(cell);
group.splice(i, 1);
score++;
}
}
For the score, it should be a global property for all your class to get updated every time.
Also, for your code to be more organised and clearer, it's better to put every task in a single method.
For example, for creating cells, you can use a createCell() method :
// 0 is the default value of __x and -15 is the default one of __y
private function createCell(__x:Number = 0, __y:Number = -15): void
{
var cell:Cell = new Cell(__x, __y);
group.push(cell);
addChild(cell);
}
Then you can use it in any place in your code, for example, for your two first cells that you create in the constructor :
public function Main()
{
// ..
createCell(400);
createCell(100);
// ...
}
Or inside the moveCell() method :
if (Math.random() < 0.01)
{
var randomX:Number = Math.random() * 700;
createCell(randomX);
}
Also, if you don't really need that a property or a method to be public, don't put it as public.
...
Hope that can help.

AS3: Why is a line created with .graphics appearing in two different places and when removed with parent.visible = false, only one goes?

Nobody seems to have this question already so I asked it because I've spent a few hours trying to debug this and can't find a solution;
Essentially, I have a function called draw, which is declared in my document class:
public function draw(Target: MovieClip,mX: int,mY: int,lX: int,lY: int):void {
Target.graphics.clear();
Target.graphics.lineStyle(1,0x000000,1);
Target.graphics.moveTo(mX,mY);
Target.graphics.lineTo(lX,lY);
}
I call it later to draw two lines, on two different MovieClips:
draw(Line,Line.mX,Line.mY,Mirror.x + (Mirror.width / 2),Line.lY);
draw(nextLine,(Mirror.x + (Mirror.width / 2)),200,(Mirror.x + (Mirror.width / 2)),0);
where
var Line: MovieClip = new MovieClip();
var Mirror: MovieClip = new mirror();
and Mirror is draggable, so Mirror.x changes whenever it is dragged.
Line is a line made using .graphics and Line.mX is equal to the Line.graphics.moveTo X value last time it was modified. Line.mY is the same, but for the Y coordinate. I set these values by doing this:
Line.mX = 0;
Line.mY = 200;
Line.lX = 550;
Line.lY = 200;
But with whatever values I want to draw the line, with lX and lY being equal to the X and Y coordinates of Line.graphics.lineTo. Then I draw Line using my draw function like this:
draw(Line,Line.mX,Line.mY,Line.lX,Line.lY);
Then it gets more complex because, actually, Line is just one line in an array of lines, created like this:
public var lines = [line0,line1,line2,line3,line4,line5,line6,line7,line8];
and each of those lines is created like this (with 0 being replaced by the line's number, respectively):
public var line0: MovieClip = new MovieClip();
then I give each line a number and a name, add them to the stage and hide them like this:
for each(var setupLine:MovieClip in lines) {
setupLine.num = (lines.indexOf(setupLine));
setupLine.name = ('line' + setupLine.num);
addChild(setupLine);
setupLine.visible = false;
}
Then, after making line0 visible, because I need to see it at the start, I loop through each line in a function that runs on ENTER_FRAME, and set the value of nextLine to a different value each time I run the loop like this:
for each(var Line:MovieClip in lines) {
nextLine = this['line' + (Line.num + 1)];
}
Within that loop, I then loop through a few other arrays, then check for a collision with the selected Line and another selected MovieClip from another array, which I wont go into or this question will be longer than the code for node.js.
So essentially, if the collision with the two MovieClips is present, I draw the line that I mentioned at the top of my question. But for some reason, although Line draws correctly, nextLine draws correctly, but a duplicate of it is drawn across the Y axis at 0, and stops where nextLine is on the Y axis (nextLine is vertical, so it has the same Y value at the start as at the end).
Even stranger, when I try to hide nextLine if the collision with the two MovieClips is no longer present, using this code:
nextLine.visible = false;
it only hides the version of nextLine that runs along the top of the stage, which I didn't even intend to create in the start.
EDIT
here is a link to the current source code
Here is a link to the entire project files with the original source code
copy/paste the new source code from the pastebin link to get the new version
Thanks in advance,
-Raph
I figured out how to do this, code is
package {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
[SWF(backgroundColor="0xbdc3c7")]
public class LightStage extends MovieClip {
//import classes
public var globeClass:Globe = new Globe();
public var mirrorClass:Mirror = new Mirror();
public var lineClass:Line = new Line();
//create all stage objects
public var curLine:Line
public var nextLine:Line;
public var curMirror:Mirror;
//create containers
public var mirrors:Vector.<Mirror> = new Vector.<Mirror>(); //a vector is an array, but every member has to be (or subclass) the specified class
public var globes:Vector.<Globe> = new Vector.<Globe>();
public var lines:Vector.<Line> = new Vector.<Line>();
trace('lightstage: working');
//create level object
public var curLevel:int = -1;
//create dependent variables
public var kill: Boolean = true;
//init function
public function LightStage() {
//setup MovieClips
var i:int = 0;
for (i = 0; i < 4; i++) {
mirrors.push(new Mirror());
}
for (i = 0; i < 4;i++ ) {
globes.push(new Globe());
}
var tmpLine:Line;
for (i = 0; i < 10; i++) {
tmpLine = new Line();
lines.push(tmpLine);
addChild(tmpLine);
tmpLine.visible = false;
}
//create ENTER_FRAME listener
stage.addEventListener(Event.ENTER_FRAME,enterFrame);
//start the game
levelUp();
}
//levelUp function
public function levelUp() {
curLevel++;
curLine = lines[curLevel]; //set line to the current level
curLine.curX = 0;
curLine.curY = 200;
curLine.draw(550, 200);
curLine.visible = true;
//show and position mirrors and globes
curMirror = mirrors[curLevel];
addChild(curMirror);
curMirror.x = 250;
curMirror.y = 350;
var curGlobe:Globe = globes[curLevel];
addChild(curGlobe);
curGlobe.x = 100;
curGlobe.y = 50;
//set mirror types
curMirror.gotoAndStop(2);
trace("you are now on level " + (curLevel + 1) + "!");
}
//ENTER_FRAME function
public function enterFrame(event:Event) {
//line1.visible = true;
for (var i:int = 0; i < lines.length;i++){
if (i < lines.length - 1) nextLine = lines[i + 1]; //check for out of bounds before assignment next line
if (lines[i].visible == true) {
kill = true;
for each(var mirror:Mirror in mirrors) {
if (lines[i].visible && mirror.stage && mirror.hitTestObject(lines[i])) { //for efficiency, do the hit test last in the if statement
for each(var globe:Globe in globes) {
//Looped through Mirrors and Lines and checked for collision - if collision is present, we loop through globes here
if (nextLine && nextLine.stage) {
addChild(nextLine);
}
//check for active globes
if (lines[i].visible && lines[i].hitTestObject(globe)) {
//check if the selected line touches the selected globe - if it does then we will start the timer for that globe
if (!globe.running){
globe.start();
//trace('timing');
kill = false;
}
}
else {
globe.reset();
}
switch(mirror.currentFrame) {
case 1:
break;
case 2:
//trace('live a life you will remember' + Math.random());
if(nextLine) nextLine.visible = true;
lines[i].draw(mirror.x + (mirror.width / 2),lines[i].curY);
if (nextLine) {
nextLine.curX = mirror.x + (mirror.width / 2);
nextLine.curY = 200;
nextLine.draw(mirror.x + (mirror.width / 2), 0);
}
kill = false;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
trace(mirror.currentFrame);
kill = false;
break;
}
}
}
else if (lines[i].visible && mirror.stage && lines[i].stage){
if (kill && nextLine){
nextLine.graphics.clear();
nextLine.visible = false;
}
}
}
}
}
}
}
}
//MIRROR CLASS DECLARATION
import flash.events.MouseEvent;
class Mirror extends MovieClip {
trace('mirror: working');
public function Mirror() {
this.addEventListener(MouseEvent.MOUSE_DOWN,onDown,false,0,true);
}
private function onDown(e:MouseEvent):void {
//add the mouse up listener on the stage, that way it's consistent even if the user drags so fast that the mouse leaves the bounds of the mirror
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
this.startDrag();
}
private function onUp(e:MouseEvent):void {
//we need to remove the listener from the stage now
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp, false);
this.stopDrag();
}
}
//LINE CLASS DECLARATION
import flash.display.Graphics;
class Line extends MovieClip {
trace('line: working');
public var curX:int;
public var curY:int;
public function Line():void {
}
public function draw(toX:int,toY:int):void {
graphics.clear();
graphics.lineStyle(1,0x000000,1);
graphics.moveTo(curX,curY);
graphics.lineTo(toX, toY);
curX = toX;
curY = toY;
}
}
//GLOBE CLASS DECLARATION
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
class Globe extends MovieClip {
trace('globe: working');
private var timer:Timer = new Timer(3 * 100, 5);
public function Globe():void {
timer = new Timer(300, 5);
timer.addEventListener(TimerEvent.TIMER, repeatShine, false, 0, true);
}
public function reset():void {
timer.reset();
}
public function start():void {
timer.start();
}
public function get running():Boolean { return timer.running; };
private function repeatShine(e:TimerEvent):void {
}
}

Blinking Random Number Generator ActionScript3

I need a random number generator on AS3 that blinks on a screen one random number per second (1-9). The random number is fine but I'm having a problem with the blinking part. It just stays permanent on the screen instead of blinking the number.
The dynamic textbox is called myNumbers. I've tried using myNumbers.visible = !myNumbers.visible on the event handler, but it didn't work.
My code:
var mytimer:Timer = new Timer(1000,10);
mytimer.addEventListener(TimerEvent.TIMER, timerHandler);
mytimer.start();
function timerHandler(event:TimerEvent):void{
var numbers:Number = Math.floor(Math.random() * (9 - 1 + 1) + 1);
myNumbers.text = numbers+"";
}
Any help is appreciated!
You can use the same Timer to generate a number (every second) and blinks your text field (every 0.5 second).
Take this code :
var number:int = 0;
var timer:Timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
function timerHandler(event:TimerEvent):void{
if(timer.currentCount % 2 == 0){
text_field.alpha = 0.2; // you can use text_filed.visible = false;
} else {
text_field.alpha = 1; // you can use text_filed.visible = true;
number = Math.floor(Math.random() * 9) + 1;
text_field.text = String(number); // you can also write it : number.toString();
}
}
Which will give you something like this :
Hope that can help.
Hide the myNumbers before start a timer:
myNumbers.visible = false;
In the timerHandler add:
myNumbers.visible = true;
setTimeout(hideText, 500);
Add hideText function:
function hideText()
{
myNumbers.visible = false;
}

How to run an external action script file at a specify frame?

Sorry for the vague question. The point is I would like to run an external actionscript(.as) file at a specify frame so that it won't run unless I clicked start button from the main menu. This is to make sure the game sprites won't appear on the main menu. I have tried "Export classes in frame" option but it won't work. The actionscript is already set to document class. I have no code placed on timeline.
The external actionscript code to my game:
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.media.*;
import com.greensock.*;
public class image_match extends MovieClip
{
private var first_tile:images;
private var second_tile:images;
private var pause_timer:Timer;
var imagedeck:Array = new
Array(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12);
var theFirstCardSound:FirstCardSound = new FirstCardSound();
var theMissSound:MissSound = new MissSound();
var theMatchSound:MatchSound = new MatchSound();
var playerScore:Number = 0;
public function image_match()
{
trace(this.currentFrame);
for (x = 1; x <= 6; x++)
{
for (y = 1; y <= 4; y++)
{
var random_card = Math.floor(Math.random() *
imagedeck.length);
var tile:images = new images ;
tile.col = imagedeck[random_card];
imagedeck.splice(random_card,1);
tile.gotoAndStop(13);
tile.x = 95;
tile.y = 145;
tile.x += (x - 1) * 122;
tile.y += (y - 1) * 132;
tile.addEventListener(MouseEvent.CLICK,tile_clicked);
tile.addEventListener(MouseEvent.MOUSE_OVER, glow);
tile.addEventListener(MouseEvent.MOUSE_OUT, noGlow);
tile.buttonMode = true;
addChild(tile);
}
}
}
//Function to create glow effect.
function glow(event:MouseEvent):void
{
TweenMax.to(event.currentTarget, 0.3, {glowFilter:{color:0x0000ff,
alpha:1, blurX:10, blurY:10,strength:0.7}});
}
//Function to remove glow effect.
function noGlow(event:MouseEvent):void
{
TweenMax.to(event.currentTarget, 0.5, {glowFilter:{alpha:0}});
}
public function tile_clicked(event:MouseEvent)
{
var clicked:images = event.currentTarget as images;
if ((first_tile == null))
{
first_tile = clicked;
theFirstCardSound.play();
first_tile.gotoAndStop(clicked.col);
}
else if (((second_tile == null) && first_tile != clicked))
{
second_tile = clicked;
second_tile.gotoAndStop(clicked.col);
if (first_tile.col == second_tile.col)
{
theMatchSound.play();
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
pause_timer.start();
playerScore += 200;
}
else
{
theMissSound.play();
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
pause_timer.start();
playerScore -= 20;
}
}
updateScore();
}
public function updateScore():void
{
scoreText.text = playerScore.toString();
trace("Score: " + scoreText.text);
}
public function reset_tiles(event:TimerEvent)
{
first_tile.gotoAndStop(13);
second_tile.gotoAndStop(13);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
}
public function remove_tiles(event:TimerEvent)
{
removeChild(first_tile);
removeChild(second_tile);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
}
}
}
The external code you posted is a class. That means the code in it will not run before you create an instance of it. Move the instance creation to the frame where you wish the code to be executed and you should be getting the behaviour you asked for.
If you don't know what an instance is, look for a line that contains something like:
...=new match_it();
addChild(...);
Those 2 lines create an instance of the match_it class and add it to the display hierachy. Move them to the frame in question. There might be more code that is required to be moved, but since you didn't paste the actual instantiation, that's something that I can't really tell.
I also would suggest taking a look at the basics of as3 classes, it will make your life a lot easier, here's an tutorial:
http://www.untoldentertainment.com/blog/2009/08/25/tutorial-understanding-classes-in-as3-part-1/

Fading out volume on a movieClip

I've looked around the net on this issue, and came up with the following code to fade out the volume on my movieclip:
var myTransform = new SoundTransform();
myTransform.volume = 1;
loaderClip2[indexNumber].soundTransform = myTransform;
audioTween = new TweenLite(myTransform, 2, {volume:0});
My movie clip is stored in the Array loaderClip2 at index position determined by the variable indexNumber. This code does not produce the desired fade. Can anyone see what is the problem here?
var myTransform:SoundTransform = new SoundTransform(1);
TweenLite.to(myTransform, 1, {volume:0, onUpdate:updateChannel, onUpdateParams:[indexNumber]});
function updateChannel(index:int):void {
loaderClip2[index].soundTransform = myTransform;
}
Try this code:
private function updateChannel() : void {
var st : SoundTransform = new SoundTransform(loaderClip2[indexNumber].soundTransform.volume, 0 );
loaderClip2[indexNumber].soundTransform = st;
}
TweenLite.to(loaderClip2[indexNumber], 4, { volume:.5, ease:Strong.easeInOut, onUpdate:updateChannel } );
Set your own parameters
Alright guys, after trying everything possible with tweenlite, I figured out another solution using good-old-fashioned ENTER_FRAME events. This is as straight-forward as possible, wish I had thought of it before:
so in a previous function I just do this:
myClip.addEventListener(Event.ENTER_FRAME, fadeAudio);
and then later flush out the event function (or whatever it is called):
var audioshift = 1;
function fadeAudio(e : Event) : void {
audioshift -= .05;
if (audioshift <= 0) {
audioshift = 0;
trace("fadeAudio complete");
e.target.removeEventListener(Event.ENTER_FRAME, fadeAudio);
}
var st : SoundTransform = new SoundTransform(audioshift, 0);
e.target.soundTransform = st;
}
Easy as pie.