Variables and Responses between layers AS3 - actionscript-3

I'm having a slight problem in a current project... i have an object, that when clicked activates a function, which hides several objects and changes a variable. The changing of said variable should then cause an object on another layer to appear, but all that happens is the objects disappear, but the other one doesn't appear... The code for the first layer is as follows.... The function in question is the last one...
import flash.events.Event;
import flash.system.fscommand;
import flash.events.MouseEvent;
stage.displayState = StageDisplayState.FULL_SCREEN;
var GameMode:Number=0;//Variable Setup
var Planet:Number=0;//
swslogo.alpha = .0;//Game Menu
voidlogomenu.alpha = .0;
newgame.alpha = .0;
loadgame.alpha = .0;
exitgame.alpha = .0;
yes.alpha = .0;
no.alpha = .0;
exitprompt.alpha = .0;
MenuExitFade.alpha = .0;
SwsLogoCorner.alpha = .0;
var IntroTimer = new Timer(3000,1); //add a 3 second timer
var QuitTimer = new Timer(1000,1); //add a 1 second timer
var IntroTimer2 = new Timer(5000,1); //add a 5 second timer
IntroTimer.addEventListener(TimerEvent.TIMER_COMPLETE,swsfadein);
intro();
function intro():void
{
IntroTimer.reset()
IntroTimer.start();
for (var i:int = 0; i < 50; i++)
{
var aStar:DisplayObject = new stars;
MenuSpawner.addChild(aStar);
}
for (var i:int = 0; i < 50; i++)
{
var aStarDust:DisplayObject = new Stardust;
MenuSpawner.addChild(aStarDust);
}
}
function swsfadein(e:Event=null):void
{
IntroTimer.stop();
IntroTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,swsfadein);
swslogo.addEventListener(Event.ENTER_FRAME, fadeinsws)
}
function fadeinsws(e:Event=null){
if(swslogo.alpha >= 1){
swslogo.removeEventListener(Event.ENTER_FRAME, fadeinsws);
IntroTimer2.addEventListener(TimerEvent.TIMER_COMPLETE,swsfadeout);
IntroTimer2.reset()
IntroTimer2.start();
} else {
swslogo.alpha +=0.1;
}
}
function swsfadeout(e:Event=null):void
{
IntroTimer2.stop();
IntroTimer2.removeEventListener(TimerEvent.TIMER_COMPLETE,swsfadeout);
swslogo.addEventListener(Event.ENTER_FRAME, fadeoutsws)
}
function fadeoutsws(e:Event=null){
if(swslogo.alpha <=0){
swslogo.removeEventListener(Event.ENTER_FRAME, fadeoutsws);
IntroTimer.addEventListener(TimerEvent.TIMER_COMPLETE,voidfadein);
IntroTimer.reset()
IntroTimer.start()
} else {
swslogo.alpha -=0.1;
}
}
function voidfadein(e:Event=null):void
{
IntroTimer.stop();
IntroTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,voidfadein);
voidlogomenu.addEventListener(Event.ENTER_FRAME, fadeinvoid)
}
function fadeinvoid(e:Event=null){
if(voidlogomenu.alpha >= 1){
voidlogomenu.removeEventListener(Event.ENTER_FRAME, fadeinvoid);
IntroTimer2.addEventListener(TimerEvent.TIMER_COMPLETE,menufadein);
IntroTimer2.reset()
IntroTimer2.start();
} else {
voidlogomenu.alpha +=0.1;
}
}
function menufadein(e:Event=null):void
{
IntroTimer2.stop();
IntroTimer2.removeEventListener(TimerEvent.TIMER_COMPLETE,menufadein);
newgame.addEventListener(Event.ENTER_FRAME, fadeinnewgame);
loadgame.addEventListener(Event.ENTER_FRAME, fadeinloadgame);
exitgame.addEventListener(Event.ENTER_FRAME, fadeinexitgame);
SwsLogoCorner.addEventListener(Event.ENTER_FRAME, fadeinswslogocorner)
}
function fadeinnewgame(e:Event=null){
if(newgame.alpha >= 1){
newgame.addEventListener(MouseEvent.CLICK, newgameclicked);
newgame.removeEventListener(Event.ENTER_FRAME, fadeinnewgame);
} else {
newgame.alpha +=0.1;
}
}
function fadeinloadgame(e:Event=null){
if(loadgame.alpha >= 1){
loadgame.addEventListener(MouseEvent.CLICK, loadgameclicked);
loadgame.removeEventListener(Event.ENTER_FRAME, fadeinloadgame);
} else {
loadgame.alpha +=0.1;
}
}
function fadeinexitgame(e:Event=null){
if(exitgame.alpha >= 1){
exitgame.addEventListener(MouseEvent.CLICK, exitgameclicked)
exitgame.removeEventListener(Event.ENTER_FRAME, fadeinexitgame);
} else {
exitgame.alpha +=0.1;
}
}
function fadeinswslogocorner(e:Event=null){
if(SwsLogoCorner.alpha >= 1){
SwsLogoCorner.removeEventListener(Event.ENTER_FRAME, fadeinswslogocorner);
} else {
SwsLogoCorner.alpha +=0.1;
}
}
function newgameclicked(e:MouseEvent):void
{
yesnofadein();
exitprompt.addEventListener(Event.ENTER_FRAME, exitpromptfadein)
exitprompt.gotoAndStop(2)
yes.addEventListener(MouseEvent.CLICK, createnewgame)
removemenufunctions();
}
function loadgameclicked(e:MouseEvent):void
{
removemenufunctions();
}
function exitgameclicked(e:MouseEvent)
{
yesnofadein();
exitprompt.addEventListener(Event.ENTER_FRAME, exitpromptfadein)
exitprompt.gotoAndStop(1)
yes.addEventListener(MouseEvent.CLICK, exit)
removemenufunctions();
}
function exitpromptfadein(e:Event=null){
if(exitprompt.alpha >= 1){
no.addEventListener(MouseEvent.CLICK, exitpromptfadeout)
exitprompt.removeEventListener(Event.ENTER_FRAME, exitpromptfadein);
} else {
exitprompt.alpha +=0.1;
}
}
function exitpromptfadeout(e:Event=null):void
{
no.removeEventListener(MouseEvent.CLICK, exitpromptfadeout)
exitprompt.addEventListener(Event.ENTER_FRAME, fadeoutexitprompt);
}
function fadeoutexitprompt(e:Event=null){
if(exitprompt.alpha <=0){
exitprompt.removeEventListener(Event.ENTER_FRAME, fadeoutexitprompt);
} else {
exitprompt.alpha -=0.1;
}
}
function yesnofadein():void
{
yes.addEventListener(Event.ENTER_FRAME, fadeinyes)
no.addEventListener(Event.ENTER_FRAME, fadeinno)
}
function fadeinyes(e:Event=null){
if(yes.alpha >= 1){
yes.removeEventListener(Event.ENTER_FRAME, fadeinyes);
} else {
yes.alpha +=0.1;
}
}
function fadeinno(e:Event=null){
if(no.alpha >= 1){
no.addEventListener(MouseEvent.CLICK, replacemenufunctions)
no.addEventListener(MouseEvent.CLICK, yesnofadeout)
no.removeEventListener(Event.ENTER_FRAME, fadeinno);
} else {
no.alpha +=0.1;
}
}
function yesnofadeout(e:MouseEvent):void
{
yes.removeEventListener(MouseEvent.CLICK, exit)
yes.removeEventListener(MouseEvent.CLICK, createnewgame)
yes.addEventListener(Event.ENTER_FRAME, fadeoutyes)
no.addEventListener(Event.ENTER_FRAME, fadeoutno)
no.removeEventListener(MouseEvent.CLICK, yesnofadeout)
}
function fadeoutyes(e:Event=null){
if(yes.alpha <=0){
yes.removeEventListener(Event.ENTER_FRAME, fadeoutyes);
} else {
yes.alpha -=0.1;
}
}
function fadeoutno(e:Event=null){
if(no.alpha <=0){
no.removeEventListener(Event.ENTER_FRAME, fadeoutno);
} else {
no.alpha -=0.1;
}
}
function removemenufunctions():void
{
exitgame.removeEventListener(MouseEvent.CLICK, exitgameclicked);
loadgame.removeEventListener(MouseEvent.CLICK, loadgameclicked);
newgame.removeEventListener(MouseEvent.CLICK, newgameclicked);
}
function replacemenufunctions(e:Event=null):void
{
exitgame.addEventListener(MouseEvent.CLICK, exitgameclicked);
loadgame.addEventListener(MouseEvent.CLICK, loadgameclicked);
newgame.addEventListener(MouseEvent.CLICK, newgameclicked);
}
function exit(e:MouseEvent)
{
MenuExitFade.x = -35;
MenuExitFade.y = 0;
MenuExitFade.addEventListener(Event.ENTER_FRAME, exitblackfade);
}
function exitblackfade(e:Event)
{
if(MenuExitFade.alpha >= 1){
MenuExitFade.removeEventListener(Event.ENTER_FRAME, exitblackfade);
QuitTimer.addEventListener(TimerEvent.TIMER_COMPLETE,forceclose);
QuitTimer.reset()
QuitTimer.start();
} else {
MenuExitFade.alpha +=0.1;
}
}
function forceclose(e:Event)
{
QuitTimer.stop();
QuitTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,forceclose);
fscommand('quit');
}
function createnewgame(e:MouseEvent)
{
var GameMode=1;
var Planet=1;
MenuSpawner.alpha=0
newgame.alpha=0
loadgame.alpha=0
exitgame.alpha=0
voidlogomenu.alpha=0
yes.alpha=0
no.alpha=0
exitprompt.alpha=0
SwsLogoCorner.alpha=0
yes.removeEventListener(MouseEvent.CLICK, createnewgame)
no.removeEventListener(MouseEvent.CLICK, yesnofadeout)
}
the code for the second is as follows
import flash.events.Event;
import flash.system.fscommand;
import flash.events.MouseEvent;
setupplanet();
Foreground.alpha=0
function setupplanet():void
{
Foreground.addEventListener(Event.ENTER_FRAME, PlanetLoop)
}
function PlanetLoop(e:Event=null):void
{
if(GameMode==0){
Foreground.alpha=0
} else {
Foreground.alpha=1
}
Foreground.gotoAndStop(1)
}
thanks...

The problem is here:
function createnewgame(e:MouseEvent)
{
var GameMode=1;
You want this variable to be "global", yet you declare it as a function local variable, thus it does not exist anywhere but inside the function at the moment the function executes.
Should be at least:
// Declared in the frame, should be visible
// to ALL frame functions on the same timeline.
var GameMode;
function createnewgame(e:MouseEvent)
{
GameMode=1;

Related

Does bitmapdata.copyPixels reduce image quality?

I am using a pair of classes to process and use Sprite Sheets but i have a slight problem, in comparison to the Bitmap class my SpriteSheetClips look very ugly, I scale both, Bitmap and SpriteSheetClip up and down using exactly the same image loaded and they look very different Bitmap looks smooth and nice while my SpriteSheetClips look pixelated with white borders, what is wrong with my classes that is causing this problem?
SpriteSheet (contains the cut bitmapDatas to be used for the clip):
package src {
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;
public class SpriteSheet {
private var frames:Array = new Array();
public function SpriteSheet(spriteSheet:BitmapData, spriteSheetXML:XML)
{
var tileAmount:int = spriteSheetXML.SubTexture.length();
var rect:Rectangle;
var point:Point = new Point(0, 0);
var frame:BitmapData;
for (var a:int = 0; a < tileAmount ; a++)
{
frame = new BitmapData(spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
rect = new Rectangle(spriteSheetXML.SubTexture[a].#x, spriteSheetXML.SubTexture[a].#y, spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
frame.copyPixels(spriteSheet, rect, point);
frames.push(frame);
}
}
public function getTile(tileNum:int):BitmapData
{
return frames[tileNum-1];
}
public function get length():int
{
return frames.length;
}
}
}
SpriteSheetClip:
package src {
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
public class SpriteSheetClip extends Sprite{
private var spriteSheet:SpriteSheet;
public var frame:Bitmap;
private var _currentFrame:int = 1;
private var _isPlaying:Boolean = true;
public var isLooping:Boolean = true;
private var frames:Array = new Array();
public function SpriteSheetClip(spriteSheetUsed:SpriteSheet)
{
spriteSheet = spriteSheetUsed;
frame = new Bitmap(spriteSheet.getTile(1), "auto", true);
this.addChild(frame);
for (var a:int = 0; a < totalFrames; a++)
{
frames.push({labelName:"", action:""});
}
this.addEventListener(Event.ENTER_FRAME, onFrameLoop, false, 0, true);
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get totalFrames():int
{
return spriteSheet.length;
}
public function get isPlaying():Boolean
{
return _isPlaying;
}
public function start()
{
_isPlaying = true;
}
public function stop()
{
_isPlaying = false;
}
public function addFrameLabel(frameNum:int, labelName:String)
{
if (frameNum == 0)
{
return;
}
frames[frameNum-1].frameLabel = labelName;
}
public function addConnection(frameLabel:*, connectedFrameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum == 0)
{
return;
}
frames[frameNum-1].action = connectedFrameLabel;
}
private function frameNumber(frameLabel:*):int
{
if (int(frameLabel) <= totalFrames && int(frameLabel) > 0)
{
return int(frameLabel);
}
for (var a:int = 0; a < frames.length; a++)
{
if (frames[a].frameLabel == frameLabel)
{
return (a+1);
}
}
return 0;
}
public function gotoAndStop(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
stop();
}
public function gotoAndPlay(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
start();
}
private function updateFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
}
public function nextFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
if (frames[currentFrame-1].action != "")
{
this.gotoAndPlay(frames[currentFrame-1].action);
return;
}
_currentFrame++;
if (currentFrame > totalFrames)
{
if (isLooping)
{
_currentFrame = 1;
}
else
{
_currentFrame = totalFrames;
_isPlaying = false;
}
}
}
private function onFrameLoop(e:Event)
{
if (isPlaying)
{
nextFrame();
}
}
}
}

Remove timer event listener

so I need to remove a timer event. But the problem is, It's in another function so I can't access it.
Here's how my code goes:
-There is a Boss
-It generates bomb
-Bomb lasts for a couple of seconds before exploding (no error)
-Bomb can be removed by clicking. (generates error)
If the bomb was removed via clicking, there will be error because the time event wasn't remove. But like I said, I can't remove it because it's in another function. Help!
import flash.events.Event;
import flash.display.MovieClip;
var boss:MovieClip = new darklord();
this.addChild(boss);
boss.x = stage.stageWidth / 2;
boss.y = stage.stageHeight / 2;
var lives:int = 3;
var maxHP:int = 2000;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
var bombcontainer:Array = [];
var timecontainer:Array = [];
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
boss.addEventListener(MouseEvent.CLICK, TapBoss);
boss.addEventListener(Event.ENTER_FRAME, MoveBoss);
function TapBoss(e:MouseEvent):void
{
currentHP -= 10;
if (currentHP <= 0)
{
currentHP = 0;
trace("You win!");
}
updateHealthBar();
}
var timerBoss:Timer = new Timer(1000,60);
timerBoss.addEventListener(TimerEvent.TIMER, bosstimerhandler);
timerBoss.start();
var secondsBoss:Number = 0;
function bosstimerhandler(event:TimerEvent)
{
//trace("Seconds elapsed: " + seconds);
//SpawnNote(null);
if (secondsBoss%5==0)
{
RandomCoord(null);
BossAttack(null);
}
secondsBoss++;
}
var HighH:int = stage.stageHeight;
var HighW:int = stage.stageWidth;
var LowH:int = 0;
var LowW:int = 0;
var destinationX:int;
var destinationY:int;
function RandomCoord(event:Event):void
{
destinationX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
destinationY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (destinationX <= 50)
{
destinationX += 50;
}
if (destinationY <= 50)
{
destinationY += 50;
}
if (destinationX + 50 >= stage.stageWidth)
{
destinationX -= 50;
}
if (destinationY + 50 >= stage.stageHeight)
{
destinationY -= 50;
}
trace("X is: ", destinationX);
trace("Y is: ", destinationY);
}
function MoveBoss(event:Event):void
{
if (boss.x < destinationX)
{
boss.x += 1;
}
else if (boss.x > destinationX)
{
boss.x -= 1;
}
if (boss.y < destinationY)
{
boss.y += 1;
}
else if (boss.y > destinationY)
{
boss.y -= 1;
}
}
function BossAttack(event:Event):void
{
var boom:MovieClip = new Bomb();
this.addChild(boom);
bombcontainer.push(boom);
boom.x = boss.x;
boom.y = boss.y;
BombCoord(null);
boom.addEventListener(Event.ENTER_FRAME, MoveBomb);
boom.addEventListener(MouseEvent.CLICK, TapBomb(boom));
BombTimer(boom);
}
function BombTimer(boom:MovieClip):void
{
var time:Timer = new Timer(1000,30);
timecontainer.push(time);
time.addEventListener(TimerEvent.TIMER, TimeHandler);
time.start();
var t:Number = 1;
function TimeHandler(event:TimerEvent):void
{
trace("Seconds elapsed: " + t);
t++;
if (t==12)
{
lives--;
trace("You lost a life!");
time.removeEventListener(TimerEvent.TIMER, TimeHandler);
RemoveBomb(boom, 0);
}
}
}
function RemoveBomb(boom:DisplayObject, bid:int):void
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
//boom.removeEventListener(MouseEvent.CLICK, TapBomb(boom));
bombcontainer.splice(bid, 1);
trace("Bomb # :" +bid+" is popped.");
this.removeChild(boom);
}
var BombX:int;
var BombY:int;
function BombCoord(event:Event):void
{
BombX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
BombY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (BombX <= 50)
{
BombX += 50;
}
if (BombY <= 50)
{
BombY += 50;
}
if (BombX + 50 >= stage.stageWidth)
{
BombX -= 50;
}
if (BombY + 50 >= stage.stageHeight)
{
BombY -= 50;
}
}
function MoveBomb(event:Event):void
{
var boom:DisplayObject = event.target as DisplayObject;
var fl_TimerInstance:Timer = new Timer(1000,6);
fl_TimerInstance.addEventListener(TimerEvent.TIMER, fl_TimerHandler);
fl_TimerInstance.start();
var fl_SecondsElapsed:Number = 1;
function fl_TimerHandler(event:TimerEvent):void
{
//trace("Seconds elapsed: " + fl_SecondsElapsed);
fl_SecondsElapsed++;
if (fl_SecondsElapsed==4)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.x < BombX)
{
boom.x += 5;
//boom.x +=5;
}
else if (boom.x > BombX)
{
boom.x -= 5;
}//boom.x -=5;
if (boom.y < BombY)
{
boom.y += 5;
//boom.x +=5;
}
else if (boom.y > BombY)
{
boom.y -= 5;
}
if (boom.x == BombX)
{
if (boom.y == BombY)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.y == BombY)
{
if (boom.x == BombX)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
}
function TapBomb(boom:MovieClip):Function
{
return function(e:MouseEvent):void {
var BombIndex:int = bombcontainer.indexOf(boom);
trace("You clicked the bomb at index " + BombIndex);
RemoveBomb(boom, BombIndex);
}
}
It's not that bad having a frame event listener on each bomb, unless perhaps you have hundreds of bombs at the same time.
You can solve the issue by making the Bomb a separate class that has its own handlers and timer. Something like this (not tested):
package {
import flash.display.*;
import flash.net.*;
import flash.utils.Timer;
public class Bomb extends MovieClip {
private var myTimer:Timer;
public function Bomb() {
myTimer = new Timer(1000,30);
myTimer.addEventListener(TimerEvent.TIMER, TimeHandler);
myTimer.start();
}
private function TimeHandler(event:TimerEvent):void {
// check the time
}
public function stopTicking():void {
this.myTimer.stop();
}
}
}
You can then create all the bombs you want and kill their timers by calling their method:
// create a bomb movieclip and add it to the displaylist
var myBomb = new Bomb();
bombContainer.addChild(myBomb);
// use the displaylist to keep track of nonexploded bombs
var someBomb = bombContainer.getChildAt(0);
// stop the timer on this bomb
someBomb.stopTicking();

How to detect if a player is on a platform

I am making a basic platform game using as3, and am trying to find a way to detect if my player is on the platform so I can allow him to jump if he is on it, but not be able to jump if he's off the platform.Here is my code:
package {
import flash.display.MovieClip
import flash.events.Event
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
var _vx = 0
var _vy = 0
var _ay = 0.5
var _isOnGround:Boolean
var canJump:Boolean
var _collisionArea:MovieClip
// Constants:
// Public Properties:
// Private Properties:
// Initialization:
public function Main()
{
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp)
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
_vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
_vx = 5;
}
else if (event.keyCode == Keyboard.UP )
{
if (canJump)
{
_vy = -10
}
}
}
function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
_vx = 0;
}
else if (event.keyCode == Keyboard.RIGHT)
{
_vx = 0;
}
}
public function onEnterFrame(event:Event):void
{
if(player1.isOnGround)
{
canJump=true
}
else if (!player1.isOnGround)
{
canJump=false
}
if (_vy > 10)
{
_vy = 10
}
player1.y += _vy
player1.x += _vx
vy += _ay
//Player vs wall collision
for (var i:int = 0; i <= 4; i++)
{
CollisionB.platform_BlockRectangles(player1, this["wall" + i]);
//trace("wall" + i);
}
}
public function set vx(vxValue:Number):void
{
_vx = vxValue;
}
public function get vx():Number
{
return _vx;
}
public function set vy(vyValue:Number):void
{
_vy = vyValue;
}
public function get vy():Number
{
return _vy;
}
public function get isOnGround():Boolean
{
return _isOnGround;
}
public function set isOnGround(onGround:Boolean):void
{
_isOnGround = onGround;
}
public function get collisionArea():MovieClip
{
return _collisionArea;
}
}
}
Im also using another class where the code is:
static public function platform_BlockRectangles(objectA:Object,objectB:Object):void
{
//This function requires the following setter properties in objectA:
// _objectIsOnGround:Boolean, vx:Number, vy:Number
var objectA_Halfwidth=objectA.width/2;
var objectA_Halfheight=objectA.height/2;
var objectB_Halfwidth=objectB.width/2;
var objectB_Halfheight=objectB.height/2;
var dx=objectB.x-objectA.x;
var ox=objectB_Halfwidth+objectA_Halfwidth-Math.abs(dx);
if (0<ox)
{
var dy=objectA.y-objectB.y;
var oy=objectB_Halfheight+objectA_Halfheight-Math.abs(dy);
if (0<oy)
{
if (ox<oy)
{
if (dx<0)
{
ox*=-1;
oy=0;
}
else
{
oy=0;
}
//Dampen horizontal velocity
objectA.vx=0;
}
else
{
if (dy<0)
{
ox=0;
oy*=-1;
objectA.isOnGround=true;
}
else
{
ox=0
}
//Dampen vertical velocity
objectA.vy=0;
}
objectA.x-=ox;
objectA.y+=oy;
}
}
}
Someone please help!!!!!!!
I extremely recommend you to use some library like: Flixel, Citrus
Try to follow this tutorial, will explain all necessary logic to help you with your game
You can use AABB collision detection. Here is a tutorial (the Distance function part).
If you google the term you will get a lot of info in the subject.
But i recomend you to use flixel or flashPunk is you are just starting and want to do games, they take care of these stuff for you and you can get to just make the game.

AS3: TypeError: Error #1009: Cannot access a property or method of a null object reference. Help Needed

I'm new to ActionScript and I really need help debugging this problem. This is what it says on my output when I run my code:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at StreetHobogame_fla::MainTimeline/pickup()
at StreetHobogame_fla::MainTimeline/gameloop()
And this is my code:
import flash.events.KeyboardEvent;
stop();
guy.stop();
var enemySpeed:Number = 3;
var wspeed:Number = 0;
var vy:Number = 0;
var gv:Number = 1;
var jumped:Boolean = false;
var score:Number = 0;
var lives:Number = 5;
livesbox.text = lives.toString();
stage.addEventListener(Event.ENTER_FRAME,gameloop);
trace(ground.x);
var motionspeed:int = 30;
left.addEventListener(MouseEvent.MOUSE_DOWN, leftMove);
left.addEventListener(MouseEvent.MOUSE_UP, leftUp);
right.addEventListener(MouseEvent.MOUSE_DOWN, rightMove);
right.addEventListener(MouseEvent.MOUSE_UP, rightUp);
jumpButton.addEventListener(MouseEvent.MOUSE_DOWN, jumpPressed);
function jumpPressed(e:Event):void
{
if (! jumped)
{
vy = -14;
jumped = true;
}
}
function rightUp(e:Event):void
{
wspeed = 0;
}
function rightMove(e:Event):void
{
wspeed += 10;
guy.gotoAndStop(2);
}
function leftMove(event:Event):void
{
wspeed = -10;
guy.gotoAndStop(1);
}
function leftUp(event:Event):void
{
wspeed = 0;
}
function gameloop(e:Event)
{
moveplayer();
jumpgravity();
exitlevel1();
//exitlevel2();
pickup();
enemy();
spikes();
enemyMove();
return (0);
}
function pickup()
{
if (guy.hitTestObject(key))
{
key.visible = false;
}
if (guy.hitTestObject(coin1))
{
coin1.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin2))
{
coin2.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin3))
{
coin3.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin4))
{
coin4.x = 2000;
score++;
scorebox.text = score.toString();
}
}
function moveplayer()
{
guy.x += wspeed;
if (guy.x < 0)
{
guy.x = 0;
}
if (guy.x > 1024)
{
guy.x = 1024;
}
}
function jumpgravity()
{
vy += gv;
if (! ground.hitTestPoint(guy.x,guy.y,true))
{
guy.y += vy;
}
if (ground.hitTestPoint(guy.x,guy.y,true))
{
guy.y--;
vy = 0;
jumped = false;
}
}
function exitlevel1()
{
if (guy.hitTestObject(exitMC))
{
if (key.visible == false)
{
stage.removeEventListener(Event.ENTER_FRAME,gameloop);
left.removeEventListener(MouseEvent.MOUSE_DOWN, leftMove);
left.removeEventListener(MouseEvent.MOUSE_UP, leftUp);
right.removeEventListener(MouseEvent.MOUSE_DOWN, rightMove);
right.removeEventListener(MouseEvent.MOUSE_UP, rightUp);
jumped= false;
wspeed = 0;
guy.gotoAndStop(1);
gotoAndStop(1,"level1Questions");
}
}
}
/*function exitlevel2()
{
if (guy.hitTestObject(exit2MC))
{
if (key.visible == false)
{
jumped= false;
wspeed = 0;
guy.gotoAndStop(1);
gotoAndStop(1,"level2Complete");
}
}
}
*/
function enemy()
{
if (guy.hitTestObject(enemy1))
{
guy.x = 520.95;
guy.y = 425.50;
if (lives<=1)
{
lives = 0;
gotoAndStop(1,"GameOver");
}
else
{
lives--;
livesbox.text = lives.toString();
}
}
}
function spikes()
{
if (guy.hitTestObject(Spike))
{
guy.x = 520;
guy.y = 425.5;
if (lives<=1)
{
lives = 0;
gotoAndStop(1,"GameOver");
}
else
{
lives--;
livesbox.text = lives.toString();
}
}
}
function enemyMove():void
{
enemy1.x += enemySpeed;
if (enemy1.x >= 350)
{
enemySpeed *= -1;
enemy1.scaleX *= -1;
}
else if (enemy1.x < 60)
{
enemySpeed *= -1;
enemy1.scaleX *= -1;
}
}
Help would be much appreciated, thank you.
At least one of this variables are null when pickup() function executes:
guy
key
coin1
scorebox
coin2
coin3
coin4
You can use trace() function to check which one.
function pickup()
{
trace('guy==' + guy);
trace('key==' + key);
trace('scorebox==' + scorebox);
trace('coin1==' + coin1);
trace('coin2==' + coin2);
trace('coin3==' + coin3);
trace('coin4==' + coin4);
if (guy.hitTestObject(key))
{
key.visible = false;
}
if (guy.hitTestObject(coin1))
{
coin1.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin2))
{
coin2.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin3))
{
coin3.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin4))
{
coin4.x = 2000;
score++;
scorebox.text = score.toString();
}
}

Convert ActionScript 2.0 code to ActionScript 3.0

I currently follow a flash tutorial online to create an interactive sketchpad. The link to tutorial is http://flashexplained.com/actionscript/making-an-interactive-drawing-sketchpad/.
The only problem with this tutorial is that the code is for actionscript 2.0 instead of 3.0. I know how to redefine the variables but besides that I am clueless, so I was hoping that someone can help me convert the code to ActionScript 3.0.
Here is the ActionScript 2.0 code:
lineThickness = 0;
selectedColor = "0x000000";
_root.onMouseDown = startDrawing;
_root.onMouseUp = stopDrawing;
function startDrawing()
{
if(_xmouse < 455)
{
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
_root.onMouseMove = drawLine;
}
}
function drawLine()
{
_root.lineTo(this._xmouse, this._ymouse);
}
function stopDrawing()
{
delete this.onMouseMove;
}
line0.onPress = function()
{
lineThickness = 0;
}
line3.onPress = function()
{
lineThickness = 3;
}
line6.onPress = function()
{
lineThickness = 6;
}
colorRed.onPress = function()
{
selectedColor = "0xFF0000";
}
colorGreen.onPress = function()
{
selectedColor = "0x00FF00";
}
AS2:
lineThickness = 0;
selectedColor = "0x000000";
AS3:
var lineThickness:int = 0;
var selectColor:uint = 0x000000;
AS2:
_root.onMouseDown = startDrawing;
_root.onMouseUp = stopDrawing;
function startDrawing()
{
if(_xmouse < 455)
{
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
_root.onMouseMove = drawLine;
}
}
function stopDrawing()
{
delete this.onMouseMove;
}
function drawLine()
{
_root.lineTo(this._xmouse, this._ymouse);
}
AS3:
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
function startDrawing(e:MouseEvent):void
{
if(mouseX < 455)
{
this.graphics.lineStyle(lineThickness, selectedColor);
this.graphics.moveTo(mouseX, mouseY);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
}
function stopDrawing(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
function mouseMove(e:MouseEvent):void
{
this.graphics.lineTo(mouseX, mouseY);
}
AS2:
line0.onPress = function()
{
lineThickness = 0;
}
line3.onPress = function()
{
lineThickness = 3;
}
line6.onPress = function()
{
lineThickness = 6;
}
colorRed.onPress = function()
{
selectedColor = "0xFF0000";
}
colorGreen.onPress = function()
{
selectedColor = "0x00FF00";
}
AS3:
line0.addEventListener(MouseEvent.CLICK, changeLine);
line3.addEventListener(MouseEvent.CLICK, changeLine);
line6.addEventListener(MouseEvent.CLICK, changeLine);
colorRed.addEventListener(MouseEvent.CLICK, changeColor);
colorGreen.addEventListener(MouseEvent.CLICK, changeColor);
function changeLine(e:MouseEvent):void
{
switch(e.currentTarget)
{
default: lineThickness = 1; break;
case line0: lineThickness = 0; break;
case line3: lineThickness = 0; break;
case line6: lineThickness = 0; break;
}
}
function changeColor(e:MouseEvent):void
{
switch(e.currentTarget)
{
default: selectedColor = 0x000000;
case colorRed: selectedColor = 0xFF0000; break;
case colorGreen: selectedColor = 0x00FF00; break;
}
}
Additional (clear the graphics):
eraser_btn.addEventListener(MouseEvent.CLICK, erase);
function erase(e:MouseEvent):void
{
this.graphics.clear();
}
I recommend you read this http://www.actionscriptcheatsheet.com/downloads/as3cs_migration.pdf
But, here is some tips.
Events you code like this
object.addEventListener(Event.EVENT_TYPE,myFunctionToHandleTheEvent);
in the case of
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
you use this
this.graphics.lineStyle(lineThickness, selectedColor);
this.graphics.moveTo(stage.mouseX, stage.mouseY);
to remove a event listener use
object.removeEventListener(Event.EVENT_TYPE,myFunction);