Bullet Trajectory in Flash - actionscript-3

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

Related

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

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

How to smoothly scroll content in an AIR Android Application?

I have written a small class to be used to scroll content on mobile devices. The class works fine but the scrolling doesn't feel smooth. Here is the class:
package {
import flash.display.Sprite;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import flash.geom.Rectangle;
import com.greensock.TweenMax;
import com.greensock.easing.*;
import flash.utils.setTimeout;
public class FlickScroll extends Sprite {
private var currentY:Number;
private var lastY:Number;
private var vy:Number;
public var clickable:Boolean = true;
private var dragging:Boolean = false;
private var firstY:Number;
private var secondY:Number;
private var content:InteractiveObject;
private var masker:InteractiveObject;
private var topBounds:Number;
private var bottomBounds:Number;
private var Offset:Number;
public var friction:Number = .90;
public var flickable:Boolean = false;
public var scrollVelocity:Number;
public function FlickScroll(Masker:InteractiveObject, Content:InteractiveObject, TopBounds:Number, BottomBounds:Number) {
masker = Masker;
content = Content;
topBounds = TopBounds;
bottomBounds = BottomBounds;
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
}
private function onAddedToStage(evt:Event):void
{
init();
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);
content.mask = masker;
content.cacheAsBitmap = true;
}
private function init():void
{
currentY = content.y;
lastY = content.y;
vy = 0;
scrollVelocity = 2;
content.addEventListener(MouseEvent.MOUSE_DOWN, onContentDown, false, 0, true);
}
private function onContentDown(evt:MouseEvent):void
{
firstY = content.y;
Offset = content.mouseY;
trace(mouseY, Offset, mouseY - Offset);
content.addEventListener(MouseEvent.MOUSE_MOVE, onContentMove, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, onContentUp, false, 0, true);
}
private function onContentMove(evt:MouseEvent):void
{
dragging = true;
clickable = false;
content.y = mouseY - Offset;
if(content.y > topBounds + 200)
{
content.y = topBounds + 200;
}
else if(content.y < bottomBounds - 200)
{
content.y = bottomBounds - 200;
}
trace("ContentY: ", content.y, "Bottom Bounds: ", bottomBounds, "Top Bounds: ", topBounds);
evt.updateAfterEvent();
}
private function onContentUp(evt:MouseEvent):void
{
secondY = content.y;
var dy:Number = secondY - firstY;
if(dy < 20 && dy > -20)
{
clickable = true;
}
if(content.y > this.topBounds)
{
TweenMax.to(content, .4, {y:topBounds, ease:Expo.easeOut});
}
else if( content.y < this.bottomBounds)
{
TweenMax.to(content, .4, {y:bottomBounds, ease:Expo.easeOut});
}
else
{
dragging = false;
}
//setTimeout(setDraggingFalse, 400);
content.removeEventListener(MouseEvent.MOUSE_MOVE, onContentMove);
content.removeEventListener(MouseEvent.MOUSE_UP, onContentUp);
}
private function onLoop(evt:Event):void
{
if(this.flickable)
{
if(dragging)
{
lastY = currentY;
currentY = mouseY;
vy = (currentY - lastY)/scrollVelocity;
}
else
{
content.y += vy;
vy *= friction;
}
}
if(!dragging)
{
if(content.y > topBounds)
{
content.y = topBounds;
}
else if(content.y < bottomBounds)
{
content.y = bottomBounds;
}
}
}
public function updateBounds(top:Number, bottom:Number):void
{
bottomBounds = bottom;
topBounds = top;
}
private function setDraggingFalse():void
{
dragging = false;
}
}
}
Sorry for the code being really messy.
What steps can I take to make the scrolling feel more smooth? Any help is greatly appreciated.
If youre using bitmaps, try following this guide. It deals with smoothly scrolling with bitmaps.
If youre dealing with a movieclip, startDrag() and stopDrag() aren't too bad. Maybe adding a Tween and decelerating it based on a frame by frame comparison of the mouses last y and current y to get the "thrust" on release of the mouse. Might have to lock the x position of the movieclip on a mouse move event (or y depending how how you want it to scroll).

Error #1034: Type Coercion failed: cannot convert flash.display::Stage#27dfe089 to flash.display.MovieClip

here it is the error >> TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage#261b4089 to flash.display.MovieClip.
at com.ply::Heli/fireBullet()
at com.ply::Heli/myOnPress()
this is Heli's Class :
package com.ply
{
import flash.display.MovieClip;
import flash.display.*;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import com.peluru.Bullet;
public class Heli extends MovieClip
{
var shotCooldown:int;
const MAX_COOLDOWN = 10;
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
public function Heli()
{
shotCooldown = MAX_COOLDOWN;
bullets = new Array();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, RunHeli);
}
private function RunHeli(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
public function update(e:Event){
shotCooldown-- ;
}
/**
* Keyboard Handlers
*/
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
yAcceleration = 1;
}
else if (event.keyCode == 32)
{
fireBullet();
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
yAcceleration = 0;
}
}
public function fireBullet() {
if (shotCooldown <=0 )
{
shotCooldown=MAX_COOLDOWN;
var b = new Bullet();
var b2= new Bullet();
b.x = this.x +20;
b.y = this.y ;
b2.x= this.x -20;
b2.y= this.y ;
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
trace(bullets.length);
parent.addChild(b);
parent.addChild(b2);
}
}
}
}
and this is the Main Class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
private var nextPlane:Timer;
public var enemies:Array;
public var bullets:Array;
public function Main()
{
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
enemies = new Array();
bullets = ne Array();
setNextPlane();
gameState = STATE_START_PLAYER;
gameLoop();
//stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
stage.addEventListener(Event.ENTER_FRAME, back);
stage.addEventListener(Event.ENTER_FRAME,checkForHits);
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
// create plane
var enemy:Airplane2 = new Airplane2();
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
enemies.push(enemy);
// set time for next plane
setNextPlane();
}
public function removePlane(plane:Airplane2) {
for(var i in enemies) {
if (enemies[i] == plane) {
enemies.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullet) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=enemies.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(enemies[airplaneNum])) {
enemies[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
trace("kena");
//shotsHit++;
//showGameScore();
break;
}
}
}
//if ((shotsLeft == 0) && (bullets.length == 0)) {
// endGame();
//}
}
public function back( evt:Event ):void
{ // Backgroud Land
if (Dessert2.y >= 0 && Dessert.y >= 720)
{
Dessert.y = Dessert2.y - 1240 ;
}
else if (Dessert.y >= 0 && Dessert2.y >= 720)
{
Dessert2.y = Dessert.y - 1240 ;
}
else
{
Dessert.y = Dessert.y +5 ;
Dessert2.y = Dessert2.y +5 ;
}
// Background Clouds
if (Clouds2.y >= 0 && Clouds.y >= 720)
{
Clouds.y = Clouds2.y - 2480 ;
}
else if (Clouds.y >= 0 && Clouds2.y >= 720)
{
Clouds2.y = Clouds.y - 2480 ;
}
else
{
Clouds.y = Clouds.y +10 ;
Clouds2.y = Clouds2.y +10 ;
}
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
gameLoop();
//txtScore.text = 'Score: '+score;
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
}
}
You have added your player in Main into stage instead of this - why, by the way? So, there are two methods of fixing this: First, change line where you add player to display list, and second, remove direct coercion from Heli.fireBullet() function. I'd say use the first one.
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
this.addChild(player); // <-- this, not stage
gameState = STATE_PLAY_GAME;
}
Change
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
to
MovieClip(root).bullets.push(b);
MovieClip(root).bullets.push(b2);

ADDED_TO_STAGE Event doesn't work in certain frame?

This is Heli's Class and it'll called in main class ,the target of main class in frame 2 .
The frame 1 contain button that can make me go to frame 2 .but this movie clip of Heli doesn't added to the stage . but it'll work if i targeting main class in frame 1 . so can anyone tell me how to use added_to_stage event in specified frame ??? (sorry about my english)
package com.ply
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Heli extends MovieClip
{
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
private var bullets:Array;
private var missiles:Array;
public function Heli()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
private function init():void
{
stage.addEventListener(Event.ENTER_FRAME, runGame);
}
private function runGame(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
}
}
public function Heli()
{
if (stage) init();
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
here it is the main class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
public function Main()
{
//stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// instantiate car class
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
//addChild(bulletholder);
addChild(bulletContainer);
gameState = STATE_START_PLAYER;
gameLoop();
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add car to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
//CheckTime();
gameLoop();
//txtScore.text = 'Score: '+score;
}
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
player.xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
player.yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 1;
}
else if (event.keyCode == 32 && shootAllow)
{
fireBullet();
}
}
public function fireBullet() {
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
var newBullet2:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = player.x+20; //+ player.width/2 - player.width/2;
newBullet.y = player.y;
newBullet2.x = player.x-20;
newBullet2.y = player.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
bulletContainer.addChild(newBullet2);
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
//if time hasn't reached the limit, then just increment
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 0;
}
}
}
}

class bug after making it external

I have object char in my stage and i controlled it with main.as but when i decided to make it char.as and to add it in main.as become the error..
main.as
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
import flash.sampler.DeleteObjectSample;
import flashx.textLayout.utils.CharacterUtil;
public class main extends MovieClip
{
public function main()
{
var mychar:char = new char();
mychar.x = 60;
mychar.y = 60;
addChild(mychar);
}
}
}
char.as
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
import flash.sampler.DeleteObjectSample;
public class char extends MovieClip
{
//char vars
var isRight:Boolean = false;
var isLeft:Boolean = false;
var isUp:Boolean = false;
var isDown:Boolean = false;
var angleDegree;
var angleRadian;
//stage vars
var objects = new Array(50);
public function char()
{
for (var i = 0; i<numChildren; i++) {
objects[i] = getChildAt(i);
}
addEventListener(Event.ENTER_FRAME, charEnterFrame);
addEventListener( MouseEvent.MOUSE_DOWN , MouseClick);
addEventListener(KeyboardEvent.KEY_DOWN, KeyDown);
addEventListener(KeyboardEvent.KEY_UP, KeyUp);
}
function charEnterFrame(e:Event)
{
// **Char rotation
angleRadian=Math.atan2(mouseY-this.y,mouseX-this.x);
angleDegree = angleRadian * 180 / Math.PI;
this.rotation = angleDegree;
// **Char Movement
if (isRight==true)this.x += 5;
if (isLeft==true)this.x -= 5;
if (isUp==true)this.y -= 5;
if (isDown==true)this.y += 5;
}
function MouseClick(event:MouseEvent)
{
var radius = 30;
trace(objects.length);
var dx = radius * Math.cos(angleRadian);
var dy = radius * Math.sin(angleRadian);
var movex = 20 * Math.cos(angleRadian);
var movey = 20 * Math.sin(angleRadian);
var bullet = new Sprite();
bullet.graphics.beginFill(0x000000);
bullet.graphics.drawCircle(this.x+dx, this.y+dy, 3);
bullet.graphics.endFill();
var i = 1;
var f:Function;
addChild(bullet);
bullet.addEventListener(Event.ENTER_FRAME, f = function(){
bullet.x += movex*i;
bullet.y += movey*i;
for (var j = 0; j < objects.length-1; j++) {
if (bullet.hitTestObject(objects[j])) {
bullet.graphics.clear();
}
}
i++;
});
}
function KeyDown(event:KeyboardEvent):void
{
if (event.keyCode == 39)isRight = true;
if (event.keyCode == 37)isLeft = true;
if (event.keyCode == 38)isUp = true;
if (event.keyCode == 40)isDown = true;
}
function KeyUp(event:KeyboardEvent):void
{
if (event.keyCode == 39)isRight = false;
if (event.keyCode == 37)isLeft = false;
if (event.keyCode == 38)isUp = false;
if (event.keyCode == 40)isDown = false;
}
}
}
Flash result:http://www.shareswf.com/media/games/swf/28063.swf