Flow Field Actionscript: How to change triangles (boids) appearance to png image? - actionscript-3

I was wondering if there was a way to change the appearance of the "particles" to an image that I've created. I found the lab at Lab: Simulating Flocking Behavior with Perlin Noise.
I've been trying to figure out how can I upload birds that I've created into the sketch.
Would anyone care to help me figure out if it's even possible?
/**
*
* FlowField v1.00
* 14/12/2008 17:53
*
* © JUSTIN WINDLE | soulwire ltd
* http://blog.soulwire.co.uk
*
**/
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Point;
import flash.utils.getTimer;
public class FlowField extends Sprite
{
//___________________________________________________________ _____
//————————————————————————————————————————————— CLASS MEMBERS VALUE
private static const MARGIN: int = 10;
private static const UI_Y_OPEN: int = 200;
private static const UI_Y_CLOSED: int = 314;
private static const FADING: ColorTransform = new ColorTransform(1, 1, 1, 0.99);
//———————————————————————————————————————————————————————————
private var _offsets: Array = [];
private var _offsetSpeed1: Number = 2.0;
private var _offsetSpeed2: Number = -2.0;
private var _speedMultiplier: Number = 2.0;
private var _numParticles: int = 1000;
private var _noiseSeed: int = 1000;
private var _baseX: int = 180;
private var _baseY: int = 180;
private var _settingsOpen: Boolean = false;
private var _useBlitting: Boolean = false;
private var _renderBMD: BitmapData;
private var _noiseBMD: BitmapData;
private var _renderBMP: Bitmap;
private var _noiseBMP: Bitmap;
private var _particles: Sprite;
//___________________________________________________________
//————————————————————————————————————————— GETTERS + SETTERS
public function set numParticles( value:int ):void
{
_numParticles = value;
ui.particlesTF.text = value.toString();
if ( _numParticles > _particles.numChildren )
{
var particle:Particle;
while ( _particles.numChildren < _numParticles )
{
particle = new Particle();
particle.x = Math.random() * stage.stageWidth;
particle.y = Math.random() * stage.stageHeight;
_particles.addChild( particle );
}
}
else if ( _numParticles < _particles.numChildren )
{
while ( _particles.numChildren > _numParticles )
{
_particles.removeChildAt( _numParticles );
}
}
}
public function set noiseSeed( value:int ):void
{
_noiseSeed = value;
ui.seedTF.text = value.toString();
}
public function set baseX( value:int ):void
{
_baseX = value;
ui.baseXTF.text = value.toString();
}
public function set baseY( value:int ):void
{
_baseY = value;
ui.baseYTF.text = value.toString();
}
public function set offsetSpeed1( value:Number ):void
{
_offsetSpeed1 = value;
ui.offset1TF.text = value.toString();
}
public function set offsetSpeed2( value:Number ):void
{
_offsetSpeed2 = value;
ui.offset2TF.text = value.toString();
}
public function set speedMultiplier( value:Number ):void
{
_speedMultiplier = value;
ui.pSpeedTF.text = value.toString();
}
public function set useBlitting( value:Boolean ):void
{
_useBlitting = value;
if ( _useBlitting )
{
Particle.COLOUR = 0xFFFFFF;
removeChild( _particles );
addChild( _renderBMP );
}
else
{
Particle.COLOUR = 0x111111;
removeChild( _renderBMP );
addChild( _particles );
}
for (var i:int = 0; i < _numParticles; i++)
{
Particle( _particles.getChildAt(i) ).draw();
}
addChild( _noiseBMP );
addChild( ui );
}
//___________________________________________________________
//——————————————————————————————————————————————— CONSTRUCTOR
public function FlowField()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.MEDIUM;
stage.align = StageAlign.TOP_LEFT;
_offsets.push( new Point() );
_offsets.push( new Point() );
_noiseSeed = Math.random() * 2000 << 0;
_renderBMD = new BitmapData( stage.stageWidth, stage.stageHeight, false, 0 );
_renderBMP = new Bitmap( _renderBMD );
addChild( _renderBMP );
_noiseBMD = new BitmapData( stage.stageWidth, stage.stageHeight );
_noiseBMD = new BitmapData( stage.stageWidth + (MARGIN * 4), stage.stageHeight + (MARGIN * 4), false );
_noiseBMP = new Bitmap( _noiseBMD );
_noiseBMP.visible = false;
addChild( _noiseBMP );
createParticles();
configureListeners();
useBlitting = false;
}
//___________________________________________________________
//——————————————————————————————————————————————————— METHODS
//———————————————————————————————————————————————————————————
private function createParticles():void
{
_particles = new Sprite();
addChild( _particles );
addChild( ui );
for (var i:int = 0; i < _numParticles; i++)
{
var particle:Particle = new Particle();
particle.x = Math.random() * stage.stageWidth;
particle.y = Math.random() * stage.stageHeight;
_particles.addChild( particle );
}
}
private function configureListeners():void
{
ui.particlesSlider.addEventListener( Event.CHANGE, onSliderChange );
ui.seedSlider.addEventListener( Event.CHANGE, onSliderChange );
ui.baseXSlider.addEventListener( Event.CHANGE, onSliderChange );
ui.baseYSlider.addEventListener( Event.CHANGE, onSliderChange );
ui.offset1Slider.addEventListener( Event.CHANGE, onSliderChange );
ui.offset2Slider.addEventListener( Event.CHANGE, onSliderChange );
ui.pSpeedSlider.addEventListener( Event.CHANGE, onSliderChange );
ui.showNoiseCB.addEventListener( Event.CHANGE, onCBSelect );
ui.blitCB.addEventListener( Event.CHANGE, onCBSelect );
ui.particlesSlider.value = _numParticles;
ui.particlesTF.text = _numParticles.toString();
ui.seedSlider.value = _noiseSeed;
ui.seedTF.text = _noiseSeed.toString();
ui.baseXSlider.value = _baseX;
ui.baseXTF.text = _baseX.toString();
ui.baseYSlider.value = _baseY;
ui.baseYTF.text = _baseX;
ui.offset1Slider.value = _offsetSpeed1;
ui.offset1TF.text = _offsetSpeed1.toString();
ui.offset2Slider.value = _offsetSpeed2;
ui.offset2TF.text = _offsetSpeed2.toString();
ui.pSpeedSlider.value = _speedMultiplier;
ui.pSpeedTF.text = _speedMultiplier.toString();
addEventListener( Event.ENTER_FRAME, update );
}
//___________________________________________________________
//———————————————————————————————————————————— EVENT HANDLERS
private function update( event:Event ):void
{
_offsets[0].x += _offsetSpeed1;
_offsets[0].y += _offsetSpeed1;
_offsets[1].x += _offsetSpeed2;
_offsets[1].y += _offsetSpeed2;
_noiseBMD.perlinNoise( _baseX, _baseY, 2, _noiseSeed, false, true, 10, true, _offsets );
var particle:Particle;
var brightness:Number;
var radians:Number;
var angle:Number;
var speed:Number;
var pixel:int;
for (var i:int = 0; i < _particles.numChildren; i++)
{
particle = _particles.getChildAt(i) as Particle;
pixel = _noiseBMD.getPixel( particle.x + (MARGIN *2), particle.y + (MARGIN *2) );
brightness = pixel / 0xFFFFFF;
speed = 0.1 + brightness * particle.speed * _speedMultiplier;
angle = 360 * brightness * particle.wander;
radians = angle * Math.PI / 180;
particle.x += Math.cos( radians ) * speed;
particle.y += Math.sin( radians ) * speed;
particle.scaleX = particle.scaleY = 0.1 + brightness * (_useBlitting ? 4 : 6);
particle.rotation = angle;
if ( particle.x < -MARGIN ) particle.x = stage.stageWidth + MARGIN;
else if ( particle.x > stage.stageWidth + MARGIN ) particle.x = -MARGIN;
if ( particle.y < -MARGIN ) particle.y = stage.stageHeight + MARGIN;
else if ( particle.y > stage.stageHeight + MARGIN ) particle.y = -MARGIN;
}
if ( _useBlitting )
{
_renderBMD.colorTransform( _renderBMD.rect, FADING );
_renderBMD.draw( _particles );
}
if ( !_settingsOpen && mouseY > UI_Y_CLOSED )
{
_settingsOpen = true;
}
else if ( _settingsOpen && mouseY < UI_Y_OPEN )
{
_settingsOpen = false;
}
if ( _settingsOpen && ui.y > UI_Y_OPEN )
{
ui.y += (UI_Y_OPEN - ui.y) / 3;
}
else if ( !_settingsOpen && ui.y < UI_Y_CLOSED )
{
ui.y += (UI_Y_CLOSED -ui.y) / 3;
}
}
private function onSliderChange( event:Event ):void
{
switch( event.currentTarget )
{
case ui.particlesSlider : numParticles = event.currentTarget.value; break;
case ui.seedSlider : noiseSeed = event.currentTarget.value; break;
case ui.baseXSlider : baseX = event.currentTarget.value; break;
case ui.baseYSlider : baseY = event.currentTarget.value; break;
case ui.offset1Slider : offsetSpeed1 = event.currentTarget.value; break;
case ui.offset2Slider : offsetSpeed2 = event.currentTarget.value; break;
case ui.pSpeedSlider : speedMultiplier = event.currentTarget.value; break;
}
}
private function onCBSelect( event:Event ):void
{
switch( event.currentTarget )
{
case ui.showNoiseCB : _noiseBMP.visible = ui.showNoiseCB.selected; break;
case ui.blitCB : useBlitting = ui.blitCB.selected; break;
}
}
}
}
import flash.display.Shape;
internal class Particle extends Shape
{
public static var COLOUR:uint = 0x111111;
public static const MIN_SPEED:int = 1;
public static const MAX_SPEED:int = 4;
public static const MIN_WANDER:Number = 0.8;
public static const MAX_WANDER:Number = 1.2;
public var speed:Number;
public var wander:Number;
public function Particle()
{
speed = Math.random() * (MAX_SPEED - MIN_SPEED) + MIN_SPEED;
wander = Math.random() * (MAX_WANDER - MIN_WANDER) + MIN_WANDER;
draw();
}
public function draw()
{
graphics.clear();
graphics.beginFill( COLOUR );
graphics.moveTo( -1, -0.5);
graphics.lineTo( 1, 0);
graphics.lineTo( -1, 0.5);
graphics.lineTo( -1, -0.5);
graphics.endFill();
}
}

Related

State Machine Cant get to work

Learning to code so this might sound noobish...
Using Action Script
I am trying to make my Agents react to my segments so they run away.
So I need to connect part of my Main code to my Agent code
Here is my code :
Main.as
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.display.Stage;
public class Main extends Sprite
{
private var score:Score;
private var count:int;
private var bleh: int = 0;
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 20;
private var player:Point = new Point (200, 200)
private var friend:Agent = new Agent;
private var snakeHead:SnakeHead;
private var snakeTail:SnakeTail;
private var background: Sprite;
private var border: Bushes;
private var xVel: Number;
private var yVel: Number;
public function Main():void
{
xVel = 0;
yVel = 0;
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
snakeHead = new SnakeHead();
snakeTail = new SnakeTail();
score = new Score();
border = new Bushes;
score.x = 11;
score.y = 14;
addChild(score);
stage.addChild(border);
count = 0;
addChildAt(snakeHead,0);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (10, 20);
addChildAt(segment,0);
addChildAt(snakeTail,0);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
background = new LevelOne(); //creates the background
addChildAt(background,0);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 3; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = 400;
a.y = 300;
a.name = "Name"+x;
trace (x);
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(evt:Event):void
{
for (var i:int = 0; i < Agents.length; i++)
{
Agents[i].update();
if (snakeHead.hitTestObject(Agents[i]))
{
//trace (Agents[i].name);
removeAgent(Agents[i]);
Agents.splice(i,1);
count ++;
score.lowercasetext.text = count.toString();
trace("count: " + count);
}
}
}
private function onEnterFrame(evt:Event):void
{
player.x += xVel;
player.y += yVel;
drag(snakeHead, player.x, player.y);
drag(segments[0], snakeHead.x, snakeHead.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
var PlayerHalfWidth: Number = segments[i].width / 2;
var PlayerHalfHeight: Number = segments[i].height / 2;
if (segments[i].x + PlayerHalfWidth > stage.stageWidth) {
segments[i].x = stage.stageWidth - PlayerHalfWidth;
} else if (segments[i].x - PlayerHalfWidth < 0) {
segments[i].x = 0 + PlayerHalfWidth;
}
if (segments[i].y + PlayerHalfHeight > stage.stageHeight) {
segments[i].y = stage.stageHeight - PlayerHalfHeight;
}else if (segments[i].y - PlayerHalfHeight < 0) {
segments[i].y = 0 + PlayerHalfHeight;
}
var playerHalfWidth: Number = segments[i - 1].width / 2;
var playerHalfHeight: Number = segments[i - 1].height / 2;
if (segments[i - 1].x + playerHalfWidth > stage.stageWidth) {
segments[i - 1].x = stage.stageWidth - playerHalfWidth;
} else if (segments[i - 1].x - playerHalfWidth < 0) {
segments[i - 1].x = 0 + playerHalfWidth;
}
if (segments[i - 1].y + playerHalfHeight > stage.stageHeight) {
segments[i - 1].y = stage.stageHeight - playerHalfHeight;
}else if (segments[i - 1].y - playerHalfHeight < 0) {
segments[i - 1].y = 0 + playerHalfHeight;
}
}
drag(snakeTail, segments[19].x, segments[19].y);
var HeadHalfWidth: Number = snakeHead.width / 2;
var HeadHalfHeight: Number = snakeHead.height / 2;
if (snakeHead.x + HeadHalfWidth > stage.stageWidth) {
snakeHead.x = stage.stageWidth - HeadHalfWidth;
} else if (snakeHead.x - HeadHalfWidth < 0) {
snakeHead.x = 0 + HeadHalfWidth;
}
if (snakeHead.y + HeadHalfHeight > stage.stageHeight) {
snakeHead.y = stage.stageHeight - HeadHalfHeight;
}else if (snakeHead.y - HeadHalfHeight < 0) {
snakeHead.y = 0 + HeadHalfHeight;
}
//drag(segments[19], snakeTail.x, snakeTail.y);
/*for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
if(segments[0].hitTestObject(a))
{
trace("True");
trace(bleh + " " + "F*CKING HELL!");
trace(a.name);
stage.removeChild(Agents[1]);
}
}*/
}
private function removeAgent(a:Agent):void
{
a.parent.removeChild(a);
trace("Collision Detected!");
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = -5;
}
if (evt.keyCode == 83)
{
player;
yVel = 5;
}
if (evt.keyCode == 68)
{
player;
xVel = 5;
}
if (evt.keyCode == 65)
{
player;
xVel = -5;
}
//trace (player.x + " " + player.y);
trace (xVel + " " + yVel);
}
private function keyUp (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = 0;
}
else if (evt.keyCode == 83)
{
player;
yVel = 0;
}
else if (evt.keyCode == 68)
{
player;
xVel = 0;
}
else if (evt.keyCode == 65)
{
player;
xVel = 0;
}
}
private function drag(segment:MovieClip, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Agent.as
package agent
{
import agent.states.ChaseState;
import agent.states.ConfusionState;
import agent.states.FleeState;
import agent.states.IAgentState;
import agent.states.IdleState;
import agent.states.WanderState;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.*;
import Segment;
import Main;
public class Agent extends MovieClip
{
private var mouses:mouse;
public static const IDLE:IAgentState = new IdleState(); //Define possible states as static constants
public static const WANDER:IAgentState = new WanderState();
public static const CHASE:IAgentState = new ChaseState();
public static const FLEE:IAgentState = new FleeState();
public static const CONFUSED:IAgentState = new ConfusionState();
public var snake:Segment;
private const RAD_DEG:Number = 180 / Math.PI;
private var _previousState:IAgentState; //The previous executing state
private var _currentState:IAgentState; //The currently executing state
private var _pointer:Shape;
private var _tf:TextField;
public var velocity:Point = new Point();
public var speed:Number = 0;
public var fleeRadius:Number = 100; //If the mouse is "seen" within this radius, we want to flee
public var chaseRadius:Number = 50; //If the mouse is "seen" within this radius, we want to chase
public var numCycles:int = 0; //Number of updates that have executed for the current state. Timing utility.
public function Agent()
{
//Boring stuff here
_tf = new TextField();
_tf.defaultTextFormat = new TextFormat("_sans", 10);
_tf.autoSize = TextFieldAutoSize.LEFT;
_pointer = new Shape();
mouses = new mouse();
snake = new Segment(1, 1);
/*g.beginFill(0);
g.drawCircle(0, 0, 5);
g.endFill();
g.moveTo(0, -5);
g.beginFill(0);
g.lineTo(10, 0);
g.lineTo(0, 5);
g.endFill();*/
addChild(mouses);
addChild(_tf);
_currentState = IDLE; //Set the initial state
}
/**
* Outputs a line of text above the agent's head
* #param str
*/
public function say(str:String):void {
_tf.text = str;
_tf.y = -_tf.height - 2;
}
/**
* Trig utility methods
*/
public function get canSeeMouse():Boolean {
var dot:Number = snake.x * velocity.x + snake.y * velocity.y;
return dot > 0;
}
public function get distanceToMouse():Number {
var dx:Number = x - snake.x;
var dy:Number = y - snake.y;
return Math.sqrt(dx * dx + dy * dy);
}
public function randomDirection():void {
var a:Number = Math.random() * 6.28;
velocity.x = Math.cos(a);
velocity.y = Math.sin(a);
}
public function faceMouse(multiplier:Number = 1):void {
var dx:Number = snake.x - x;
var dy:Number = snake.y - y;
var rad:Number = Math.atan2(dy, dx);
velocity.x = multiplier*Math.cos(rad);
velocity.y = multiplier*Math.sin(rad);
}
/**
* Update the current state, then update the graphics
*/
public function update():void {
if (!_currentState) return; //If there's no behavior, we do nothing
numCycles++;
_currentState.update(this);
x += velocity.x*speed;
y += velocity.y*speed;
if (x + velocity.x > stage.stageWidth || x + velocity.x < 0) {
x = Math.max(0, Math.min(stage.stageWidth, x));
velocity.x *= -1;
}
if (y + velocity.y > stage.stageHeight || y + velocity.y < 0) {
y = Math.max(0, Math.min(stage.stageHeight, y));
velocity.y *= -1;
}
mouses.rotation = RAD_DEG * Math.atan2(velocity.y, velocity.x);
}
public function setState(newState:IAgentState):void {
if (_currentState == newState) return;
if (_currentState) {
_currentState.exit(this);
}
_previousState = _currentState;
_currentState = newState;
_currentState.enter(this);
numCycles = 0;
}
public function get previousState():IAgentState { return _previousState; }
public function get currentState():IAgentState { return _currentState; }
}
}

Bullet Trajectory in Flash

I'm currently creating a bullet that follows my avatar and is spawned once I hit the spacebar but I am a little confused on how I go about providing a velocity/trajectory to said object to collide with my enemies. Any help will do.
game file
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.utils.*;
public class SpaceVigilanteGame extends MovieClip
{
public var army:Array;
public var avatar:Avatar;
public var bullet:Bullet;
public var gameTimer:Timer;
public var useMouseControl:Boolean;
public var rightKeyIsBeingPressed:Boolean;
public var leftKeyIsBeingPressed:Boolean;
public var spaceBarIsBeingPressed:Boolean;
var gameWidth:int = 0;
var gameHeight:int = 0;
public function log(message:String):void
{
trace (message);
if (ExternalInterface.available)
{
ExternalInterface.call('console.log', message);
}
}
public function SpaceVigilanteGame()
{ useMouseControl = false;
leftKeyIsBeingPressed = false;
rightKeyIsBeingPressed = false;
spaceBarIsBeingPressed = false;
army = new Array();
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
avatar = new Avatar();
addChild( avatar );
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
avatar.x = 50;
avatar.y = 400;
}
gameWidth = stage.stageWidth;
gameHeight = stage.stageHeight;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
gameTimer.addEventListener( TimerEvent.TIMER, moveAvatar );
gameTimer.addEventListener( TimerEvent.TIMER, shoot );
gameTimer.start();
stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
//Respawn enemies
var myInterval:uint = setInterval (spawnEnemy, 2000);
function spawnEnemy(){
var posX = Math.floor(Math.random() * (660 - 25 + 1)) + 35;
var newEnemy = new Enemy( posX, 30 );
army.push( newEnemy );
addChild( newEnemy );
}
function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = true;
}
else if ( keyboardEvent.keyCode == Keyboard.LEFT )
{
leftKeyIsBeingPressed = true;
}
else if (keyboardEvent.keyCode == Keyboard.SPACE )
{
spaceBarIsBeingPressed = true;
}
}
function onKeyRelease( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = false;
}
else if (keyboardEvent.keyCode ==Keyboard.LEFT )
{
leftKeyIsBeingPressed = false;
}
else if (keyboardEvent.keyCode == Keyboard.SPACE )
{
spaceBarIsBeingPressed = false;
}
}
}
public function moveEnemy( timerEvent:TimerEvent ):void
{
// Set up Enemy Array
for each ( var enemy:Enemy in army )
{
if ( avatar.hitTestObject( enemy ) )
{
// game over screen
gameTimer.stop();
var gameOverScreen:GameOverScreen = new GameOverScreen();
gameOverScreen.x = 0;
gameOverScreen.y = 0;
addChild( gameOverScreen );
}
// Have enemy move to one side of the screen, drop down a pixel, and move into the other direction
else if(enemy.x+enemy.width+2<=gameWidth)
{
enemy.moveRight();
}
else if(enemy.y+enemy.height+2<=gameHeight)
{
enemy.moveDown();
}
else if(enemy.x-2>=0)
{
enemy.moveLeft();
}
else if(enemy.y-2>=0)
{
enemy.moveUp();
}
//Loop enemy back to top
if (enemy.y >= 460){
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
enemy.y = 0;
}
}
}
public function moveAvatar( timerEvent:TimerEvent ):void
{
// Boolean statement is set to false, so that the mouse control doesn't work
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
// move avatar left and right
else if ( rightKeyIsBeingPressed )
{
if (avatar.x <= 660){
avatar.moveRight();
}
}
else if ( leftKeyIsBeingPressed )
{
if (avatar.x >= 35){
avatar.moveLeft();
}
}
}
// shoot bullet
public function shoot (timerEvent:TimerEvent ):void
{
if ( spaceBarIsBeingPressed )
{
bullet = new Bullet(avatar.x, avatar.y);
addChild( bullet );
bullet.moveBullet();
}
}
}
}
Bullet Class
package
{
import flash.display.MovieClip;
public class Bullet extends MovieClip
{
public function Bullet(xPos:Number, yPos:Number)
{
x = xPos;
y = yPos;
}
public function moveBullet():void
{
y += 2;
}
}
}

Moving b2body With Keyboard

I have this code that gives the b2Body an impulse towards the cursor when you click on stage.
private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
I was trying to use keyboard right arrow key for movement and so in the update function I added the if key[Keyboard.RIGHT]:
private function update(e:Event):void {
world.Step (1 / 30, 10, 10);
if (key[Keyboard.RIGHT]) {
impulse_x = 3;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
}
private function onKeyUp(e:KeyboardEvent):void
{
key[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
key[e.keyCode] = true;
}
But the b2body goes to top left on the screen and stays there and doesn't move. I am changing the impulse value that then goes into the vector that is applied to the body.
Although it doesn't give me any errors.
EDIT: The whole code!
package
{
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import Box2D.Dynamics.Contacts.b2ContactEdge;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
public var world:b2World = new b2World(new b2Vec2(0, 0), true);
public var world_scale:Number = 30;
public var mainChar:b2Body;
private var ground:b2Body;
public var keys:Array = [];
public var beingPressed:Boolean;
public var impulse_x:Number;
public var impulse_y:Number;
public var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
public function Main():void
{
createMainCharacter(stage.stageWidth / 2, stage.stageHeight / 2, 50, 100);
var th:uint = 10;
addEventListener(Event.ENTER_FRAME, update);
//stage.addEventListener(MouseEvent.CLICK, clicked);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
/**private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}**/
private function update(e:Event):void
{
world.Step (1 / 30, 10, 10);
var temp:Sprite;
for (var body:b2Body = world.GetBodyList(); body != null; body = body.GetNext())
{
if (body.GetUserData())
{
temp = body.GetUserData() as Sprite;
temp.x = body.GetPosition().x * world_scale;
temp.y = body.GetPosition().y * world_scale;
temp.rotation = body.GetAngle() * (180 / Math.PI); // radians to degrees
}
}
if (keys[Keyboard.RIGHT])
{
impulse_x = 3;
impulse_y = 0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
} else {
impulse_x = 0;
impulse_y = 0;
}
}
private function createMainCharacter(x:Number, y:Number, width:Number, height:Number):void
{
var mainCharSprite:Sprite = new Sprite();
mainCharSprite.graphics.beginFill(0x000000);
mainCharSprite.graphics.drawRect( -width / 2, -height / 2 , width, height);
mainCharSprite.graphics.endFill;
mainCharSprite.x = x;
mainCharSprite.y = y;
addChild(mainCharSprite);
var mainCharDef:b2BodyDef = new b2BodyDef();
mainCharDef.userData = mainCharSprite;
mainCharDef.type = b2Body.b2_dynamicBody;
mainCharDef.position.Set (x / world_scale, y / world_scale);
mainChar = world.CreateBody(mainCharDef);
var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsBox((width / 2) / world_scale, (height / 2) / world_scale);
var fixtureDef:b2FixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.restitution = 0.1;
fixtureDef.friction = 0.1;
fixtureDef.density = 0.5;
mainChar.CreateFixture(fixtureDef);
}
private function onKeyUp(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
}
}
Changing the values of impulse_x and impulse_y is not going to update the values used by the b2Vec2 impulse. In AS3 primitives are passed by value not by reference. If you want the b2Vec2 object referenced by the variable impulse to change its values you need to change them directly on the object itself:
impulse.x = 3.0;
impulse.y = 0.0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());

User interaction with Leapmotion AS3 library

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());
}
}
}
}

Game Over function is not working Starling

I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code.
package screens
{
import flash.geom.Rectangle;
import flash.utils.getTimer;
import events.NavigationEvent;
import objects.GameBackground;
import objects.Hero;
import objects.Item;
import objects.Obstacle;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.text.TextField;
import starling.utils.deg2rad;
public class InGame extends Sprite
{
private var screenInGame:InGame;
private var screenWelcome:Welcome;
private var startButton:Button;
private var playAgain:Button;
private var bg:GameBackground;
private var hero:Hero;
private var timePrevious:Number;
private var timeCurrent:Number;
private var elapsed:Number;
private var gameState:String;
private var playerSpeed:Number = 0;
private var hitObstacle:Number = 0;
private const MIN_SPEED:Number = 650;
private var scoreDistance:int;
private var obstacleGapCount:int;
private var gameArea:Rectangle;
private var touch:Touch;
private var touchX:Number;
private var touchY:Number;
private var obstaclesToAnimate:Vector.<Obstacle>;
private var itemsToAnimate:Vector.<Item>;
private var scoreText:TextField;
private var remainingLives:TextField;
private var gameOverText:TextField;
private var iconSmall:Image;
static private var lives:Number = 2;
public function InGame()
{
super();
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
drawGame();
scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true);
remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true);
iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1"));
iconSmall.x = 360;
iconSmall.y = 40;
this.addChild(iconSmall);
this.addChild(scoreText);
this.addChild(remainingLives);
}
private function drawGame():void {
bg = new GameBackground();
this.addChild(bg);
hero = new Hero();
hero.x = stage.stageHeight / 2;
hero.y = stage.stageWidth / 2;
this.addChild(hero);
startButton = new Button(Assets.getAtlas().getTexture("startButton"));
startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5;
this.addChild(startButton);
gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250);
}
public function disposeTemporarily():void {
this.visible = false;
}
public function initialize():void {
this.visible = true;
this.addEventListener(Event.ENTER_FRAME, checkElapsed);
hero.x = -stage.stageWidth;
hero.y = stage.stageHeight * 0.5;
gameState ="idle";
playerSpeed = 0;
hitObstacle = 0;
bg.speed = 0;
scoreDistance = 0;
obstacleGapCount = 0;
obstaclesToAnimate = new Vector.<Obstacle>();
itemsToAnimate = new Vector.<Item>();
startButton.addEventListener(Event.TRIGGERED, onStartButtonClick);
//var mainStage:InGame =InGame.current.nativeStage;
//mainStage.dispatchEvent(new Event(Event.COMPLETE));
//playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onStartButtonClick(event:Event):void {
startButton.visible = false;
startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick);
launchHero();
}
private function launchHero():void {
this.addEventListener(TouchEvent.TOUCH, onTouch);
this.addEventListener(Event.ENTER_FRAME, onGameTick);
}
private function onTouch(event:TouchEvent):void {
touch = event.getTouch(stage);
touchX = touch.globalX;
touchY = touch.globalY;
}
private function onGameTick(event:Event):void {
switch(gameState) {
case "idle":
if(hero.x < stage.stageWidth * 0.5 * 0.5) {
hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05;
hero.y = stage.stageHeight * 0.5;
playerSpeed += (MIN_SPEED - playerSpeed) * 0.05;
bg.speed = playerSpeed * elapsed;
} else {
gameState = "flying";
}
break;
case "flying":
if(hitObstacle <= 0) {
hero.y -= (hero.y - touchY) * 0.1;
if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) {
hero.rotation = deg2rad(-(hero.y - touchY) * 0.2);
}
if(hero.y > gameArea.bottom - hero.height * 0.5) {
hero.y = gameArea.bottom - hero.height * 0.5;
hero.rotation = deg2rad(0);
}
if(hero.y < gameArea.top + hero.height * 0.5) {
hero.y = gameArea.top + hero.height * 0.5;
hero.rotation = deg2rad(0);
}
} else {
hitObstacle--
cameraShake();
}
playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01;
bg.speed = playerSpeed * elapsed;
scoreDistance += (playerSpeed * elapsed) * 0.1;
scoreText.text = "Score: " + scoreDistance;
initObstacle();
animateObstacles();
createEggItems();
animateItems();
remainingLives.text = "Lives: "+lives + " X ";
if(lives == 0) {
gameState = "over";
}
break;
case "over":
gameOver();
break;
}
}
private function gameOver():void {
gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true);
scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true);
this.addChild(scoreText);
this.addChild(gameOverText);
playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain"));
playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75;
this.addChild(playAgain);
playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onRetry(event:Event):void {
playAgain.visible = false;
gameOverText.visible = false;
scoreText.visible = false;
var btnClicked:Button = event.target as Button;
if((btnClicked as Button) == playAgain) {
this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true));
}
disposeTemporarily();
}
private function animateItems():void {
var itemToTrack:Item;
for(var i:uint = 0; i < itemsToAnimate.length; i++) {
itemToTrack = itemsToAnimate[i];
itemToTrack.x -= playerSpeed * elapsed;
if(itemToTrack.bounds.intersects(hero.bounds)) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
if(itemToTrack.x < -50) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
}
}
private function createEggItems():void {
if(Math.random() > 0.95){
var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10));
itemToTrack.x = stage.stageWidth + 50;
itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top;
this.addChild(itemToTrack);
itemsToAnimate.push(itemToTrack);
}
}
private function cameraShake():void {
if(hitObstacle > 0) {
this.x = Math.random() * hitObstacle;
this.y = Math.random() * hitObstacle;
} else if(x != 0) {
this.x = 0;
this.y = 0;
lives--;
}
}
private function initObstacle():void {
if(obstacleGapCount < 1200) {
obstacleGapCount += playerSpeed * elapsed;
} else if(obstacleGapCount !=0) {
obstacleGapCount = 0;
createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000);
}
}
private function animateObstacles():void {
var obstacleToTrack:Obstacle;
for(var i:uint = 0; i<obstaclesToAnimate.length; i++) {
obstacleToTrack = obstaclesToAnimate[i];
if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) {
obstacleToTrack.alreadyHit = true;
obstacleToTrack.rotation = deg2rad(70);
hitObstacle = 30;
playerSpeed *= 0.5;
}
if(obstacleToTrack.distance > 0) {
obstacleToTrack.distance -= playerSpeed * elapsed;
} else {
if(obstacleToTrack.watchOut) {
obstacleToTrack.watchOut = false;
}
obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed;
}
if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") {
obstaclesToAnimate.splice(i, 1);
this.removeChild(obstacleToTrack);
}
}
}
private function checkElapsed(event:Event):void {
timePrevious = timeCurrent;
timeCurrent = getTimer();
elapsed = (timeCurrent - timePrevious) * 0.001;
}
private function createObstacle(type:Number, distance:Number):void{
var obstacle:Obstacle = new Obstacle(type, distance, true, 300);
obstacle.x = stage.stageWidth;
this.addChild(obstacle);
if(type >= 4) {
if(Math.random() > 0.5) {
obstacle.y = gameArea.top;
obstacle.position = "top"
} else {
obstacle.y = gameArea.bottom - obstacle.height;
obstacle.position = "bottom";
}
} else {
obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top;
obstacle.position = "middle";
}
obstaclesToAnimate.push(obstacle);
}
}
}
You're not calling initialize() anywhere, which is where the gameState is initially set to "idle" it seems... what does this code do currently when you run it?
The goal here is to get the onGameTick(event) function running every frame, which is going to switch between idle/flying/over game states.