Here's the link to the whole project including all the dependencies if needed.
https://www.dropbox.com/sh/3d3towtkhb4c38r/AADdxDJq9ix7bK9hTkt_VTSAa?dl=0
Basically trying to clean up some script I was left to deal with and have been banging my head against the wall as to why this isn't working. I don't get any debug errors, everything seems to be linked where it needs to be linked. My font seems to be embedded, all my instance names seem to be right... the only thing I can think of is I'm missing something silly in the code. Any help would be really appreciated! Nothing like being left a mess and having to fix it.
Basically the text box is supposed to have a countdown timer based on what race is approaching (e.g Race X is in xxx minutes) and If there isn't a race approaching, it should show some default text. At the moment, It doesn't seem to want to change the dynamic text at all!
EDIT: I'll also mention the RaceRibbon Movieclip that the text is contained in is also exported for as3 to the com.RaceRibbon class.
package {
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.utils.Timer;
import com.boo.CustomDate;
import com.boo.ScreensaverSimple;
import com.RaceRibbon;
// This sections is for the image slides and Hour Of Power setting.
public class Generic extends MovieClip {
// This is where you can set the Hour of Power time start and end time (in 24 hour format e.g. 1330 for 1:30pm)
// If there is no hour of power, simply set both numbers to 0
private var HourOfPowerStartTime:Number = 0;
private var HourOfPowerEndTime:Number = 0;
private var HourOfPower1StartTime:Number = 0;
private var HourOfPower1EndTime:Number = 0;
public var race_ribbon:RaceRibbon;
private var ss:ScreensaverSimple;
public var time_check_timer:Timer;
public var is_race_time:Boolean;
public var current_state:String;
public var next_race:Date;
public var race_time_arr:Array;
public var race_num:int;
private var ss_time_arr:Array;
private var delay_add_timer:Timer;
//Set default text
private var default_ribbon_text:String = "THERACES.COM.AU";
// Set Race Times
private var r1:Date = new Date(2017,5,5,12,15);
private var r2:Date = new Date(2017,5,5,12,50);
private var r3:Date = new Date(2017,5,5,13,25);
private var r4:Date = new Date(2017,5,5,14,00);
private var r5:Date = new Date(2017,5,5,14,35);
private var r6:Date = new Date(2017,5,5,15,15);
private var r7:Date = new Date(2017,5,5,15,55);
private var r8:Date = new Date(2017,5,5,16,35);
private var r9:Date = new Date(2017,5,5,17,15);
// Hide the mouse
public function Generic() {
Mouse.hide();
// Set Race Ribbon
race_ribbon = new RaceRibbon;
race_ribbon.x = 1109;
race_ribbon.y = 983;
race_time_arr = [r1,r2,r3,r4,r5,r6,r7,r8,r9];
// Display Slideshow
ss = new ScreensaverSimple;
ss.setScreensaver(screens);
// Make sure Hour of Power is not visible
HOP1.visible = false;
HOP2.visible = false;
time_check_timer = new Timer(1000);
time_check_timer.addEventListener(TimerEvent.TIMER, checkTime);
delay_add_timer = new Timer(1,1);
delay_add_timer.addEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.start();
}
public function addAllChildren(evt:TimerEvent=null):void {
delay_add_timer.removeEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.stop();
delay_add_timer = null;
addChild(race_ribbon);
time_check_timer.start();
checkTime();
}
public function checkTime(evt:TimerEvent=null):void {
setDatesToCurrent(race_time_arr);// This makes every day race day
setDatesToCurrent(ss_time_arr);// This makes all screensaver dates current
checkNextRace();
if(next_race != null && is_race_time == false)// If it isn't race time
{
setCountdown();
}
if(next_race == null && is_race_time == true)// If it's race time
{
setDefaultText();
}
checkHOP1();
checkHOP2();
}
//Call to make Hour Of Power 1 visible/invisible based on set times
private function checkHOP1():void {
HOP1.visible = (HourOfPowerStartTime || HourOfPowerEndTime);
if (!HOP1.visible) return;
var CurrentTime:Number = CustomDate.return24HourNumber();
HOP1.visible = (CurrentTime >= HourOfPowerStartTime && CurrentTime <= HourOfPowerEndTime);
}
//Call to make Hour Of Power 2 visible/invisible based on set times
private function checkHOP2():void {
HOP2.visible = (HourOfPower1StartTime || HourOfPower1EndTime);
if (!HOP2.visible) return;
var CurrentTime:Number = CustomDate.return24HourNumber();
HOP2.visible = (CurrentTime >= HourOfPower1StartTime && CurrentTime <= HourOfPower1EndTime);
}
public function setDatesToCurrent(arr:Array):void {// This makes every day race day
var cd:Date = new Date();// Current Date
for(var i:int=0;i<arr.length;i++){
arr[i].fullYear = cd.fullYear;
arr[i].month = cd.month;
arr[i].date = cd.date;
}
}
public function checkNextRace():void {
var ct:Date = new Date();// Current Time as a Date
next_race = null;
is_race_time = false;
// FOR LOOP THIS... one day
if(ct < r1) {
next_race = r1;
} else if(raceTimeSpan(r1) == true) {
is_race_time = true;
race_num = 1;
} else if(ct > raceTimeSpan(r1) && ct < r2) {
next_race = r2;
} else if(raceTimeSpan(r2) == true) {
is_race_time = true;
race_num = 2;
} else if(ct > raceTimeSpan(r2) && ct < r3) {
next_race = r3;
} else if(raceTimeSpan(r3) == true) {
is_race_time = true;
race_num = 3;
} else if(ct > raceTimeSpan(r3) && ct < r4) {
next_race = r4;
} else if(raceTimeSpan(r4) == true) {
is_race_time = true;
race_num = 4;
} else if(ct > raceTimeSpan(r4) && ct < r5) {
next_race = r5;
} else if(raceTimeSpan(r5) == true) {
is_race_time = true;
race_num = 5;
} else if(ct > raceTimeSpan(r5) && ct < r6) {
next_race = r6;
} else if(raceTimeSpan(r6) == true) {
is_race_time = true;
race_num = 6;
} else if(ct > raceTimeSpan(r6) && ct < r7) {
next_race = r7;
} else if(raceTimeSpan(r7) == true) {
is_race_time = true;
race_num = 7;
} else if(ct > raceTimeSpan(r7) && ct < r8) {
next_race = r8;
} else if(raceTimeSpan(r8) == true) {
is_race_time = true;
race_num = 8;
} else if(ct > raceTimeSpan(r8) && ct < r9) {
next_race = r9;
} else if(raceTimeSpan(r9) == true) {
is_race_time = true;
race_num = 9;
} else if(ct > raceTimeSpan(r9)) {// If all races are finished
setDefaultText();
}
}
public function raceTimeSpan(d:Date):Boolean {
var race_mins:int = 2;
var race_on:Boolean = false;
var ct:Date = new Date();
if(ct.hours == d.hours) {
var max_mins:int = d.minutes + race_mins;
if(ct.minutes >= d.minutes && ct.minutes < max_mins) {
race_on = true;
}
}
return race_on;
}
public function setCountdown():void {
var hours_left:int = int(String(CustomDate.countdownTime(next_race)).split(":")[0]);
var mins_left:int = int(String(CustomDate.countdownTime(next_race)).split(":")[1]);
mins_left = (60*hours_left)+mins_left;
is_race_time = false;
if(mins_left > 2) {
race_ribbon.setText("NEXT RACE IN <font color='#000000' letterspacing='-1'>"+(mins_left+1)+" MINUTES</font>");
race_ribbon.setBG(0);
} else if(mins_left < 3) {
if((mins_left+1) <= 1) {
race_ribbon.setText("NEXT RACE IN <font color='#fdb913' letterspacing='-1'>"+(mins_left+1)+" MINUTE</font>");
} else {
race_ribbon.setText("NEXT RACE IN <font color='#fdb913' letterspacing='-1'>"+(mins_left+1)+" MINUTES</font>");
}
race_ribbon.setBG(1);
}
}
public function setDefaultText():void {
race_ribbon.setText("<font color='#fdb913' letterspacing='-1'>"+default_ribbon_text+"</font>");
race_ribbon.setBG(1);
}
}
}
And just in case you don't want to go through the files individually the com.RaceRibbon code is
package com {
import flash.display.MovieClip;
import fl.motion.Color;
import flash.display.Sprite;
import flash.text.*;
public class RaceRibbon extends MovieClip {
private var c1:Color;
private var c2:Color;
public function RaceRibbon() {
c1 = new Color();
c1.setTint(0xfdb913,1);
c2 = new Color();
c2.setTint(0x000000,1);
}
public function setText(str:String=""):void {
str = str.toUpperCase();
this.tb.htmlText = str;
}
public function setBG(p:int=0):void {
switch(p){
case 0:
bg.transform.colorTransform = c1;
break;
case 1:
bg.transform.colorTransform = c2;
break;
}
}
}
}
I've not had a chance to test your project files but just a suggestion on elimination :
Either manually trigger setDefaultText(); or else directly target the RaceRibbon's textField (so just comment // out the other two you aren't testing from those shown 3 lines of code).
If any Update test below work correctly to update text then your true problem lies in either :
IF statement of function setCountdown():(before if(mins_left > 2) what does trace ("minutes left: " + mins_left); say about the amount? Does it look like it could ever become > 2 or < 3 or +1 <= 1? If not, then your text will not update either.)
or function checkNextRace() (especially if you set next_race = null; then surely following that with next_race = r1; should give a debugger error like "Cannot set a value to a variable that is NULL (non-existent)" but you said you got no errors so I'm confused why mine does that. (use ctrl+shift_+enter to debug not that Test Movie option).
Anyways the code...
public function Generic() {
Mouse.hide();
// Set Race Ribbon
race_ribbon = new RaceRibbon;
race_ribbon.x = 1109; race_ribbon.y = 983;
// Update test #1
setDefaultText(); //did via Function work?
// Update test #2
race_ribbon.tb.htmlText = "testing123"; //did via Direct Targeting work?
race_ribbon.tb.htmlText = "<font color='#fdb913' letterspacing='-1'>" + "testing123" + "</font>"; //maybe works with HTML?
// Temp disable other code for above elimination tests
/*
race_time_arr = [r1,r2,r3,r4,r5,r6,r7,r8,r9];
// Display Slideshow
ss = new ScreensaverSimple; ss.setScreensaver(screens);
// Make sure Hour of Power is not visible
HOP1.visible = false; HOP2.visible = false;
time_check_timer = new Timer(1000);
time_check_timer.addEventListener(TimerEvent.TIMER, checkTime);
delay_add_timer = new Timer(1,1);
delay_add_timer.addEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.start();
*/
}
Related
I have a DPAD in my game when the player holds down let's say the Left DPAD, if he moves his touch to the Up DPAD and let's go, the player continues going in the left direction.
It also works if you hold the a direction, lets say Up continue holding but move off the Up DPAD, sometimes you may continue going in that direction.
What I've tried to prevent this:
On direction clicks, trigger checks on whether your in motion, or
already going a different direction
Setting collisions to force these variables to become false; aka,
you hit something, inMotion = false, etc
That's about all I can think of on how to fix this.
Also, I use a lot of variables for my checks, is it better to change my functions to return booleans, or is this way fine? Just curious.
Game Class
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Game extends MovieClip
{
public var area1:Boolean = true;
public var area2:Boolean = false;
public var area3:Boolean = false;
public var player1:Boolean = true;
public var player2:Boolean = false;
public var upWalkspeed:Number = -5;
public var downWalkspeed:Number = 5;
public var leftWalkspeed:Number = -5;
public var rightWalkspeed:Number = 5;
public var inMotion:Boolean = false;
public var goingUp:Boolean = false;
public var goingDown:Boolean = false;
public var goingLeft:Boolean = false;
public var goingRight:Boolean = false;
public var playerPosKeeper_mc:MovieClip = new mc_PlayerPosKeeper();
public var up_dpad:MovieClip = new dpad_Up();
public var down_dpad:MovieClip = new dpad_Down();
public var left_dpad:MovieClip = new dpad_Left();
public var right_dpad:MovieClip = new dpad_Right();
public var menu_dpad:MovieClip = new dpad_Menu();
public var run_dpad:MovieClip = new dpad_Menu();
public var barrierRoof1_game:MovieClip = new game_BarrierRoof();
public var barrierRoof2_game:MovieClip = new game_BarrierRoof();
public var barrierSide1_game:MovieClip = new game_BarrierSide();
public var barrierSide2_game:MovieClip = new game_BarrierSide();
public var StageCollisions:Array = new Array(barrierRoof1_game, barrierRoof2_game, barrierSide1_game, barrierSide2_game);
// fix MC goes after not before ||| public var player1States:Array = new Array(mc_P1D1,mc_P1D2,"mc_P1L1","mc_P1L2","mc_P1R1","mc_P1R2","mc_P1U1","mc_P1U2");
public function Game()
{
trace("SUCCESS | Constructed Game Class");
var aMove:Movement = new Movement(this);
addChild(aMove);
}
}
}
Movement Class
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.net.dns.AAAARecord;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Movement extends MovieClip
{
public function Movement(main:Game)
{
trace("SUCCESS | Constructed Movement Class");
addChild(main.playerPosKeeper_mc);
main.playerPosKeeper_mc.x = 384;
main.playerPosKeeper_mc.y = 46;
addChild(main.up_dpad);
main.up_dpad.x = 55;
main.up_dpad.y = 336;
addChild(main.down_dpad);
main.down_dpad.x = 57;
main.down_dpad.y = 432;
addChild(main.left_dpad);
main.left_dpad.x = 19;
main.left_dpad.y = 372;
addChild(main.right_dpad);
main.right_dpad.x = 118;
main.right_dpad.y = 372;
addChild(main.menu_dpad);
main.menu_dpad.x = 61;
main.menu_dpad.y = 377;
addChild(main.run_dpad);
main.run_dpad.x = 684;
main.run_dpad.y = 369;
addChild(main.barrierRoof1_game);
main.barrierRoof1_game.x = 0;
main.barrierRoof1_game.y = 0;
addChild(main.barrierRoof2_game);
main.barrierRoof2_game.x = 0;
main.barrierRoof2_game.y = 470;
addChild(main.barrierSide1_game);
main.barrierSide1_game.x = 0;
main.barrierSide1_game.y = 0;
addChild(main.barrierSide2_game);
main.barrierSide2_game.x = 790;
main.barrierSide2_game.y = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
main.up_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, upBeginInput);
main.down_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, downBeginInput);
main.left_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, leftBeginInput);
main.right_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, rightBeginInput);
// Maybe add diagnol direction buttons in the future?;
// !! NOTE !!
// Use some sort of value, maybe a return or a variable to sync up animations
// to if the player is moving, in the future
// Movement Directions
// Start of UP Movement
function upBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = true;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
main.up_dpad.addEventListener(TouchEvent.TOUCH_END, upEndInput);
addEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function upEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingUp = false;
main.up_dpad.removeEventListener(TouchEvent.TOUCH_END, upEndInput);
removeEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function sendUpMovement():void
{
if (main.inMotion == true && main.goingUp == true && main.goingDown == false && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.upWalkspeed);
}
else
{
}
}
// End of UP Movement
// Start of DOWN Movement
function downBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = true;
main.goingLeft = false;
main.goingRight = false;
main.down_dpad.addEventListener(TouchEvent.TOUCH_END, downEndInput);
addEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function downEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingDown = false;
main.down_dpad.removeEventListener(TouchEvent.TOUCH_END, downEndInput);
removeEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function sendDownMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == true && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.downWalkspeed);
}
else
{
}
}
// End of DOWN Movement
// Start of LEFT Movement
function leftBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = true;
main.goingRight = false;
main.left_dpad.addEventListener(TouchEvent.TOUCH_END, leftEndInput);
addEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function leftEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingLeft = false;
main.left_dpad.removeEventListener(TouchEvent.TOUCH_END, leftEndInput);
removeEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function sendLeftMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == true && main.goingRight == false)
{
movePlayer(main.leftWalkspeed, 0);
}
else
{
}
}
// End of LEFT Movement
// Start of RIGHT Movement
function rightBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = true;
main.right_dpad.addEventListener(TouchEvent.TOUCH_END, rightEndInput);
addEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function rightEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingRight = false;
main.right_dpad.removeEventListener(TouchEvent.TOUCH_END, rightEndInput);
removeEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function sendRightMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == false && main.goingRight == true)
{
movePlayer(main.rightWalkspeed, 0);
}
else
{
}
}
// End of RIGHT Movement
function movePlayer(movementX:Number, movementY:Number):void
{
var originalX:Number = main.playerPosKeeper_mc.x;
var originalY:Number = main.playerPosKeeper_mc.y;
main.playerPosKeeper_mc.x += movementX;
if (checkCollision())
{
main.playerPosKeeper_mc.x = originalX;
}
main.playerPosKeeper_mc.y += movementY;
if (checkCollision())
{
main.playerPosKeeper_mc.y = originalY;
}
}
function checkCollision():Boolean
{
for each (var StageCollisions:MovieClip in main.StageCollisions)
{
if (main.playerPosKeeper_mc.hitTestObject(StageCollisions))
{
return true;
main.inMotion = false;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
}
}
return false;
}
}
}
}
Before you even start to debug behaviors, you need to understand what algorithmic approach is. You have 4 similar pieces of code which differ in minor details and make your whole script too long and unreadable and hard to manage. Here's the guideline:
var isMoving:Boolean;
var Direction:Point = new Point;
var Buttons:Array = [Up, Down, Left, Right];
// Subscribe all buttons for the same handlers and behaviors.
for each (var aButton:InteractiveObject in Buttons)
{
aButton.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
aButton.addEventListener(MouseEvent.MOUSE_OUT, onUp);
aButton.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onDown(e:MouseEvent):void
{
// Figure which button was pressed.
switch (e.currentTarget)
{
case Up:
Direction.x = 0;
Direction.y = -1;
break;
case Down:
Direction.x = 0;
Direction.y = 1;
break;
case Left:
Direction.x = -1;
Direction.y = 0;
break;
case Up:
Direction.x = 1;
Direction.y = 0;
break;
}
// Now start moving Hero into the Direction.
if (!isMoving)
{
isMoving = true;
addEventListener(Event.ENTER_FRAME, onFrame);
}
}
function onFrame(e:Event):void
{
Hero.x += Direction.x;
Hero.y += Direction.y;
}
function onUp(e:MouseEvent):void
{
// If any of buttons is released or mouse out, stop moving Hero.
removeEventListener(Event.ENTER_FRAME, onFrame);
Direction.x = 0;
Direction.y = 0;
isMoving = false;
}
As you can see, the beauty of algorithmic approach is that you need to handle differently only things that need to be handled differently, in the example case (which is pretty similar to what you want to create) it is the block to set the movement direction. The rest of the code is identical for all the buttons and that's why the whole script is short and readable, easy to understand and manageable.
I can connect the device and attach a custom cursor to one finger, but I can´t use any of the gestures to over/click a button or drag a sprite around, etc.
I´m using Starling in the project. To run this sample just create a Main.as, setup it with Starling and call this class.
My basic code:
package
{
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.events.LeapEvent;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.InteractionBox;
import com.leapmotion.leap.Pointable;
import com.leapmotion.leap.ScreenTapGesture;
import com.leapmotion.leap.Vector3;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.TouchEvent;
/**
* ...
* #author miau
*/
public class LeapController extends Sprite
{
private var _controller:Controller;
private var _cursor:Shape;
private var _screenTap:ScreenTapGesture;
private var _displayWidth:uint = 800;
private var _displayHeight:uint = 600;
public function LeapController()
{
addEventListener(Event.ADDED_TO_STAGE, _startController);
}
private function _startController(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, _startController);
//adding controller
_controller = new Controller();
_controller.addEventListener( LeapEvent.LEAPMOTION_INIT, onInit );
_controller.addEventListener( LeapEvent.LEAPMOTION_CONNECTED, onConnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_DISCONNECTED, onDisconnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_EXIT, onExit );
_controller.addEventListener( LeapEvent.LEAPMOTION_FRAME, onFrame );
//add test button
_testButton.x = stage.stageWidth / 2 - _testButton.width / 2;
_testButton.y = stage.stageHeight / 2 - _testButton.height / 2;
addChild(_testButton);
_testButton.touchable = true;
_testButton.addEventListener(TouchEvent.TOUCH, doSomething);
//draw ellipse as a cursor
_cursor = new Shape();
_cursor.graphics.lineStyle(6, 0xFFE24F);
_cursor.graphics.drawEllipse(0, 0, 80, 80);
addChild(_cursor);
}
private function onFrame(e:LeapEvent):void
{
trace("ON FRAME STARTED");
var frame:Frame = e.frame;
var interactionBox:InteractionBox = frame.interactionBox;
// Get the first hand
if(frame.hands.length > 0){
var hand:Hand = frame.hands[0];
var numpointables:int = e.frame.pointables.length;
var pointablesArray:Array = new Array();
if(frame.pointables.length > 0 && frame.pointables.length < 2){
//trace("number of pointables: "+frame.pointables[0]);
for(var j:int = 0; j < frame.pointables.length; j++){
//var pointer:DisplayObject = pointablesArray[j];
if(j < numpointables){
var pointable:Pointable = frame.pointables[j];
var normal:Vector3 = pointable.tipPosition;
var normalized:Vector3 = interactionBox.normalizePoint(normal);
//pointable.isFinger = true;
_cursor.x = normalized.x * _displayWidth;
_cursor.y = _displayHeight - (normalized.y * _displayHeight);
_cursor.visible = true;
}else if (j == 0) {
_cursor.visible = false;
}
}
}
}
}
private function onExit(e:LeapEvent):void
{
trace("ON EXIT STARTED");
}
private function onDisconnect(e:LeapEvent):void
{
trace("ON DISCONNECT STARTED");
}
private function onConnect(e:LeapEvent):void
{
trace("ON CONNECT STARTED");
_controller.enableGesture( Gesture.TYPE_SWIPE );
_controller.enableGesture( Gesture.TYPE_CIRCLE );
_controller.enableGesture( Gesture.TYPE_SCREEN_TAP );
_controller.enableGesture( Gesture.TYPE_KEY_TAP );
}
private function onInit(e:LeapEvent):void
{
trace("ON INIT STARTED");
}
private function doSomething(e:TouchEvent):void
{
trace("I WAS TOUCHED!!!");
}
}
}
If a good code Samaritan can update this code to perform a screen tap gesture (or any interacion with any object), I will really appreciate this a lot.
Regards!
controller.enableGesture(Gesture.TYPE_SWIPE);
controller.enableGesture(Gesture.TYPE_SCREEN_TAP);
if(controller.config().setFloat("Gesture.Swipe.MinLength", 200.0) && controller.config().setFloat("Gesture.Swipe.MinVelocity", 500)) controller.config().save();
if(controller.config().setFloat("Gesture.ScreenTap.MinForwardVelocity", 30.0) && controller.config().setFloat("Gesture.ScreenTap.HistorySeconds", .5) && controller.config().setFloat("Gesture.ScreenTap.MinDistance", 1.0)) controller.config().save();
//etc...
Then catch it in the frame event listener:
private function onFrame( event:LeapEvent ):void
{
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
for ( var i:int = 0; i < gestures.length; i++ )
{
var gesture:Gesture = gestures[ i ];
switch ( gesture.type )
{
case Gesture.TYPE_SCREEN_TAP:
var screentap:ScreenTapGesture = ScreenTapGesture ( gesture);
trace ("ScreenTapGesture-> x: " + Math.round(screentap.position.x ) + ", y: "+ Math.round( screentap.position.y));
break;
case Gesture.TYPE_SWIPE:
var screenSwipe:SwipeGesture = SwipeGesture(gesture);
if(gesture.state == Gesture.STATE_START) {
//
}
else if(gesture.state == Gesture.STATE_STOP) {
//
trace("SwipeGesture-> direction: "+screenSwipe.direction + ", duration: " + screenSwipe.duration);
}
break;
default:
trace( "Unknown gesture type." )
}
}
}
When the event occurs, check the coordinates translated to the stage/screen and whether a hit test returns true.
EDIT: Considering I have no idea how to reliable get the touch point x/y (or better: how to translate them to the correct screen coordinates), I would probably do something like this in my onFrame event:
private function onFrame(event:LeapEvent):void {
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
var posX:Number;
var posY:Number;
var s:Shape;
if(frame.pointables.length > 0) {
var currentVector:Vector3 = screen.intersectPointable(frame.pointables[0], true); //get normalized vector
posX = 1920 * currentVector.x - stage.x; //NOTE: I hardcoded the screen res value, you can get it like var w:int = leap.locatedScreens()[0].widthPixels();
posY = 1080 * ( 1 - currentVector.y ) - stage.y; //NOTE: I hardcoded the screen res value, you can get it like var h:int = leap.locatedScreens()[0].heightPixels();
}
for(var i:int = 0; i < gestures.length; i++) {
var gesture:Gesture = gestures[i];
if(gesture.type == Gesture.TYPE_SCREEN_TAP) {
if(posX >= _button1.x &&
posX <= _button1.x + _button1.width &&
posY >= _button1.y &&
posY <= _button1.y + _button1.height) {
s = new Shape();
s.graphics.beginFill(0x00FF00);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Lisa tocada!");
}
else {
s = new Shape();
s.graphics.beginFill(0xFF0000);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Fallaste! Intentalo otra vez, tiempo: "+new Date().getTime());
}
}
}
}
I have a real problem on an ActionScript homework. I have to program a solitaire, and I'm now stuck on a bug that I don't understand.
When I launch my game object, it instanciates a CardDeck object, and fill its array with Card objects. But since my last edit, a "ArgumentError: Error #1063" is thrown every 2 seconds, and i just don't get why. I've looked and tried the few topics related to this Error, but I didn't manage to make it work ...
Here are my classes :
Card.as
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Card extends MovieClip
{
public static const COLOR_RED:int = 1;
public static const COLOR_BLACK:int = 2;
public static const SYMBOL_HEART:int = 1;
public static const SYMBOL_DIAMOND:int = 2;
public static const SYMBOL_SPADE:int = 3;
public static const SYMBOL_CLUB:int = 4;
public var game:Game;
private var t:Timer; // For click/double click fix
private var currentTarget:Card;
public var container:CardStack;
public var color:int;
public var symbol:int;
public var value:int;
public var isVisible:Boolean = false;
public function Card(type:int, value:int, g:Game)
{
game = g;
if (type == SYMBOL_HEART || type == SYMBOL_DIAMOND)
this.color = COLOR_RED;
else
this.color = COLOR_BLACK;
this.symbol = type;
this.value = value;
this.doubleClickEnabled = true;
this.addEventListener(MouseEvent.CLICK, Click);
this.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function doubleClick(e:MouseEvent):void
{
t.removeEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
if (t.running)
t.stop();
onCardDoubleClick(e);
}
private function Click(e:MouseEvent):void
{
currentTarget = (Card)(e.currentTarget);
t = new Timer(100,1);
t.addEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
t.start();
}
public function isSameColor(otherCard:Card):Boolean
{
if (this.color == otherCard.color)
return true;
else
return false;
}
public function setVisible(flipped:Boolean):void
{
if (flipped == true)
{
isVisible = true;
gotoAndStop(value);
}
else {
isVisible = false;
gotoAndStop(14);
}
game.pStage.addChild(this);
}
public function setInvisible():void
{
removeListeners();
game.pStage.removeChild(this);
}
public function removeListeners():void
{
this.removeEventListener(MouseEvent.CLICK, Click);
this.removeEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function onCardClick(e:TimerEvent):void
{
var card:Card = currentTarget;
if (this.isVisible == true) {
if (game.flagSelecting == false) {
if (!(card.container == game.deck && game.deck.isHeadCard(card) == false))
game.select.addToSelect(card);
}else{
if (card.container == game.deck)
game.deck.lastPickedCard--;
game.mvOutCard(game.select.tSelect, card.container);
}
}else {
if (((card.container.deckSize()) - 1) == (game.selCard(card, card.container)))
card.setVisible(true);
}
}
private function onCardDoubleClick(e:MouseEvent):void
{
var card:Card = (Card)(e.currentTarget);
// Acestack
if (game.aceStacks.canMoveTo(card) == true)
{
game.moveToAce(card);
}
//K sur place libre
if (card.value == 13) {
var freeStack:CardStack = (game.river.hasFreeStack());
if (freeStack != null){
game.select.addToSelect(card);
game.moveKing(game.select.tSelect, freeStack);
}
}
game.select.reinitSelection();
}
}
CardDeck.as
import Math;
import flash.events.MouseEvent;
import flash.events.Event;
public class CardDeck extends CardStack
{
// THIS IS ABOUT CARDDECK
public var lastPickedCard:int = 0;
public var isEmptyNow:Boolean = false;
// THIS IS ABOUT HANDSTACK
public var handStack:Array = new Array();
public static const X_FIRST_HANDCARD:int = 120;
public static const X_CARD_PADDING:int = 18;
public static const Y_HANDSTACK:int = 62;
public function CardDeck(g:Game)
{
trace("GAME" + g);
var a:Array = new Array();
var nGame:Game = g;
super(a,g);
trace("CONSTRUCTEUR2");
var i:int = 1;
while (i <= 52)
{
if (i < 14)
this.deck.push(new HeartCard(i,g));
else if (i >= 14 && i < 27)
this.deck.push(new DiamondCard(i - 13, g));
else if (i >= 27 && i < 40)
this.deck.push(new SpadeCard(i - 26, g));
else if (i >= 40)
this.deck.push(new ClubCard(i - 39, g));
i++;
}
trace("CONSTRUCTEUR3");
var nDeck:Array;
nDeck = new Array();
var idx:int;
while(this.deck.length > 0){
var r:int = Math.random()*(this.deck.length);
idx = (Math.floor(r));
//deck[idx].container = game.deck;
nDeck.push(deck.splice(idx, 1)[0]);
}
trace("CONSTRUCTEUR4");
this.deck = nDeck;
this.addEventListener(MouseEvent.CLICK, onDeckClick);
this.game.pStage.addChild(this);
this.x = 46;
this.y = 62;
trace("CONSTRUCTEUR5");
}
private function onDeckClick(e:MouseEvent):void
{
trace("LISTENER");
if (isEmptyNow == false)
fillHand();
else
setFilled();
}
public function setEmpty():void
{
this.alpha = .2;
this.isEmptyNow = true;
}
public function setFilled():void
{
this.alpha = 1;
this.isEmptyNow = false;
this.reinitHS();
}
// HANDSTACK
public function showHand():void
{
var i:int = 0;
while (i < (this.handStack.length)) {
trace("SHOW HAND");
handStack[i].setVisible(true);
handStack[i].y = Y_HANDSTACK;
handStack[i].x = X_FIRST_HANDCARD + (i * X_CARD_PADDING);
i++;
}
this.setDepth();
}
public function fillHand():void
{
trace("FILL");
if(lastPickedCard < (deck.length)-3)
this.handStack = this.deck.slice(deck.lastPickedCard, 3);
else {
this.handStack = this.deck.slice(game.deck.lastPickedCard);
this.setEmpty();
}
showHand();
}
public function reinitHS():void {
var i:int = 0;
while (i < (this.handStack.length)) {
handStack[i].setInvisible();
i++;
}
this.handStack = new Array();
}
public function isHeadCard(c:Card):Boolean
{
if (handStack.indexOf(c) == handStack.length -1)
return true;
else
return false;
}
}
CardStack.as
import flash.display.MovieClip;
public class CardStack extends MovieClip
{
public var deck:Array;
public var game:Game;
public function CardStack(newDeck:Array, g:Game)
{
game = g;
this.deck = newDeck;
}
public function isEmpty():Boolean {
if (this.deck.lenght == 0)
return true;
else
return false;
}
public function setDepth():void
{
var i:int = 0;
while (i < (this.deck.length))
{
if (i == 0)
this.deck[i].parent.setChildIndex(this.deck[i], 1);
else
this.deck[i].parent.setChildIndex(this.deck[i], 1 + i);
i++;
}
}
public function deckSize():int {return (this.deck.length);}
}
I call this here :
public function Game(pS:Stage)
{
pStage = pS;
select = new Selection(this);
trace("flag");
deck = new CardDeck(this);
trace("flag2");
aceStacks = new AceRiver(this);
river = new River(deck.deck, this);
}
And I get this exception :
ArgumentError: Error #1063: Argument count mismatch on CardDeck(). Expected 1, got 0
Any help would be really appreciated !
Stab in the dark; assuming that the only line that calls CardDeck() is:
deck = new CardDeck(this);
then I would ask, are you using more than one swf file in your project and loading one in at runtime? If so, try rebuilding all of your swfs that reference the CardDeck class.
I'm trying to make a simple game in Flash. So far, I've added a bunch of objects to the stage using addChild(objName);. However, now I'm trying to remove the objects completely. I don't want to have to cycle through every object's name and I'm sure there must be a more efficient way to select each object (maybe by index on the stage) and removeChildAt(index); it. However, when I try this, Flash only removes the objects that were manually placed by me on the stage. It doesn't remove the ones that were placed through code. I've done some searching and I tried multiple methods, all of which yield the same result. The one that most people agree on is this one:
while (numChildren > 0)
{
removeChildAt(0);
}
Can you help me figure out why this isn't removing anything that was coded onto the stage?
Thanks in advance :D
Edit: Here is my code for the frames:
Frame 1 (Randomly generates and displays the dots):
import flash.events.MouseEvent;
import fl.motion.easing.Linear;
var dotList = new Array(); var level:int = 3; var invisoDotList = new Array();
var loop:int;
var line:Line = new Line();
line.x = 274;
line.y = 187;
addChild(line);
for(loop = 0; loop < level; loop++)
{
var dot:Dot = new Dot();
var invisoDot:InvisoDot = new InvisoDot();
var tester:Boolean = true;
var xval:int = Math.floor(Math.random()*(1+520))+14;
var looper:int = 0;
while(looper < dotList.length)
{
if(Math.abs(xval - dotList[looper].x) > 30)//minimum spacing
{
looper++;
}
else
{
looper = 0;
xval = Math.floor(Math.random()*(1+520))+14;
}
}
dot.x = xval;
dot.y = 187;
invisoDot.x = xval;
invisoDot.y = 187;
invisoDot.alpha = 0;
dotList[loop] = dot;
invisoDotList[loop] = invisoDot;
addChild(invisoDot);
addChild(dot);
}
//trace(dotList); test to ensure that dots are added to the array
var nb1:NextButton = new NextButton();
nb1.x = 0;
nb1.y = 0;
nb1.alpha = 0;
addChild(nb1);
nb1.addEventListener(MouseEvent.CLICK, hideDots);
function hideDots(e:MouseEvent)
{
for(var loop:int = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
line.alpha = 0;
nextFrame();
}
stop();
Frame 2 (Displays further instructions and contains a couple of methods that will be used later on):
import flash.events.MouseEvent;
removeChild(nb1);
var nb2:NextButton = new NextButton();
nb2.x = 0;
nb2.y = 0;
nb2.alpha = 0;
addChild(nb2);
nb2.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent)
{
nextFrame();
}
function clearStage()
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
stop();
Frame 3 (Makes the dots disappear when they are clicked and keeps an accuracy count):
import flash.events.MouseEvent;
import flash.utils.Timer;
line.alpha = 1;
removeChild(nb2);
//setChildIndex(line,0);
var clicks:int = -1;
var passed:int = 0;
var fromLine:Boolean = false;
//trace(dotList.length);
stage.addEventListener(MouseEvent.CLICK, clickCount);
for(var loopvar:int = 0; loopvar < dotList.length; loopvar++)
{
//trace("loop");
dot = dotList[loopvar];
invisoDot = invisoDotList[loopvar];
dot.addEventListener(MouseEvent.CLICK, onClick);
invisoDot.addEventListener(MouseEvent.CLICK, onClick);
//trace("event");
}
//trace(dotList.length);
function onClick(e:MouseEvent)
{
//e.currentTarget.alpha = .5;
for(var hitcheck:int = 0; hitcheck < dotList.length; hitcheck++)
{
if(dotList[hitcheck].x == e.currentTarget.x)
{
dotList[hitcheck].alpha = 1;
}
}
//trace("check");
}
var numChanged:int = 0;
function clickCount(e:MouseEvent)
{
clicks++;
//trace(clicks);
numChanged = 0;
for(var index:int = 0; index < dotList.length; index++)//check whether the user has gotten all the dots
{
if(dotList[index].alpha == 1)
{
numChanged++;
}
}
if(numChanged == level)//if the user has gotten all the dots
{
/*trace("next screen for sucess");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
if((clicks - level) == 1)
{
passed = 2
}
else if((clicks - level) == 0)
{
passed = 1;
}
passed = 1;
fromLine = true;
nextFrame();
}
else if((clicks - numChanged) >= 2)//this ends the session as soon as 2 mistakes are made
{
/*trace("next screen for failed number of clicks");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
passed = 3;
fromLine = true;
nextFrame();
}
/*else if((clicks - level) >= 2)//if the user has made too many mistakes. This ends the session after the maximum number of tries have been used
{
trace("next screen too many clicks");
trace(clicks);
}*/
}
//trace("end");
stop();
Frame 4 (Generates the results table. A sidenote: there is a bug where "Okay" is never a result because in Frame 3, the value of passed never equals 2. Not sure why though):
import flash.text.TextFormat;
import flash.text.TextField;
var failFormat:TextFormat = new TextFormat();
failFormat.color = 0xFF0000;
failFormat.font = "Arial";
failFormat.size = 18;
var passFormat:TextFormat = new TextFormat();
passFormat.color = 0x00FF00;
passFormat.font = "Arial";
passFormat.size = 18;
var okayFormat:TextFormat = new TextFormat();
okayFormat.color = 0x808000;
okayFormat.font = "Arial";
okayFormat.size = 18;
var normalFormat:TextFormat = new TextFormat();
normalFormat.color = 0x000000;
normalFormat.font = "Arial";
normalFormat.size = 18;
var lineResults = new Array();
var squareResults = new Array();
trace(passed);
if(fromLine == true)
{
if(passed == 1)
{
lineResults[lineResults.length] = "Pass";
}
else if(passed == 2)
{
lineResults[lineResults.length] = "Okay";
}
else if(passed == 3)
{
lineResults[lineResults.length] = "Fail";
}
}
fromLine = false;
lineResults = lineResults.reverse();
squareResults = squareResults.reverse();
var loopLength:int = (lineResults.length >= squareResults.length) ? lineResults.length : squareResults.length;
var loopStart:int = 0;
if(loopLength > 11)
{
loopStart = loopLength - 12
}
var cb:CellBlock = new CellBlock();
cb.x = 283.05;
cb.y = 20.35;
addChild(cb);
var col1Head:TextField = new TextField();
col1Head.defaultTextFormat = normalFormat;
col1Head.text = "# of Dots";
col1Head.x = 114.95
col1Head.y = 8.3;
addChild(col1Head);
var col2Head:TextField = new TextField();
col2Head.defaultTextFormat = normalFormat;
col2Head.text = "Line";
col2Head.x = 259.95
col2Head.y = 8.3;
addChild(col2Head);
var col3Head:TextField = new TextField();
col3Head.defaultTextFormat = normalFormat;
col3Head.text = "Square";
col3Head.x = 381.95
col3Head.y = 8.3;
addChild(col3Head);
for(loop = loopStart; loop < loopLength; loop++)
{
var block:CellBlock = new CellBlock();
block.x = 283.05;
block.y = 20.35 + (loop - loopStart + 1)*33;
addChild(block);
var col2:TextField = new TextField();
var col3:TextField = new TextField();
var col1:TextField = new TextField();
/*col2.defaultTextFormat = passFormat;
col3.defaultTextFormat = okayFormat;*/
col1.defaultTextFormat = normalFormat;
switch(lineResults[loop])
{
case "Pass":
col2.defaultTextFormat = passFormat;
break;
case "Okay":
col2.defaultTextFormat = okayFormat;
break;
case "Fail":
col2.defaultTextFormat = failFormat;
break;
}
switch(squareResults[loop])
{
case "Pass":
col3.defaultTextFormat = passFormat;
break;
case "Okay":
col3.defaultTextFormat = okayFormat;
break;
case "Fail":
col3.defaultTextFormat = failFormat;
break;
}
//col2.text = "Pass";
col2.text = lineResults[loop];
col2.x = 260.95;
col2.y = block.y - 12;
addChild(col2);
//col3.text = "Okay";
try
{
col3.text = squareResults[loop];
}
catch(e:Error)
{
}
col3.x = 386.95;
col3.y = block.y - 12;
addChild(col3);
col1.text = String(loop + 1);
col1.x = 133.95;
col1.y = block.y - 12;
addChild(col1);
}
var nb4:NextButton = new NextButton();
nb4.x = 0;
nb4.y = 0;
nb4.alpha = 0;
addChild(nb4);
nb4.addEventListener(MouseEvent.CLICK, clearStage);
stop();
Frame 5 (Next frame which is a test to make sure that everything gets erased, which it doesn't):
removeChild(nb4);
stop();
This error:
ArgumentError: Error #1063: Argument count mismatch on Game_fla::MainTimeline/clearStage(). Expected 0, got 1. clearStage()
Occurs because your clearStage() method has been added as the click event handler of a button. If your clearStage() function is going to be used an an event handler, it needs to accept an "event" parameter. So you should define the function like this:
function clearStage(event:Event)
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
As a side note, this means that if you want to also call clearStage() manually, that is use it without adding it as an event handler, that you'll need to include this event parameter... but you can just pass in a null, because your code doesn't need to actually use the event parameter:
clearStage(null);
I'm not sure I see anything else wrong. I'd start by adding that event parameter to your clearStage() function as I shown above.
I should also add I mostly worked in Flex or pure AS3, and am not super skilled in Flash CS6 and programming on the timeline :)
From memory, I don't think Flash re-orders when you remove a child. If you remove a child at index 0, every other child is still numbered 1 to x. childAt(0) is just null now. Keep that in mind with this sort of process.
I have a memory game program and when the timer runs out, I want it to go to frame 3 where it displays the "game failed" page.
I have it all set up, except when the game runs out of time, the frame just appears to overlap the original frame, instead of going to a completely separate page.
Can anyone help me?
Here is my code:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import flash.text.TextField;
public class MemoryGame extends MovieClip{
private var firstTile:cards;
private var secondTile:cards;
private var pauseTimer:Timer;
private var score:int;
private var cardCount:int;
var seconds:Number;
var minutes:Number;
var numberDeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
public function MemoryGame(){
//TIMER FUNCTION
var levelTimer:Timer = new Timer(1000, 180);
levelTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
levelTimer.addEventListener(TimerEvent.TIMER, timerHandler);
// LEVEL FUNCTION
easyBtn.addEventListener(MouseEvent.CLICK, easyButtonClicked);
medBtn.addEventListener(MouseEvent.CLICK, medButtonClicked);
hardBtn.addEventListener(MouseEvent.CLICK, hardButtonClicked);
score = 0;
txtScore.text=""+score;
//Level button events
function easyButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("easy button clicked!");
seconds = 0;
minutes = 1;
txtTime.text = "1:00";
levelTimer.start();
setupTiles();
}
function medButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("medium button clicked!");
seconds = 30;
minutes = 0;
txtTime.text = "0:30";
levelTimer.start();
setupTiles();
}
function hardButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("hard button clicked!");
seconds = 15;
minutes = 0;
txtTime.text = "0:15";
levelTimer.start();
setupTiles();
}
//Timer handlers
function timerHandler(e:TimerEvent):void {
if (seconds > 00) {
seconds -=1;
}
else {
if (minutes > 0) {minutes -=1;seconds = 59;}
}
txtTime.text = minutes+":"+(seconds >= 10 ? seconds : "0"+seconds);
}
function timerCompleteHandler(e:TimerEvent):void {
e.target.reset();
e.target.stop();
trace("game over!");
}
//Tiles set up
function setupTiles(){
for(x=1; x<=4; x++) {
for (y=1; y<=3; y++){
var randomCard = Math.floor(Math.random()*numberDeck.length);
var tile:cards = new cards();
tile.card = numberDeck[randomCard];
numberDeck.splice(randomCard,1);
tile.gotoAndStop(9);
tile.x = (x-1) * 150;
tile.y = (y-1) * 200;
tile.addEventListener(MouseEvent.CLICK,tileClicked);
addChild(tile);
cardCount = cardCount + 1
}
}
}
}
public function tileClicked(event:MouseEvent) {
var clicked:cards = (event.currentTarget as cards);
if (firstTile == null){
firstTile = clicked;
firstTile.gotoAndStop(clicked.card);
}
else if (secondTile == null && firstTile != clicked){
secondTile = clicked;
secondTile.gotoAndStop(clicked.card);
if (firstTile.card == secondTile.card){
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
pauseTimer.start();
}
else {
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
pauseTimer.start();
}
}
if (seconds == 0){
this.gotoAndStop(2);
pauseTimer.stop();
//levelTimer.stop();
}
}
public function resetCards(event:TimerEvent) {
firstTile.gotoAndStop(9);
secondTile.gotoAndStop(9);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
score = score - 2;
txtScore.text=""+score;
}
public function removeCards(event:TimerEvent){
removeChild(firstTile);
removeChild(secondTile);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
score = score + 10;
txtScore.text=""+score;
cardCount = cardCount - 2;
trace("Cardcount: " + cardCount);
if (cardCount == 0){
this.gotoAndStop(2);
txtFinalScore.text=" "+score;
pauseTimer.stop();
}
}
}
}
Thank you so much!
When you add an object using addChild(object) it isn't associated with keyframes along the timeline.
So what you need to do is rather than jumping to frame 2, removeChild(object) or object.visible = false all children you don't want and addChild(object) your 'out of time' assets.
A good work ethic is to create destroy() functions that remove and null any unwanted assets. This way you can easily remove unwanted items and free up memory.