Accessing timeline variables from a class? - actionscript-3

In one of the frame of my program I have code for a "player" that is essentially a cannon that follows the character around, specifics aren't important. So I'd like to make this cannon into a class that I can then place as a movieclip, on the stage and have similar cannons serving similar functions. So Basicly I need to make this into a class that somehow interacts with timeline variables?
right now the Player class looks like this
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
public class Player extends MovieClip
{
public function Player() {
}
}
}
Warning code dump you don't have to read all this, this is the player code that I need to make into a class so that I can make more players with different parameters to their not all following the character etc... So how do I do this? this code is interacting with objects on the stage and other variables in the timeline at the moment.
// player settings
var _rotateSpeedMax:Number = 20;
var _gravity:Number = .10;
// projectile gun settings
var _bulletSpeed:Number = 4;
var _maxDistance:Number = 200;
var _reloadSpeed:Number = 250;//milliseconds
var _barrelLength:Number = 20;
var _bulletSpread:Number = 5;
// gun stuff
var _isLoaded:Boolean = true;
var _isFiring:Boolean = false;
var _endX:Number;
var _endY:Number;
var _startX:Number;
var _startY:Number;
var _reloadTimer:Timer;
var _bullets:Array = [];
// array that holds walls
var _solidObjects:Array = [];
// global vars
var _player:MovieClip;
var _dx:Number;
var _dy:Number;
var _pcos:Number;
var _psin:Number;
var _trueRotation:Number;
/**
* Constructor
*/
_solidObjects = [world.wall01,world.wall02,world.wall03,world.wall04];
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
//character.addEventListener(Event.ENTER_FRAME, moveDude);
//////////////////////////////////////;
// Player & Weapon Methods
//////////////////////////////////////
/**
* Creates player
* Uses "Player" movieclip linked in library
*/
createPlayer();
function createPlayer():void
{
// attach player movieclip from library
// position player in center
if (character!=null&&_player!=null)
{
_player.x = character.x +5;
_player.y = character.y +5;
}
else if (_player ==null)
{
_player = new Player();
// add to display list
stage.addChild(_player);
}
}
/**
* Fire weapon
*/
function fire():void
{
// check if firing
if (! _isFiring)
{
return;
}
// check if reloaded
if (! _isLoaded)
{
return;
}
// create bullet
createBullet();
// start reload timer
_reloadTimer = new Timer(_reloadSpeed);
_reloadTimer.addEventListener(TimerEvent.TIMER, reloadTimerHandler);
_reloadTimer.start();
// set reload flag to false;
_isLoaded = false;
}
/**
* Creates a bullet movieclip and sets it's properties
*/
function createBullet():void
{
// precalculate the cos & sine
_pcos = Math.cos(_player.rotation * Math.PI / 180);
_psin = Math.sin(_player.rotation * Math.PI / 180);
// start X & Y
// calculate the tip of the barrel
_startX = _player.x - _barrelLength * _pcos;
_startY = _player.y - _barrelLength * _psin;
// end X & Y
// calculate where the bullet needs to go
// aim 50 pixels in front of the gun
_endX = _player.x - 50 * _pcos + Math.random() * _bulletSpread - _bulletSpread * .5;
_endY = _player.y - 50 * _psin + Math.random() * _bulletSpread - _bulletSpread * .5;
// attach bullet from library
var tempBullet:MovieClip = new Bullet();
// calculate velocity
tempBullet.vx = (_endX - _startX) / _bulletSpeed;
tempBullet.vy = (_endY - _startY) / _bulletSpeed;
// set position
tempBullet.x = _startX;
tempBullet.y = _startY;
// save starting location
tempBullet.startX = _startX;
tempBullet.startY = _startY;
// set maximum allowed travel distance
tempBullet.maxDistance = stage.stageHeight;//_maxDistance;
// add bullet to bullets array
_bullets.push(tempBullet);
// add to display list;
stage.addChild(tempBullet);
}
/**
* Updates bullets
*/
function updateBullets():void
{
var i:int;
var tempBullet:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullet = _bullets[i];
// check if gravity is enabled
if (gravityCheckbox.selected)
{
// add gravity to Y velocity
tempBullet.vy += _gravity;
}
// update bullet position
tempBullet.x += tempBullet.vx;
tempBullet.y += tempBullet.vy;
// check if bullet went too far
if (getDistance(tempBullet.startX - tempBullet.x, tempBullet.startY - tempBullet.y) > tempBullet.maxDistance + _barrelLength)
{
destroyBullet(tempBullet);
}
// check for collision with walls
if (checkCollisions(tempBullet.x,tempBullet.y))
{
destroyBullet(tempBullet);
}
}
}
/**
* Destroys bullet
* #parambulletTakes bullet movieclip
*/
function destroyBullet(bullet:MovieClip):void
{
var i:int;
var tempBullet:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullet = _bullets[i];
// if found bullet in array
if (tempBullet == bullet)
{
// remove from array
_bullets.splice(i, 1);
// remove from display list;
bullet.parent.removeChild(bullet);
// stop loop;
return;
}
}
}
/**
* Reload weapon
*/
function reloadWeapon():void
{
_isLoaded = true;
}
/**
* Checks for collisions between points and objects in _solidObjects
* #returnCollision boolean
*/
function checkCollisions(testX:Number, testY:Number):Boolean
{
var i:int;
var tempWall:MovieClip;
// loop thru _solidObjects array
for (i = 0; i < _solidObjects.length; i++)
{
// save a reference to current object
tempWall = _solidObjects[i];
// do a hit test
if (tempWall.hitTestPoint(testX,testY,true))
{
return true;
// stop loop
break;
}
}
return false;
}
/**
* Calculate player rotation
*/
function updateRotation():void
{
// calculate rotation based on mouse X & Y
_dx = _player.x - stage.mouseX;
_dy = _player.y - stage.mouseY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx,_dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > _player.rotation + 180)
{
rotateTo -= 360;
}
if (rotateTo < _player.rotation - 180)
{
rotateTo += 360;
}
// ease rotation
_trueRotation = (rotateTo - _player.rotation) / _rotateSpeedMax;
// update rotation
_player.rotation += _trueRotation;
}
//////////////////////////////////////
// Event Handlers
//////////////////////////////////////
/**
* Enter Frame handler
* #parameventUses Event
*/
function enterFrameHandler(event:Event):void
{
createPlayer();
updateRotation();
updateBullets();
fire();
}
/**
* Mouse Up handler
* #parameUses MouseEvent
*/
function onMouseUpHandler(event:MouseEvent):void
{
_isFiring = false;
}
/**
* Mouse Down handler
* #parameUses MouseEvent
*/
function onMouseDownHandler(event:MouseEvent):void
{
_isFiring = true;
}
/**
* Reload timer
* #parameTakes TimerEvent
*/
function reloadTimerHandler(e:TimerEvent):void
{
// stop timer
e.target.stop();
// clear timer var;
_reloadTimer = null;
reloadWeapon();
}
//////////////////////////////////////
// Utilities
//////////////////////////////////////
/**
* Get distance
* #paramdelta_x
* #paramdelta_y
* #return
*/
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
/**
* Get radians
* #paramdelta_x
* #paramdelta_y
* #return
*/
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y,delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #paramradiansTakes radians
* #returnReturns degrees
*/
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}

From the class you can access a variable like this: MovieClip(root).variable

Related

AS3 TypeError: Error #1009: Cannot access a property or method of a null object reference when importing external .swf

I'm importing an external swf into my main project by using the fallowing code:
var FirstLevelLoader:Loader = new Loader();
var FirstLevelFile:URLRequest = new URLRequest("Mainlv.swf");
//load level one
startlevelbttn.addEventListener(MouseEvent.CLICK, LoadFirstLevel);
function LoadFirstLevel(e:Event){
FirstLevelLoader.load(FirstLevelFile);
addChild(FirstLevelLoader);
}
This same type of code works fine when importing other swfs but for Mainlv it doesn't instead it tells me the fallowing error.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Mainlv/createPlayer()
at Mainlv()
So I suppose the error is in the Mainlv.swf file but I don't see what is wrong and running that file independently produces no errors. Here's the code for the fallowing file.
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Mainlv extends MovieClip
{
// player settings
private var _moveSpeedMax:Number = 1000;
private var _rotateSpeedMax:Number = 15;
private var _decay:Number = .98;
private var _destinationX:int = 150;
private var _destinationY:int = 150;
// player
private var _player:MovieClip;
// global
private var _isActive:Boolean = false;
private var _dx:Number = 0;
private var _dy:Number = 0;
private var _vx:Number = 0;
private var _vy:Number = 0;
private var _trueRotation:Number = 0;
private var allbullets:Array = new Array();
private var allast:Array = new Array();
private var score:int=0;
/**
* Constructor
*/
public function Mainlv()
{
// create player object
createPlayer();
// add listeners
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, onMouseUpHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, onMouseDownHandler);
stage.addEventListener(MouseEvent.CLICK, triggerbullet);
}
private function triggerbullet(event:Event){
var mybullet:Bullet= new Bullet();
stage.addChild(mybullet);
mybullet.x=_player.x;
mybullet.y=_player.y;
mybullet.rotation=_player.rotation;
allbullets.push(mybullet);
}
/**
* Creates player
*/
private function createPlayer():void
{
_player = new Player();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 1.15;
stage.addChild(_player);
}
/**
* EnterFrame Handlers
*/
private function enterFrameHandler(event:Event):void
{
updatePosition();
updateRotation();
scorebox.text=String(score);
var t:Number = Math.random();
if(t>0.98) {
addasteroid();
}
for (var a:int = 0;a<allast.length;a++) {
for (var b:int = 0;b<allbullets.length;b++) {
if (allbullets[b].hitTestObject(allast[a])) {
//removeChild(allbullet[b]);
removeChild(allast[a]);
//score
score+=5;
if (score==100) {
dispatchEvent(new Event("next_level"));
}
}
if (allast[a].hitTestObject(_player)) {
//removeChild(allbullet[b]);
trace("hitplayer");
endGame();
}
}
allast[a].y += 3;
}
}//function
/*END GAME*/
private function endGame() {
stage.removeChild(_player);
dispatchEvent(new Event("END_GAME")); // call End_game function to exit external swf
}
/**
* Calculate Rotation
*/
private function updateRotation():void
{
// calculate rotation
_dx = _player.x - _destinationX;
_dy = _player.y - _destinationY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > _player.rotation + 180) rotateTo -= 360;
if (rotateTo < _player.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - _player.rotation) / _rotateSpeedMax;
// update rotation
_player.rotation += _trueRotation;
}
/**
* Calculate Position
*/
private function updatePosition():void
{
// check if mouse is down
if (_isActive)
{
// update destination
_destinationX = stage.mouseX;
_destinationY = stage.mouseY;
// update velocity
_vx += (_destinationX - _player.x) / _moveSpeedMax;
_vy += (_destinationY - _player.y) / _moveSpeedMax;
}
else
{
// when mouse is not down, update velocity half of normal speed
_vx += (_destinationX - _player.x) / _moveSpeedMax * .25;
_vy += (_destinationY - _player.y) / _moveSpeedMax * .25;
}
// apply decay (drag)
_vx *= _decay;
_vy *= _decay;
// if close to target, slow down turn speed
if (getDistance(_dx, _dy) < 50)
{
_trueRotation *= .5;
}
// update position
_player.x += _vx;
_player.y += _vy;
}
/**
* Mouse DOWN handler
* #param e
*/
private function onMouseDownHandler(e:MouseEvent):void
{
_isActive = true;
}
/**
* Mouse UP handler
* #param e
*/
private function onMouseUpHandler(e:MouseEvent):void
{
_isActive = false;
}
/**
* Get distance
* #param delta_x
* #param delta_y
* #return
*/
public function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
/**
* Get radians
* #param delta_x
* #param delta_y
* #return
*/
public function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #param radians
* #return
*/
public function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
public function addasteroid() {
var newast:asteroid = new asteroid();
newast.x=Math.random()*950;
newast.y=Math.random()*200;
addChild(newast);
allast.push(newast);
}
} //don't code outside of here
}//end
Your problem come from using stage into your class without adding the class instance to the parent stage.
So your code should be like this :
...
public function Mainlv() {
this.addEventListener(Event.ADDED_TO_STAGE, init)
}
private function init(e:Event){
this.removeEventListener(Event.ADDED_TO_STAGE, init);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, onMouseUpHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, onMouseDownHandler);
stage.addEventListener(MouseEvent.CLICK, triggerbullet);
createPlayer()
}
...
And don't forget to add the Mainlv instance to parent stage :
import Mainlv
var m:Mainlv = new Mainlv()
addChild(m)
I tested this code and it works fine.

Error 1180 Call to possibly undefined method Bullet

I have a problem here and I have tried my best to figure out why I'm getting this error on Line 325. Here is the entire script. I'm using Flash CS5.5. Thank you for helping as I'm completely stuck. I changed the names of my movieClips but still the error persists. Thanks again.
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.getTimer;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.system.fscommand;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.display.SimpleButton;
var loader:Loader = new Loader();
var file:URLRequest = new URLRequest("vermin-ator.swf");
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteLoad);
loader.load(file);
function onCompleteLoad (loadEvent:Event):void
{
addChild(loadEvent.currentTarget.content);
}
// player settings
var _rotateSpeedMax:Number = 20;
//private var _gravity:Number = .68;
// projectile gun settings
var _bulletSpeed:Number = 8;
var _maxDistance:Number = 300;
var _reloadSpeed:Number = 250; //milliseconds
var _barrelLength:Number = 20;
var _bulletSpread:Number = 5;
var score:int = 0;
// gun stuff - do not edit
var _isLoaded:Boolean = true;
var _isFiring:Boolean = false;
var _endX:Number;
var _endY:Number;
var _startX:Number;
var _startY:Number;
var _reloadTimer:Timer;
var _bullets:Array = [];
// array that holds walls
//var _solidObjects:Array = [];
//array for rifle sounds
var mySoundArray:Array = [];
var mySoundRandom:Number;
//game scorings
//var myFormat:TextFormat = new TextFormat();
// myFormat.size = 20;
//var gameScoreField:TextField;
//var gameScore:int;
// gameScore = 0;
// var myText_txt:TextField = new TextField();
// global vars
var player:MovieClip;
//var _player2:MovieClip;
//var _player3:MovieClip;
var _dx:Number;
var _dy:Number;
var _pcos:Number;
var _psin:Number;
var _trueRotation:Number;
var count:Number;
var dougie:MovieClip;
var murphy:MovieClip;
var dougieTalk:MovieClip;
var murphyTalk:MovieClip;
var murphyScream:MovieClip;
var newRabbit:MovieClip;
var tempBullet:MovieClip;
var bullet_mc:MovieClip;
//how much time before another rabbit is made
var rabbitTime:int = 0;
//how much time is needed to make a rabbit
var rabbitLimit:int = 16;
//this movieclip holds the bullets
//var bulletContainer:MovieClip = new MovieClip();
//addChild(bulletContainer)
var soundOn:Boolean = true;
//var myTransform:SoundTransform;
//variable for rifle sound
var rifle1Sound:Sound = new rifle1sound();
//variable for rifle sound
var rifle2Sound:Sound = new rifle2sound();
//variable for rifle sound
var rifle3Sound:Sound = new rifle3sound();
//variable for rifle sound
var rifle4Sound:Sound = new rifle4sound();
//variable for man laughing
//var manLaughSound:Sound = new manlaughsound();
//variable for man laughing
//var manPleasedSound:Sound = new manpleasedsound();
//varible for background sound
var bckgroundSound:Sound = new bckgroundsound();
//varible for rabbit shot sound
//var rabbitSound:Sound = new rabbitsound();
//variable for button sound
var BtnSound:Sound = new buttonSound();
//make screen for Stop invisible
var stopScreen:MovieClip;
//make screen for Credits visible
var creditScreen:MovieClip;
//make screen for Rules visible
var rulesScreen:MovieClip;
murphyTalk.visible = true;
dougieTalk.visible = true;
dougie.visible = true;
murphy.visible = true;
murphyScream.visible = true;
creditScreen.visible = true;
rulesScreen.visible = true;
stopScreen.visible = false;
//enable hand cursors on mouse over over buttons
var movieClip_8:MovieClip;
var movieClip_9:MovieClip;
var movieClip_10:MovieClip;
var movieClip_11:MovieClip;
var newrabbit:MovieClip;
var closeGame:MovieClip;
//listener and function for how to play button
movieClip_10.addEventListener(MouseEvent.MOUSE_DOWN, helpScreen);
function helpScreen(evt:MouseEvent):void {
rulesScreen.visible=true;
}
//listener and function for how to play button
movieClip_9.addEventListener(MouseEvent.MOUSE_DOWN, ahelpScreen);
function ahelpScreen(evt:MouseEvent):void {
creditScreen.visible=true;
}
//Add event listeners for all 3 Over, Out and Down
movieClip_8.addEventListener(MouseEvent.MOUSE_OVER, mOver);
function mOver(e:MouseEvent):void {
murphyTalk.visible = false;
dougieTalk.visible = false;
dougie.visible = false;
murphy.visible = false;
murphyScream.visible= true;
}
movieClip_8.addEventListener(MouseEvent.MOUSE_OUT, mOut);
//Mouse methods
function mOut(e:MouseEvent):void {
murphyScream.visible= false;
removeChild(murphyTalk);
removeChild(dougieTalk);
removeChild(dougie);
removeChild(murphy);
//Remove all listeners
movieClip_8.removeEventListener(MouseEvent.MOUSE_OVER, mOver);
movieClip_8.removeEventListener(MouseEvent.MOUSE_OUT, mOut);
}
/**
* Constructor
*/
//public function Main()
/*recurring event listener for updates
addEventListener(Event.ENTER_FRAME,showGameScore);
function showGameScore() {
gameScoreField.text = "Game: "+String(gameScore);
addChild(gameScoreField); */
movieClip_8.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
function mDown(e:MouseEvent):void {
createPlayer();
// add listeners
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, `enter code here`onMouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
// add movieclips to solidObjects array
// will test for collisions with bullets
//
// *** movieclips are located on stage in the fla
//_solidObjects = [rabbit01, rabbit02, rabbit03, rabbit04];
//adding enemies to stage
if(rabbitTime < rabbitLimit){
//if time hasn't reached the limit, then just increment
rabbitTime ++;
} else {
//defining a variable which will hold the new enemy
//var newRabbit:MovieClip = new Rabbit();
//making the enemy offstage when it is created
newrabbit.s = -1 * newrabbit.width;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newrabbit.x = int(Math.random()*(stage.stageWidth - newrabbit.width));
//then add the enemy to stage
addChild(newrabbit);
//and reset the enemyTime
rabbitTime = 0;
}
//////////////////////////////////////
// Player & Weapon Methods
//////////////////////////////////////
/**
* Creates player
* Uses "Player" movieclip linked in library
*/
function createPlayer():void
{
// attach player movieclip from library
player = new Player();
// position player in center
player.x = stage.stageWidth / 2;
//_player.y = stage.stageHeight / 2;
// add to display list
stage.addChild(player);
}
/**
* Reload timer
* #param e Takes TimerEvent
*/
function reloadTimerHandler(e:TimerEvent):void
{
// stop timer
e.target.stop();
// clear timer var
_reloadTimer = null;
reloadWeapon();
}
/**
* Fire weapon
*/
function fire():void
{
// check if firing
if (!_isFiring) return;
// check if reloaded
if (!_isLoaded) return;
// create bullet
createBullet();
// start reload timer
_reloadTimer = new Timer(_reloadSpeed);
_reloadTimer.addEventListener(TimerEvent.TIMER, `enter code here`reloadTimerHandler);
_reloadTimer.start();
// set reload flag to false
_isLoaded = false;
}
/**
* Creates a bullet movieclip and sets it's properties
*/
function createBullet():void
{
// precalculate the cos & sine
_pcos = Math.cos(player.rotation * Math.PI / 180);
_psin = Math.sin(player.rotation * Math.PI / 180);
// start X & Y
// calculate the tip of the barrel
_startX = player.x - _barrelLength * _pcos;
_startY = player.y - _barrelLength * _psin;
// end X & Y
// calculate where the bullet needs to go
// aim 50 pixels in front of the gun
_endX = player.x - 50 * _pcos + Math.random() * _bulletSpread - `enter code here`_bulletSpread * .5;
_endY = player.y - 50 * _psin + Math.random() * _bulletSpread - `enter code here`_bulletSpread * .5;
// attach bullet from library
var tempBullets:MovieClip = new Bullet();
// calculate velocity
tempBullets.vx = (_endX - _startX) / _bulletSpeed;
tempBullets.vy = (_endY - _startY) / _bulletSpeed;
// set position
tempBullets.x = _startX;
tempBullets.y = _startY;
// save starting location
tempBullets.startX = _startX;
tempBullets.startY = _startY;
// set maximum allowed travel distance
tempBullets.maxDistance = _maxDistance;
// add bullet to bullets array
_bullets.push(tempBullets);
// add to display list
stage.addChild(tempBullets);
}
/**
* Updates bullets
*/
function updateBullets():void
{
var i:int;
var tempBullets:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullets = _bullets[i];
// check if gravity is enabled
//if (gravityCheckbox.selected)
//{
// add gravity to Y velocity
//tempBullet.vy += _gravity;
}
// update bullet position
tempBullets.x += tempBullets.vx;
tempBullets.y += tempBullets.vy;
// check if bullet went too far
if (getDistance(tempBullets.startX - tempBullets.x, `enter code here`tempBullets.startY - tempBullets.y) > tempBullets.maxDistance + `enter code here`_barrelLength)
{
destroyBullet(tempBullets);
}
// check for collision with walls
if (checkCollisions(tempBullets.x, tempBullets.y))
{
destroyBullet(tempBullets);
}
}
/**
* Destroys bullet
* #param bullet Takes bullet movieclip
*/
function destroyBullet(bullet_mc:MovieClip):void
{
var i:int;
var tempBullets:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullets = _bullets[i];
// if found bullet in array
if (tempBullets == bullet_mc)
{
// remove from array
_bullets.splice(i, 1);
// remove from display list
_bullets.removeChild(bullet_mc);
// stop loop
return;
}
}
}
/**
* Reload weapon
*/
function reloadWeapon():void
{
_isLoaded = true;
}
/**
* Checks for collisions between points and objects in _solidObjects
* #return Collision boolean
*/
function checkCollisions(testX:Number, testY:Number):Boolean
{
//var i:int;
var newrabbit:MovieClip;
// loop thru _solidObjects array
//for (i = 0; i < _solidObjects.length; i++)
{
// save a reference to current object
//newRabbit = _solidObjects[i];
// do a hit test
if (newrabbit.hitTestPoint(testX, testY, true))
{
return true;
// stop loop
//break;
}
}
return false;
}
/**checking if Rabbits is touching any bullets
for(var i:int = 0;i<_root.bulletContainer.numChildren;i++){
//numChildren is the amount of movieclips within the bulletContainer.
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:MovieClip = _root.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget)){
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
_root.removeChild(this);
//also remove the bullet and its listeners
_root.bulletContainer.removeChild(bulletTarget);
bulletTarget.removeListeners();
}
}*/
/**
* Calculate player rotation
*/
function updateRotation():void
{
// calculate rotation based on mouse X & Y
_dx = player.x - stage.mouseX;
_dy = player.y - stage.mouseY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > player.rotation + 90) rotateTo -= 180;
if (rotateTo < player.rotation - 90) rotateTo += 180;
// ease rotation
_trueRotation = (rotateTo - player.rotation) / _rotateSpeedMax;
// update rotation
player.rotation += _trueRotation;
}
//////////////////////////////////////
// Event Handlers
//////////////////////////////////////
/**
* Enter Frame handler
* #param event Uses Event
*/
function enterFrameHandler(event:Event):void
{
updateRotation();
updateBullets();
fire();
}
/**
* Mouse Up handler
* #param e Uses MouseEvent
*/
function onMouseUpHandler(event:MouseEvent):void
{
_isFiring = false;
//make bubble for Run Scream invisible
murphyScream.visible = false;
}
/**
* Mouse Down handler
* #param e Uses MouseEvent
*/
function onMouseDownHandler(event:MouseEvent):void
{
_isFiring = true;
//play random rifle sound from an array
var mySoundArray:Array = new Array(rifle1sound, rifle2sound, `enter code here`rifle3sound, rifle4sound);
`enter code here`mySoundArray[Math.floor(Math.random()*mySoundArray.length)].play();
}
//////////////////////////////////////
// Utilities
//////////////////////////////////////
/**
* Get distance
* #param delta_x
* #param delta_y
* #return
*/
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
/**
* Get radians
* #param delta_x
* #param delta_y
* #return
*/
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #param radians Takes radians
* #return Returns degrees
*/
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
movieClip_8.removeEventListener(MouseEvent.MOUSE_DOWN, mDown);
}
//listener and function for how to play button
movieClip_11.addEventListener(MouseEvent.MOUSE_DOWN, bhelpScreen);
function bhelpScreen(evt:MouseEvent):void {
stopScreen.visible=true;
}
closeGame.addEventListener(MouseEvent.MOUSE_DOWN, closeApp);
function closeApp(event:MouseEvent):void {
fscommand("quit");
}
Check that Bullet is also the class name on the library.

AS3 No keyboard input registering

so I want an object to orbit around another, but I want it to do it only when the right arrow key is pressed. When I run this program, the orbiter doesn't move at all, even when the right arrow key is pressed and it doesn't trace!
Any help is greatly appreciated!
PS Do I have to use an event listener with KEY_DOWN or can I return a number and check it?
var orbiter:Orbiter = new Orbiter();
var origin:Origin = new Origin();
var angle:Number = 0;
var speed:Number = 1.5;
var radius:Number = 75;
origin.x= 100;
origin.y =100;
addChild(orbiter);
addChild(origin);
stage.addEventListener(Event.ENTER_FRAME, Orbit_Brah);
function Orbit_Brah(event:Event):void
{
var nLeftOrRight = CheckKeyDown;
if (nLeftOrRight == 1)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
function CheckKeyDown(event:KeyboardEvent):int
{
if (event.keyCode == Keyboard.RIGHT)
{
trace ("Key Press Registered");
return 1;
}
return 0;
}
You will need to add a listener to fetch the info from the KeyboardEvents. Store the info in a variable and use it in your update loop. You may also want to use KeyboardEvent.KEY_UP to check when the keys are released as well. Something like this.
stage.addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyboardDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyboardUpHandler);
function Update(pEvent : Event) : void
{
// update code here using stored info
if(_isMovingRight)
{
//
}
}
function OnKeyboardDownHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = true;
break;
}
}
function OnKeyboardUpHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = false;
break;
}
}
You're trying too hard. All you need to do after your declarations is:
stage.addEventListener(KeyboardEvent.KEY_DOWN, Orbit_Brah);
function Orbit_Brah(e)
{
if (e.keyCode == Keyboard.RIGHT)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
That still leaves you with one little math problem, which will be obvious when you run the code, but you can take care of that.

Throwing a button in Flash / AS3

I'm trying to make a button draggable and also throw it across the screen. I know that I have to use the mouseDown and mouseUp options for the button, but could someone explain a method for allowing me to drag it and then throw it? In other words, it should keep going after mouseUp.
Thanks in advance for any advice that you can offer -
Chris
Funnily enough, I have an old class for this lying around. Just use the below as a base class for any object you want to be able to throw around:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* Use as a base class for objects to be grabbed and thrown with the mouse.
* #author Marty Wallace.
* #version 1.01.
*/
public class BouncingObject extends Sprite
{
// properties
public var yv:Number = 0;
public var xv:Number = 0;
private var _grabbed:Boolean = false;
private var _gy:int = 0;
private var _gx:int = 0;
private var _ox:int = 0;
private var _oy:int = 0;
protected var bounce:Number = 0.3;
protected var weight:Number = 3;
protected var friction:Number = 2;
/**
* Constructor
*/
public function BouncingObject()
{
addEventListener(Event.ADDED_TO_STAGE, _init);
}
/**
* Called on dispatch of Event.ADDED_TO_STAGE
* #param e Event.ADDED_TO_STAGE
*/
private function _init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
addEventListener(Event.ENTER_FRAME, _handle);
addEventListener(MouseEvent.MOUSE_DOWN, _handleClick);
addEventListener(MouseEvent.MOUSE_UP, _handleRelease);
addEventListener(MouseEvent.MOUSE_OUT, _handleRelease);
}
/**
* Called on dispatch of Event.ENTER_FRAME
* #param e Event.ENTER_FRAME
*/
private function _handle(e:Event):void
{
_ox = x;
_oy = y;
yv += weight;
if(_grabbed)
{
x = parent.mouseX - _gx;
y = parent.mouseY - _gy;
}
else
{
x += xv;
y += yv;
}
if(x < 0)
{
x = 0;
xv = -xv*bounce;
yv -= yv / friction;
}
if(x + width > stage.stageWidth)
{
x = stage.stageWidth - width;
xv = -xv*bounce;
yv -= yv / friction;
}
if(y < 0)
{
y = 0;
yv = -yv*bounce;
xv -= xv / friction;
}
if(y + height > stage.stageHeight)
{
y = stage.stageHeight - height;
yv = -yv*bounce;
xv -= xv / friction;
}
}
/**
* Called on dispatch of MouseEvent.MOUSE_DOWN
* #param e MouseEvent.MOUSE_DOWN
*/
private function _handleClick(e:MouseEvent):void
{
grabbed = true;
parent.addChild(this);
}
/**
* Called on dispatch of MouseEvent.MOUSE_UP
* #param e MouseEvent.MOUSE_UP
*/
private function _handleRelease(e:MouseEvent):void
{
grabbed = false;
}
/**
* Sets grabbed
* #param val Boolean representing value to set grabbed as
*/
protected function set grabbed(bool:Boolean):void
{
_grabbed = bool;
if(_grabbed)
{
_gx = mouseX;
_gy = mouseY;
}
else
{
xv = x - _ox;
yv = y - _oy;
}
}
/**
* Deconstructor - remove event listeners.
*/
public function deconstruct():void
{
removeEventListener(Event.ENTER_FRAME, _handle);
removeEventListener(MouseEvent.MOUSE_DOWN, _handleClick);
removeEventListener(MouseEvent.MOUSE_UP, _handleRelease);
removeEventListener(MouseEvent.MOUSE_OUT, _handleRelease);
}
}
}
Feel free to alter whatever you need, e.g. setting weight to 0 will prevent the object from falling down.

AS2 code to AS3 code help converting!

Help!!! This as2 code has given me a mind numbing headache. Can someone help me convert it to AS3. Here is the code:
import flash.filters.GlowFilter;
//Settings
var maxDist:Number = 400;
var accuracy:Number = 1;
//other vars (do not edit)
var dx:Number;
var dy:Number;
var startX:Number;
var startY:Number;
var endX:Number;
var endY:Number;
var realDist:Number;
var rad:Number = Math.PI/180;
var rad2:Number = 180/Math.PI;
map_mc.createEmptyMovieClip("laser_mc", map_mc.getNextHighestDepth());
//Glow Filter
var glow:GlowFilter = new GlowFilter();
glow.color = 0xFF0000;
glow.alpha = 1;
glow.blurX = 7;
glow.blurY = 7;
glow.quality = 2;
map_mc.laser_mc.filters = new Array(glow);
/**
*
* Mouse Controls
*
*/
//create an object that we'll listen to
mouseListener = new Object();
//on Click, fire the weapon
mouseListener.onMouseDown = function() {
fireWeapon();
}
//on release, stop weapon firing
mouseListener.onMouseUp = function() {
stopWeapon();
}
//on mouse move, rotate the player
mouseListener.onMouseMove = function() {
rotatePlayer();
}
//add listener
Mouse.addListener(mouseListener);
/**
*
* Laser Weapon
*
*/
//fire weapon function - creates an onEnterFrame function to repeat updateLaser() over and over
function fireWeapon():Void
{
_root.onEnterFrame = function ():Void {
updateLaser();
}
}
//stop weapon function - deletes onEnterFrame and clears laser movieclip
function stopWeapon():Void
{
delete _root.onEnterFrame;
map_mc.laser_mc/**/.clear();
}
//Update Laser Function
function updateLaser() :Void
{
//run a loop
for (realDist=0; realDist<maxDist; realDist += accuracy)
{
//get end X&Y
endX = map_mc.player_mc._x + Math.cos(map_mc.player_mc._rotation * rad) * realDist;
endY = map_mc.player_mc._y + Math.sin(map_mc.player_mc._rotation * rad) * realDist;
//calculate hit test
if (map_mc.walls_mc.hitTest(endX, endY, true)) {
break;
}
}
//calculate the tip of the barrel (start X & Y)
startX = map_mc.player_mc._x + 15 * Math.cos(map_mc.player_mc._rotation * rad);
startY = map_mc.player_mc._y + 15 * Math.sin(map_mc.player_mc._rotation * rad);
// Clear it before we draw, so the line doesnt stay there
map_mc.laser_mc.clear();
//draw laser
map_mc.laser_mc.lineStyle(2, 0xFF0000, 75);
map_mc.laser_mc.moveTo(startX, startY);
map_mc.laser_mc.lineTo(endX, endY);
}
//rorate player towards mouse function
function rotatePlayer():Void
{
//get distance between mouse and player
dx = map_mc._xmouse-map_mc.player_mc._x;
dy = map_mc._ymouse-map_mc.player_mc._y;
//calculate rotation of player
map_mc.player_mc._rotation = Math.atan2(dy, dx)*rad2;
}
THX
Here is the bulk of it
You shouldn't get compile errors now
Plus I cleaned it up
You will also have to fix your rotation point of player_mc
import flash.filters.GlowFilter;
//Settings
var maxDist:Number = 400;
var accuracy:Number = 1;
//other vars (do not edit)
var dx:Number;
var dy:Number;
var startX:Number;
var startY:Number;
var endX:Number;
var endY:Number;
var realDist:Number;
var rad:Number = Math.PI/180;
var rad2:Number = 180/Math.PI;
var laser_mc:MovieClip = new MovieClip()
map_mc.addChild(laser_mc)
//Glow Filter
var glow:GlowFilter = new GlowFilter();
glow.color = 0xFF0000;
glow.alpha = 1;
glow.blurX = 7;
glow.blurY = 7;
glow.quality = 2;
laser_mc.filters = new Array(glow);
/**
*
* Mouse Controls
*
*/
stage.addEventListener( MouseEvent.MOUSE_DOWN, fire);
//on Click, fire the weapon
function fire( e:Event ):void {
stage.addEventListener( Event.ENTER_FRAME , updateLaser)
}
stage.addEventListener( MouseEvent.MOUSE_UP, stopFire);
//on release, stop weapon firing
function stopFire( e:Event ):void {
laser_mc.graphics.clear();
stage.removeEventListener( Event.ENTER_FRAME , updateLaser)
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved)
//on mouse move, rotate the player
function mouseMoved( e:Event ):void {
//get distance between mouse and player
dx = map_mc.mouseX-map_mc.player_mc.x;
dy = map_mc.mouseY-map_mc.player_mc.y;
//calculate rotation of player
map_mc.player_mc.rotation = Math.atan2(dy, dx)*rad2;
}
//Update Laser Function
function updateLaser( e:Event ):void {
//run a loop
for (realDist=0; realDist<maxDist; realDist += accuracy){
//get end X&Y
endX = map_mc.player_mc.x + Math.cos(map_mc.player_mc.rotation * rad) * realDist;
endY = map_mc.player_mc.y + Math.sin(map_mc.player_mc.rotation * rad) * realDist;
//calculate hit test
if (map_mc.walls_mc.hitTestPoint(endX,endY)) {
break;
}
}
//calculate the tip of the barrel (start X & Y)
startX = map_mc.player_mc.x + 15 * Math.cos(map_mc.player_mc.rotation * rad);
startY = map_mc.player_mc.y + 15 * Math.sin(map_mc.player_mc.rotation * rad);
//draw laser
laser_mc.graphics.clear();
laser_mc.graphics.lineStyle(2, 0xFF0000);
laser_mc.graphics.moveTo(startX, startY);
laser_mc.graphics.lineTo(endX, endY);
}