Why are my timer and score count not working? - actionscript-3

I am trying to create a game using action script 3 and can't understand why the following code is resulting in my score immediately resetting to 0 and my timer rapidly changing numbers with no consistent pattern? Any help is much appreciated! Thank You!
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var score:int=0;
var nCount:Number = 5;
var myTimer:Timer = new Timer(3000, nCount);
timer_txt.text = nCount.toString();
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();
function countdown(e:TimerEvent):void{
nCount--;
timer_txt.text = nCount.toString();
}
init();
function init(): void {
Mouse.hide();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(MouseEvent.CLICK, checkIfHit);
}
function update(myEvent:Event):void{
aim_mc.x = this.mouseX;
aim_mc.y = this.mouseY;
score_txt.text = "Score: " + score;
}
function checkIfHit(e:MouseEvent):void{
for(var i:int = 1; i < 4;++i){
var myClip:MovieClip = MovieClip(getChildByName("duck" + i));
if (myClip.hitTestPoint(mouseX,mouseY,true)){
score = score + 1;
}
}
}

As mentioned by #coner in his comment, I think that you have another frame that, maybe, you have added by mistake, and that's why your animation is initialized everytime :
To avoid that, if you need that frame (these frames) for any reason, you can add a stop() in your first one and then you can use gotoAndStop() or gotoAndPlay() in another time to change the frame, or if you don't need that frame and you've added by mistake, you have just to remove it.
Also, don't forget to remove the event listeners and to stop your game after that your countdown is finished ...
Hope that can help.

Related

AS3 timer works in game

I have a countdown timer I made in AS3 the start, stop, and reset works fine in the game.
Problem: This Flash app is now inserted into an external virtual-life game as some animated billboard/sign. Each "person" in the game sees the sign but must click the (Flash) button, inside the sign, to start the timer code. Only the person pressing button can see it working. Everyone is given 05:00 minutes to present their offer.
I need everyone in a room to see timer countdown since its for a auction.
Any help I would appreciate it.
This is what I tried to use so far:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class timerClass extends MovieClip
{
var myTimer:Timer = new Timer(1000, 300);
var i:Number = 300;
public function timerClass()
{
//# constructor code
timerTxt.text = String("05:00");
myTimer.addEventListener(TimerEvent.TIMER, updateTime);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, TimerComplete);
startbutton.addEventListener(MouseEvent.CLICK, StartNow);
pausebutton.addEventListener(MouseEvent.CLICK, PauseNow);
restartbutton.addEventListener(MouseEvent.CLICK, restartNow);
}
private function updateTime(e:TimerEvent)
{
i--;
var totalSeconds:* = i;
var minutes:* = Math.floor(totalSeconds/60);
var seconds:* = totalSeconds % 60;
if(String(minutes).length < 2)
{
minutes = "0" + minutes;
if(String(seconds).length < 2)
seconds = "0" + seconds;
}
timerTxt.text = minutes + ":" + seconds;
}
private function TimerComplete(e:TimerEvent)
{
messageTxt.text = "PRESENTATION IS NOW OVER"
timerTxt.text = String("00:00");
}
private function StartNow(e:MouseEvent)
{ myTimer.start(); }
private function PauseNow(e:MouseEvent)
{ myTimer.stop(); }
private function restartNow(e: MouseEvent): void
{
myTimer.stop();
myTimer = new Timer(1000, 300);
myTimer.addEventListener(TimerEvent.TIMER, updateTime);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, TimerComplete);
i = 300;
messageTxt.text = "";
timerTxt.text = String("05:00");
}
} //#end Class
} //#end Package
I need everyone in a room to see timer countdown since its for a auction
This is what timer should look like, I just need eveyone to see counter at same time once i press start.
https://cldup.com/cds0PwoS5Y.swf
thank you
jln

Use button to enable timer inside a function

I'm making something in actionscript 3, and when I press the first button btnSkaffPenger, it increases the number by 1 for each click. But my second button btnTrePrinter is supposed to increase the number by 1 every 2 seconds, automatically, but only works once, and doesnt reset. (I added so you can only press the button once, I don't think that interferes with the function resetting)
Thanks
The buttons code:
btnTrePrinter.addEventListener(MouseEvent.CLICK, trePrinter);
function trePrinter(evt:MouseEvent):void
{
var timer:Timer = new Timer(2000);
var harVentet:Function = function(event:TimerEvent):void{
timer.removeEventListener(TimerEvent.TIMER, harVentet);
timer = null;
sumPenger++
txtSumPenger.text = sumPenger.toString();
}
timer.addEventListener(TimerEvent.TIMER, harVentet);
timer.start();
btnTrePrinter.mouseEnabled = false;
btnTrePrinter.alpha=0.4;
}
Full code:
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var sumPenger:int = 0;
btnSkaffPenger.addEventListener(MouseEvent.CLICK, penger1);
function penger1(evt:MouseEvent):void
{
sumPenger++
txtSumPenger.text = sumPenger.toString();
}
btnTrePrinter.addEventListener(MouseEvent.CLICK, trePrinter);
function trePrinter(evt:MouseEvent):void
{
var timer:Timer = new Timer(2000);
var harVentet:Function = function(event:TimerEvent):void{
timer.removeEventListener(TimerEvent.TIMER, harVentet);
timer = null;
sumPenger++
txtSumPenger.text = sumPenger.toString();
}
timer.addEventListener(TimerEvent.TIMER, harVentet);
timer.start();
btnTrePrinter.mouseEnabled = false;
btnTrePrinter.alpha=0.4;
}
As I was told, it's a bad practice to put the answer in comments, so I post it once again.
Just to clarify what happens in your code:
var timer:Timer = new Timer(2000);
// the timer created with 2 seconds delay and infinite repeats
var harVentet:Function = function(event:TimerEvent):void {
// 2 seconds passed after "timer.start()" call
// it's the first invocation of this listener
timer.removeEventListener(TimerEvent.TIMER, harVentet);
timer = null;
// the listener is removed and timer is destroyed
// since the listener removed from timer, no more invocations will happen
sumPenger++
txtSumPenger.text = sumPenger.toString();
}
timer.addEventListener(TimerEvent.TIMER, harVentet);
// the listener is added to timer
timer.start();
// the timer starts
Remove this code:
timer.removeEventListener(TimerEvent.TIMER, harVentet);
timer = null;
and the timer will work as you expect.

Enemy to spawn at specific locations

I am new to as3, I tried to look for an answer to my question already. For a side scrolling game I have enemies set at certain locations, and I need them to spawn, not just show up once at these specific places in the game. These are excerpts from the timeline code concerning the problem.
var enemyList:Array = new Array();
function addEnemiesToLevel1():void
{
addEnemy (700, 125);
addEnemy (1000, 125);
addEnemy(2405, 125);
addEnemy(3300, -155);
}
if (enemyList.length > 0)
{
for (var i:int = 0; i < enemyList.length; i++)
{
function addEnemy(xLocation:int, yLocation:int):void
{
var enemy:Enemy = new Enemy(xLocation, yLocation);
back.addChild(enemy);
enemy.addEventListener(Event.REMOVED, enemyRemoved);
enemyList.push(enemy);
}
The enemy is tied to a class file controlling movement towards player
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Enemy extends MovieClip {
private var xSpeedConst:int = 6;
public function Enemy(xLocation:int, yLocation:int) {
// constructor code
x = xLocation;
y = yLocation;
addEventListener(Event.ENTER_FRAME, loop);
}
public function loop(e:Event):void {
x -= xSpeedConst;
}
public function removeSelf():void {
trace("remove enemy");
removeEventListener(Event.ENTER_FRAME, loop);
this.parent.removeChild(this);
}
}
}
The enemy is also set for collisions so I don't want to change the code too much, since I might spoil something. If I have to add Timer, please tell me where exactly, because I already tried that and failed. Thank you for your help.
Although I recommend not coding in the timeline, a working example timer setup in the timeline would look like this:
var timer:Timer = new Timer(2000,0);
timer.addEventListener(TimerEvent.TIMER, createEnemy);
function createEnemy(e:TimerEvent):void{
//create a new enemy, pass the x and y you want (xPos and yPos here)
//var xPos:int, yPos:int
var enemy:Enemy = new Enemy( xPos, yPos );
back.addChild(enemy);
}
timer.start();
You could also do a similar setup in your class files if you are generating enemies there. Again, doing this in the timeline will much harder to maintain and debug.

How to add a Timer in AS3

I was wondering how to add an ingame Timer in AS3, I made a health bar for enemy mobs and once mob is attacked, health bar is visible. I need to add piece of code which if Enemy was not attacked for 5 Seconds, healthBar.visible = false; but I have no idea how to deal with time in AS3
any ideas ?
My suggestions are as follows:
Assumed MouseClick is Ninja attacked hero. If you using a this code you need to create Class or fit type. I just written skeleton code.
Download Source
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
stage.addEventListener(MouseEvent.CLICK, onAttacked);
var isAttacked:Boolean;
var timer:Timer = new Timer(100,50);
var alphaCount:Number = 1.0;
timer.addEventListener(TimerEvent.TIMER, onTick);
function onAttacked(e:MouseEvent):void
{
isAttacked = true;
timer.start();
}
function onTick(e:TimerEvent):void
{
alphaCount = 1.0 - ( 2 * timer.currentCount ) / 100;
if(!isAttacked)
{
goFadeStatusBar();
}
else
{
restoreStatusBar();
alphaCount = 1.0;
timer.reset();
timer.start();
isAttacked = false;
}
}
function goFade():void
{
bar.alpha = alphaCount;
}
function restore():void
{
bar.alpha = 1;
}

AS3 - If symbol's coordinates arrive here?

I'm using Flash Professional CS5.5 and I need to make an app where there is a ball (symbol) that moves using the accelerometer and I want that, when the ball coordinates A reach this coordinates B it goes to frame 2 (gotoAndPlay(2)). I have to find the ball coord first, right? How do I make this?
Here is the code I've now
c_ball.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void{
c_ball.startDrag();}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void{
c_ball.stopDrag();}
would it work if, after retriving the coordinates?
function f_level (e) if (c_ball.x==100 && c_ball.y==100) {
gotoAndStop(2);}
MOUSE_UP and MOUSE_DOWN are not what you need if you're looking for Accelerometer data. You want the Accelerometer class and associated events.
Try something like this:
import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;
var accel:Accelerometer = new Accelerometer();
accel.addEventListener(AccelerometerEvent.UPDATE, handleAccelUpdate);
Update handler:
function handleAccelUpdate(e:AccelerometerEvent):void{
//inside this function you now have access to acceleration x/y/z data
trace("x: " + e.accelerationX);
trace("y: " + e.accelerationY);
trace("z: " + e.accelerationZ);
//using this you can move your MC in the correct direction
c_ball.x -= (e.accelerationX * 10); //using 10 as a speed multiplier, play around with this number for different rates of speed
c_ball.y += (e.accelerationY * 10); //same idea here but note the += instead of -=
//you can now check the x/y of your c_ball mc
if(c_ball.x == 100 && c_ball.y == 100){
trace("you win!"); //fires when c_ball is at 100, 100
}
}
Now this will let you "roll" your MC off the screen so you're probably going to want to add some kind of bounds checking.
Check out this great writeup for more info:
http://www.republicofcode.com/tutorials/flash/as3accelerometer/
An easy and save way is to use colission detection, instead of testing for exectly one position ( what is hard to meet for users) you go for a target area :
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Hittester extends Sprite
{
var ball:Sprite = new Sprite();
var testarea:Sprite = new Sprite();
public function Hittester()
{
super();
ball.graphics.beginFill(0xff0000);
ball.graphics.drawCircle(0,0,10);
testarea.graphics.beginFill(0x00ff00);
testarea.graphics.drawRect(0,0,50,50);
testarea.x = 100;
testarea.y = 100;
// if testarea should be invisble
/*testarea.alpha = 0;
testarea.mouseEnabled = false;
*/
ball.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
addChild(testarea);
addChild(ball);
}
private function startDragging( E:Event = null):void{
ball.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}
private function stopDragging( E:Event = null):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
ball.stopDrag();
test();
}
private function test():void{
if( ! ball.hitTestObject(testarea) ){
ball.x = 10;
ball.y = 10;
}
else{
// here goes next frame command ;)
}
}
}
}