Set timer with random interval - actionscript-3

I have the current code:
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
How do I change the timer so that instead of triggering sendEnemy every 2 seconds, it triggers it at a random time between 1 and 3 seconds?

The Timer class possess the delay property which indicates the delay between two "timer" events. So, you just have to randomly change the delay (for the next spawn) at the beginning of sendEnemy.
function sendEnemy(evt:TimerEvent):void {
Timer(evt.currentTarget).delay = (1+Math.random()*2)*1000; // change the delay until the next call.
// continue with the usual sendEnemy code.
}

Triggering between 1 and 3 seconds, means that each second it has 33% chance to be triggered. So:
enemyShipTimer = new Timer( 1000 );
enemyShipTimer.addEventListener("timer", function( e:TimerEvent ):void
{
if( Math.random() < 0.33 )
{
trace( "triggered!" );
}
});
enemyShipTimer.start();

package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Test extends MovieClip {
private var _timer:Timer = null;
public function Test() : void {
addEventListener(Event.ADDED_TO_STAGE, _Init);
}
private function _Init(e:Event) : void {
_RandomTimer();
}
private function _RandomCount() : Number {
var min = 1000;
var max = 2000;
return Math.floor(Math.random() * max + min);
}
private function _RandomTimer() : void {
_timer = new Timer(_RandomCount(), 1);
_timer.addEventListener(TimerEvent.TIMER, _OnTimerCall);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, _OnTimerEnd);
_timer.start();
}
private function _OnTimerCall(e:TimerEvent) : void {
trace(_timer.delay);
}
private function _OnTimerEnd(e:TimerEvent) : void {
_timer.removeEventListener(TimerEvent.TIMER_COMPLETE, _OnTimerEnd);
_RandomTimer();
}
}
}

You can use the Math.random function.
You can choose the maximum value of the random function by multiplying it.
But your random would still go to zero, so you have to add it with a starting number.
var randomNumber:Number = Math.random(); // Number between 0 - 1
randomNumber *= 2000; // Number between 0 - 2000
randomNumber += 1000; // Number between 1000 - 3000
enemyShipTimer = new Timer(randomNumber);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();

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

AS3 - Space Shooter Enemy Shots

I'm very new to AS3 and programming in general and I've been developing a space shooter game in AS3 and have run into trouble regarding the enemy shots. The enemies fly vertically down from the top of the screen and should fire two shots (one going left and one going right) once their y coordinates equal that of the player. This works fine, except after anything from 30 seconds to 2 minutes, the following errors occur.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at EnemyShip2/fireWeapon()[G:\Games Related\1942\src\EnemyShip2.as:78]
at EnemyShip2/loop2()[G:\Games Related\1942\src\EnemyShip2.as:65]
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at EnemyShot/removeSelf()[G:\Games Related\1942\src\EnemyShot.as:43]
at EnemyShot/loop()[G:\Games Related\1942\src\EnemyShot.as:36]
Below is the relevant code, for the enemy ship class as well as the enemy shot class.
Enemy Ship
package
{
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.display.Stage;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* ...
* #author D Nelson
*/
[Embed(source = "../assets/enemyship2.png")]
//This enemy moves relatively slowly and fires horizontal shots
public class EnemyShip2 extends Bitmap
{
private var vy:Number = 3;
//private var ay:Number = .2;
private var target:HeroShip;
private var enemyShip2:EnemyShip2;
private var enemyfireTimer:Timer;
private var enemycanFire:Boolean = true;
public function EnemyShip2(target:HeroShip):void
{
this.target = target;
scaleX = 0.3;
scaleY = 0.3;
x = Math.floor(Math.random() * 550);
y = -105;
addEventListener(Event.ENTER_FRAME, loop2, false, 0, true);
enemyfireTimer = new Timer(1000, 1);
enemyfireTimer.addEventListener(TimerEvent.TIMER, handleenemyfireTimer, false, 0, true);
}
private function handleenemyfireTimer(e:TimerEvent) : void
{
//the timer runs, so a shot can be fired again
enemycanFire = true;
}
private function removeSelf2():void
{
removeEventListener(Event.ENTER_FRAME, loop2);
if (stage.contains(this))
{
stage.removeChild(this);
}
}
private function loop2 (e:Event):void
{
//vy += ay;
y += vy;
if (y > stage.stageHeight)
{
removeSelf2();
}
if (y >= target.y && (enemycanFire))
{
fireWeapon();
enemycanFire = false;
enemyfireTimer.start();
}
if (this.x > 540 || this.x < 10)
{
removeSelf2();
}
}
private function fireWeapon():void
{
stage.addChild(new EnemyShot(target, x, y, -4));
stage.addChild(new EnemyShot(target, x, y, +4));
}
}
}
Enemy Shot
package
{
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
import flash.display.Stage;
/**
* ...
* #author D Nelson
*/
[Embed(source="../assets/enemyshot.png")]
public class EnemyShot extends Bitmap
{
private var speed:Number;
private var target:HeroShip;
private var vx:Number;
public function EnemyShot(target:HeroShip, x:Number, y:Number, vx:Number)
{
this.target = target;
this.x = x;
this.y = y;
this.vx = vx;
scaleX = 0.3;
scaleY = 0.3;
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event) : void
{
x += vx;
if (x >= 600 || x <= -50)
{
removeSelf();
}
}
private function removeSelf():void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stage.contains(this))
{
stage.removeChild(this);
}
}
}
}
Also provided is the main class, in case that is of any help.
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.*;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.utils.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.text.*;
import flash.media.Sound;
import flash.media.SoundChannel;
/**
* ...
* #author D Nelson
*/
public class Main extends MovieClip
{
[Embed(source = "snd/gamemusic2.mp3")]
private var MySound : Class;
private var mainsound : Sound;
private var shootsound: Sound = new ShootSound;
private var sndChannel:SoundChannel = new SoundChannel;
public var heroShip:HeroShip;
public var enemyShip1:EnemyShip1
public var enemyShip2:EnemyShip2
public var enemyShip3:EnemyShip3
public var enemyShip4:EnemyShip4
public var bossShip: BossShip
public var enemyShot: EnemyShot;
public var playerShot: PlayerShot;
private var background1:Background1;
private var background2:Background2;
public static const scrollspeed:Number = 2;
public var playerShotArray:Array = new Array()
public var enemyShotArray:Array = new Array()
public var enemies1Array:Array = new Array()
public var enemies2Array:Array = new Array()
private var fireTimer:Timer; //this creates a delay between each shot
private var canFire:Boolean = true; //this checks if a shot can be fired
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
mainsound = (new MySound) as Sound;
shootsound = (new ShootSound) as Sound;
mainsound.play();
background1 = new Background1();
background2 = new Background2();
//setting the backgrounds one below another
background1.y = 0;
background2.y = background1.height;
//add background at the lowest depth level
stage.addChildAt(background1,0);
stage.addChildAt(background2, 0);
//sets up the timer and its listener
fireTimer = new Timer(250, 1);
fireTimer.addEventListener(TimerEvent.TIMER, handlefireTimer, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleCharacterShoot);
//background scrolling effect
stage.addEventListener(Event.ENTER_FRAME, backgroundScroll);
//loop for enemy1 variety
stage.addEventListener(Event.ENTER_FRAME, loop1, false, 0, true);
//loop for enemy2 variety
stage.addEventListener(Event.ENTER_FRAME, loop2, false, 0, true);
//speed of player shots
setInterval(playerShootMovement, 10);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//entry point
heroShip = new HeroShip();
stage.addChild(heroShip);
//test values for enemies
/*enemyShip1 = new EnemyShip1();
stage.addChildAt(enemyShip1, 2);
enemyShip1.y = stage.stageWidth * 0.3;
enemyShip1.x = 300;
enemyShip2 = new EnemyShip2();
stage.addChildAt(enemyShip2, 2);
enemyShip2.y = stage.stageWidth * 0.3;
enemyShip2.x = 200;
enemyShip3 = new EnemyShip3();
stage.addChildAt(enemyShip3, 2);
enemyShip3.y = stage.stageWidth * 0.3;
enemyShip3.x = 100;
enemyShip4 = new EnemyShip4();
stage.addChildAt(enemyShip4, 2);
enemyShip4.y = stage.stageWidth * 0.3;
enemyShip4.x = 400;
bossShip = new BossShip();
stage.addChildAt(bossShip, 1);
bossShip.y = 10;
bossShip.x = 130;*/
Mouse.hide();
}
private function handlefireTimer(e:TimerEvent) : void
{
//the timer runs, so a shot can be fired again
canFire = true;
}
public function playerShoot():void
{
//if canFire is true, allow a shot to be fired, then set canFire to false and start the timer again
//else, do nothing
if (canFire)
{
//Add new line to the array
playerShotArray.push(playerShot = new PlayerShot);
//Spawn missile in ship
playerShot.y = heroShip.y;
playerShot.x = heroShip.x+11;
addChild(playerShot);
canFire = false;
fireTimer.start();
sndChannel = shootsound.play();
}
}
public function playerShootMovement():void
{
//code adapted from the Pie Throw tutorial
for (var i:int = 0; i < playerShotArray.length; i++)
{
playerShotArray[i].y -= 10;
if (playerShotArray[i].y == 850)
{
playerShotArray.shift();
}
}
}
public function handleCharacterShoot(e:KeyboardEvent):void
{
/**
* SpaceBar = 32
*/
if (e.keyCode == 32)
{
playerShoot();
}
}
public function backgroundScroll (evt:Event):void
{
background1.y += scrollspeed;
background2.y += scrollspeed;
if (background1.y >= stage.stageHeight)
{
//the background is below the visible stage area, put it above the other background
background1.y = background2.y - background2.height;
}
else if (background2.y >= stage.stageHeight)
{
background2.y = background1.y - background2.height;
}
}
//EnemyShip 1 spawning
private function loop1(e:Event):void
{
//generates probability for the ship to spawn (lower number to increase odds, decrease it to decrease odds)
if (Math.floor(Math.random() * 55) == 5)
{
var enemyShip1:EnemyShip1 = new EnemyShip1(heroShip);
enemyShip1.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy1, false, 0, true);
enemies1Array.push(enemyShip1);
stage.addChild(enemyShip1);
}
}
private function removeEnemy1(e:Event):void
{
//removes the enemy that most recently left the screen from the array
enemies1Array.splice(enemies1Array.indexOf(e.currentTarget), 1);
}
//EnemyShip2 spawning
private function loop2(e:Event):void
{
if (Math.floor(Math.random() * 40) == 5)
{
var enemyShip2:EnemyShip2 = new EnemyShip2(heroShip);
enemyShip2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy2, false, 0, true);
enemies2Array.push(enemyShip2);
stage.addChild(enemyShip2);
}
}
private function removeEnemy2(e:Event):void
{
enemies2Array.splice(enemies2Array.indexOf(e.currentTarget), 1);
}
}
}
Initially I thought it was to do with enemies firing shots while being too far to either side of the screen, but that doesn't seem to be the case. Any help would be greatly appreciated.
You need to make sure you remove the ENTER_FRAME listeners whenever you remove the object.
Actually, my advise is to not add ENTER_FRAME handlers throughout your game objects. This gets hard to manage and leads to bugs like you've encountered. Instead, add a single ENTER_FRAME as your core game loop, and update objects by calling an update() function on a list of game objects you maintain in your main game class. When you remove an object you simply won't call update() anymore. It also becomes easy to pause the game by just removing the ENTER_FRAME handler.
For example, here's a pattern I like to use for simple games:
interface IGameObject {
update():void;
}
class Enemy extends Sprite implements IGameObject {
public update():void {
// move, fire, etc
}
}
class Player extends Sprite implements IGameObject {
public update():void {
// move, fire, etc
}
}
class Bullet extends Bitmap implements IGameObject {
public update():void {
// move, collide, etc
}
}
class Main extends Sprite {
private objects:Vector.<IGameObject> = new <IGameObject>[];
public start():void {
addEventListener(Event.ENTER_FRAME, update);
}
public stopGame():void {
removeEventListener(Event.ENTER_FRAME, update);
}
private function update(e:Event):void {
for each (var object:IGameObject in objects) {
object.update();
}
}
public addObject(object:IGameObject):void {
objects.push(object);
addChild(object as DisplayObject);
}
public removeObject(object:IGameObject):void {
objects.splice(objects.indexOf(object), 1);
removeChild(object as DisplayObject);
}
}
Add and remove objects using addObject and removeObject. You can invoke them through a reference to Main or through event handlers you dispatch from your objects.

how to change boolean values with timerEvent in as3

I had written this small code to change a boolean value for 0 to 1 and vice versa every second
but it doesnt work.
The result is it always stays as 0. I must be making some stupid mistake. Please help. Thanks
var booleanL:Number = 0;
var myTimerL:Timer = new Timer(1000,60);
myTimerL.addEventListener(TimerEvent.TIMER, timerListenerL);
function timerListenerL (e:TimerEvent):void{
if(booleanL == 0) {
booleanL = 1;
} else if(booleanL == 1) {
booleanL = 0;
}
}
myTimerL.start();
trace(booleanL);
EDIT:
You can try using the computer clock time to make a stopwatch. The boolean will update every time the clock's end_time time is [delay] seconds higher than start_time. Delay is set by this line: delay = start_time.seconds + 2; here gives +2 seconds delay as limit before update
Try it like this...
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
import flash.events.Event; //added this for enter frame events
public class timer extends MovieClip
{
public var booleanL:int = 0;
public var start_time:Date = new Date;
public var end_time:Date = new Date;
public var delay:int;
public function timer()
{
//var myTimerL:Timer = new Timer(1000, 5);
//myTimerL.addEventListener(TimerEvent.TIMER, timerListenerL);
//myTimerL.start();
timer_Reset();
}
function timerListenerL ():void //(event:TimerEvent):void
{
trace("Am updating Boolean...");
if( 1 == booleanL)
{ booleanL = 0; trace(booleanL); }
else if (0 == booleanL)
{ booleanL = 1; trace(booleanL);}
}
//USE REAL TIME CLOCK VERSION
public function timer_Reset():void
{
start_time = new Date; //reset time to now..
delay = start_time.seconds + 2; //two seconds test delay
stage.addEventListener(Event.ENTER_FRAME, _update);
}
function _update (e:Event):void
{
//set end_time to now-time every frame,
//then check if end seconds are [+ delay] higher than start_time.seconds
end_time = new Date(); //set to Now time
if (end_time.seconds == delay)
{
trace(end_time.hours + ":" + end_time.minutes + ":" + end_time.seconds);
stage.removeEventListener(Event.ENTER_FRAME, _update);
timerListenerL (); //we update boolean via this function
timer_Reset(); //we reset for next check via this function
}
}
}

Line 108 1136: Incorrect number of arguments. Expected 1

I cant fix this error and when I do it causes another one. I want to be able to hit key "71" and have a new instance of the movieclip added to the stage. any suggestions? Im a novice so probably alot of mistakes...
package {
import flash.display.MovieClip; //imports needed
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.engine.EastAsianJustifier;
import flash.events.KeyboardEvent;
import flash.display.Stage;
public class myJellyFish extends MovieClip {
private var startScaleX:Number;
private var startScaleY:Number;
//private var cliqued:Number;
private var stayonscreenLeft:Number;
private var stayonscreenRight:Number;
private var stayonscreenTop:Number;
private var stayonscreenBottom:Number;
private var moveDirection:Number;
private var speed:Number;
private var turnspeed:Number;
public function myJellyFish() {
startScaleX = this.scaleX;
startScaleY = this.scaleY;
stayonscreenBottom = 400;
stayonscreenRight = 500;
stayonscreenLeft = 5;
stayonscreenTop = 5;
moveDirection = .5;
speed = Math.random()*10;
turnspeed = 25;
this.addEventListener(MouseEvent.ROLL_OVER, scrolledOver);
this.addEventListener(MouseEvent.ROLL_OUT, scrolledOff);
this.addEventListener(MouseEvent.CLICK, directionChange);
this.addEventListener(Event.ENTER_FRAME, life)
trace("custom class be a working");
// constructor code
}
function myMethod () {
trace("method also be a workin'");
}
private function scrolledOver(Event:MouseEvent):void{
this.alpha = .5;
}
private function scrolledOff(Event:MouseEvent):void{
this.alpha = 1;
}
private function directionChange(e:Event):void{
moveDirection = moveDirection * -1;
}
private function life(e:Event):void{
if (moveDirection > 0){
Hmovement();
}
if (moveDirection < 0){
Vmovement();
}
}
private function Vmovement():void{
this.y += speed;
if(this.y <= stayonscreenBottom){
speed = speed * -1;
this.startScaleY * -1;
}
if(this.y >= stayonscreenTop){
speed = speed * -1;
this.startScaleY * -1;
}
}
private function Hmovement():void{
this.x += speed;
if(this.x >= stayonscreenRight){
speed = speed * -1;
}
if(this.x <= stayonscreenLeft){
speed = speed * -1;
}
}
private function generate(e:KeyboardEvent):void{
var movieClip:myJellyFish = new myJellyFish();
addChild(movieClip);
movieClip.x = (Math.random() * 200) + 20;
movieClip.y = (Math.random()*200) + 20;
movieClip.name = "jellyfish";
}
public function moreClips (event:KeyboardEvent){ //if that key is "F" it will play the tween
trace(event.keyCode);
if (event.keyCode == 71){
generate();
}
}
}//end class
}//end package
First of all, as Rin said, there will be an argument error when calling the generate function.
Secondly, you need to add a KeyboardEvent (ref) listener in order to receive the keyboard events.
The easiest way to listen to keyboard events is to add the listener to the Stage (because the KeyboardEvents will bubble to the Stage no matter where they were triggered.) In order to get a reference to the Stage, you need to wait until your MovieClip has been added to the DisplayList (when your instance of myJellyFish has been added as a child somewhere).
You do this by listening for the Event.ADDED_TO_STAGE event.
// Your constructor
public function myJellyFish() {
// ...
// Add event listener which will trigger when
// the MovieClip has been added to the DisplayList
this.addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
}
protected function handleAddedToStage(e:Event):void {
// Remove event listener since it's no longer needed
this.removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
// You now have a reference to the stage, let's add the KeyboardEvent listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, moreClips);
}
Edit: fixed typo in removeEventListener.
Your generate function has 1 argument wich is e:KeyboardEvent, since you have function moreClips which alredy has the KeyboardEvent, you don't need the argument for the generate function.
Basicly what you are doing now is calling the generate() function without the argument. All you should do is remove the argument from the function.
private function generate():void{
var movieClip:myJellyFish = new myJellyFish();
addChild(movieClip);
movieClip.x = (Math.random() * 200) + 20;
movieClip.y = (Math.random()*200) + 20;
movieClip.name = "jellyfish";
}

need some correction in Typewriter effect in flash.

I'm using the typewriting effect in that I need to reduce the speed of word printing. I don't know how to reduce the speed of content printing.
This is the code
var format : TextFormat = new TextFormat();
format.size = 14;
format.font = "Arial";
format.bold = true;
format.color = 0x00000;
var _textField : TextField = new TextField();
_textField.width = 400;
_textField.height = 200;
_textField.selectable = false;
_textField.wordWrap = true;
_textField.defaultTextFormat = format;
_textField.x = _textField.y =10;
addChild(_textField);
var _textLoader:URLLoader = new URLLoader(new URLRequest("text.txt"));
_textLoader.addEventListener(Event.COMPLETE, Init, false, 0, true);
function Init(e:Event):void
{
var _text = e.target.data;
_letters = _text.split('');
addEventListener(Event.ENTER_FRAME, Write, false, 0, true);
}
function Write(e:Event):void
{
if (_counter < _letters.length)
{
_textField.appendText(_letters[_counter]);
_counter++;
}
}
Well, since you're using an EnterFrame event you could just reduce the FPS of the SWF, but that probably is not what you want as it would reduce the speed of everything in the SWF not just the textfield printing.
Alternatively you can just maintain some counter variable to keep track of frames and only appendText every 10 frames or so. For example:
var currFrame:int = 0;
//...
function Write(e:Event):void
{
currFrame++;//increase the counter
if(currFrame > 10)
{//only write a letter every 10 frames
currFrame = 0;//reset the counter
if (_counter < _letters.length)
{
_textField.appendText(_letters[_counter]);
_counter++;
}
}
}
Adjust that '10' to change the speed (larger numbers = slower)
First of all, I don't see the variable _counter declared anywhere in the code.
That said, they are a few ways to make it go slower, this is one of the possibilities.
If the "_counter" var is smaller than the length of the string => add a letter.
So to make this go slower you can say:
If the "_counter" var is smaller than the length of the string => wait 2seconds and then add a letter.
You can do this, for example, with the setInterval function:
www.ilike2flash.com/2009/07/time-delay-in-actionscript-3.html
so your code will look something similar to this:
var _prevCounter = "";
function Write(e:Event):void
{
if (_counter < _letters.length && _counter != _prevCounter)
{
setInterval(addLetter, 3000);
_counter++;
}
}
function addLetter()
{
_textField.appendText(_letters[_counter]);
}
This was not tested and could cause some errors, never copy/paste if you don't understand what you are copy/pasting!
Good luck & hope this helps you on your way!
Just use the Timer event instead of the ENTER_FRAME event. You can define the "speed of word printing" as the timer delay.
const DELAY_BETWEEN_LETTERS:int = 100; // here you are setting 100 ms between each letter output
var timer:Timer = new Timer(DELAY_BETWEEN_LETTERS);
function Init(e:Event):void
{
var _text = e.target.data;
_letters = _text.split('');
timer.addEventListener(TimerEvent.TIMER, Write);
timer.start();
}
function Write(e:TimerEvent):void
{
if (_counter < _letters.length)
{
_textField.appendText(_letters[_counter]);
_counter++;
}
}
You could also use timers like in the following example:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TextEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var textField:TypewriterTextField = new TypewriterTextField();
textField.autoSize = TextFieldAutoSize.LEFT;
textField.border = true;
addChild(textField);
}// end function
}// end class
}// end package
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;
class TypewriterTextField extends TextField {
public function TypewriterTextField() {
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}// end function
private function onAddedToStage(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}// end function
private function onKeyUp(e:KeyboardEvent):void {
e.preventDefault();
if (stage.focus == this) {
var char:String = String.fromCharCode(e.charCode);
if (char.match(/[a-zA-Z0-9\s\n]/) || e.charCode == 8) {
var timer:CustomTimer = new CustomTimer(e.charCode, 500, 1);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
}// end if
}// end if
}// end function
private function onTimer(e:TimerEvent):void {
var customTimer:CustomTimer = e.target as CustomTimer;
customTimer.removeEventListener(TimerEvent.TIMER, onTimer);
var charCode:uint = customTimer.object as uint;
var char:String = String.fromCharCode(charCode);
if (char.match(/[a-zA-Z0-9\s\n]/)) {
this.text += char;
}
else {
this.text = this.text.slice(0, -1);
}// end else if
}// end function
}// ende class
class CustomTimer extends Timer {
private var _cbject:Object;
public function get object():Object {
return this._cbject;
}// end function
public function CustomTimer(object:Object, delay:Number, repeatCount:int = 0) {
super(delay, repeatCount);
_cbject = object;
}// end function
}// end class