BitmapData Collision - actionscript-3

I have been trying to use BitmapData for collision detection, but have failed so far, and I don't know why. The code compiles, but doesn't do anything (when it should print "hit" ). Can anyone help me?
package
{
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.display.MovieClip;
import flash.ui.Keyboard;
import flash.display.BitmapData;
import flash.geom.Point;
public class Main extends MovieClip
{
private var spd:int = 5;
private var pressedKeys:Object = {};
private var bgMask:BitmapData;
private var plMask:BitmapData;
private var wall:Wall = new Wall();
public function Main()
{
var bgBitMapData:BitmapData = new BitmapData(bg.width,bg.height,true,0);
bgMask = bgBitMapData.clone();
wall.x = bg.x;
wall.y = bg.y;
bgMask.draw( wall );
var plBitMapData:BitmapData = new BitmapData(pl.width,bg.height,true,0);
plMask = bgBitMapData.clone();
bgMask.draw( pl );
stage.addEventListener(KeyboardEvent.KEY_DOWN,this.keyPressHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,this.keyPressHandler);
stage.addEventListener(Event.ENTER_FRAME,this.gameLoop);
}
public function keyPressHandler( evt:KeyboardEvent ):void
{
if (evt.type == KeyboardEvent.KEY_DOWN)
{
pressedKeys[evt.keyCode] = 1;
}
else
{
delete pressedKeys[ evt.keyCode ];
}
}
public function inputHandler():void
{
var moveXBy:int;
var moveYBy:int;
if (pressedKeys[Keyboard.J])
{
moveXBy -= spd;
}
if (pressedKeys[Keyboard.K])
{
moveYBy += spd;
}
if (pressedKeys[Keyboard.L])
{
moveXBy += spd;
}
if (pressedKeys[Keyboard.I])
{
moveYBy -= spd;
}
pl.x += moveXBy;
pl.y += moveYBy;
}
public function playerWallCollision():void
{
if ( plMask.hitTest( new Point( wall.x, wall.y ), 1, bgMask, new Point( pl.x, pl.y ), 1))
{
trace( "hit" );
}
}
public function gameLoop( evt:Event ):void
{
wallUpdate();
inputHandler();
playerWallCollision();
}
private function wallUpdate()
{
wall.x = bg.x;
wall.y = bg.y;
}
}
}

as far as this script tells me, after the lines:
var bgBitMapData:BitmapData = new BitmapData(bg.width,bg.height,true,0);
// bgBitMapData is an empty BMP at this point cause its just freshly instanciated
bgMask = bgBitMapData.clone();
wall.x = bg.x;
wall.y = bg.y;
bgMask.draw( wall );
var plBitMapData:BitmapData = new BitmapData(pl.width,bg.height,true,0);
// no idea y you make this plBitMapData anyway
plMask = bgBitMapData.clone();
// now you clone the empty bgBitMapData to be plMask
bgMask.draw( pl );
plMask is never filled with anything! So compared with an empty BitmapData should allways return false.
So the answer to when should it output hit - never ;)
And as a sidenote try to keep it more readable by 1. write a comment every here and there what your intention is and 2. go for direct ways :
var bgBitMapData:BitmapData = new BitmapData(bg.width,bg.height,true,0);
bgMask = bgBitMapData.clone();
// this position seems just wrong to me wall.x or wall.y do not effect the draw so keep it somewhere else... since you will copy the inside of wall
wall.x = bg.x;
wall.y = bg.y;
bgMask.draw( wall );
For me it should look like:
// placing a wall to new / init coordinates
wall.x = bg.x;
wall.y = bg.y;
// drawing wall on bgMask for hittesting against player or what ever you intende here
bgMask = new BitmapData(bg.width,bg.height,true,0);
bgMask.draw( wall );

Related

(Actionscript 3) Pixel-perfect collision detection between the walls and player?

I am trying to make a flash game in which there is collision detection between the player and the walls. However, when I try using Wall11.hitTestPoint(), I cannot get the collision detection to be perfect. Then, I decided to use bitmap but it is hard to code this because the wall is irregularly shaped (it is not a square, rectangle, circle or any regular shape). Is there anyway to improve the collision detection with walls?
function checkCollision(_debug:Boolean = false):Boolean {
var bmd1:BitmapData = new BitmapData(Wall11.width, Wall11.height, true, 0);
var bmd2:BitmapData = new BitmapData(LevelOnePlayer.width, LevelOnePlayer.height, true, 0);
bmd1.draw(Wall11);
bmd2.draw(LevelOnePlayer);
if (_debug) {
var bmp:Bitmap = new Bitmap(bmd1);
bmp.x = Wall11.x;
bmp.y = Wall11.y;
addChild(bmp);
var bmp2:Bitmap = new Bitmap(bmd2);
bmp2.x = LevelOnePlayer.x;
bmp2.y = LevelOnePlayer.y;
addChild(bmp2);
}
if(bmd1.hitTest(new Point(Wall11.x, Wall11.y), 255, bmd2, new Point(LevelOnePlayer.x, LevelOnePlayer.y), 255))
return true;
if (!_debug) {
bmd1.dispose();
bmd2.dispose();
}
return false;
}
These are basics of hitTestPoint stuff.
package
{
import flash.geom.Point;
import flash.events.Event;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
public class HitTest extends Sprite
{
private var textArea:TextField;
private var Circle:Shape;
private var Box:Shape;
public function HitTest()
{
if (stage) onStage();
else addEventListener(Event.ADDED_TO_STAGE, onStage);
}
private function onStage(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, onStage);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.showDefaultContextMenu = false;
stage.align = StageAlign.TOP_LEFT;
stage.stageFocusRect = false;
addShapes();
addLabel();
onFrame();
// Call it every frame to keep things updated.
addEventListener(Event.ENTER_FRAME, onFrame);
}
private function onFrame(e:Event = null):void
{
// Place graphics to the center of the stage.
x = stage.stageWidth >> 1;
y = stage.stageHeight >> 1;
// Lets detect collision with the circle.
var aPoint:Point = new Point();
// Take local mouse coordinates within the target shape.
aPoint.x = Circle.mouseX;
aPoint.y = Circle.mouseY;
// Convert them into the root coordinates - it is the ONLY correct way.
// Comment the next 2 lines to see how local coordinates fail to work.
aPoint = Circle.localToGlobal(aPoint);
aPoint = root.globalToLocal(aPoint);
// Hit test the point against shape.
// Set the last parameter to false to see hitTest against the shape bounding box.
var aHit:Boolean = Circle.hitTestPoint(aPoint.x, aPoint.y, true);
textArea.text = aHit? "! HIT !": "NO HIT";
}
private function addShapes():void
{
Circle = new Shape();
Circle.graphics.lineStyle(2, 0x000000, 1);
Circle.graphics.beginFill(0xCC99FF, 1);
Circle.graphics.drawCircle(0, 0, 50);
Circle.graphics.endFill();
Box = new Shape();
Box.graphics.lineStyle(0, 0xCCCCCC, 1);
Box.graphics.drawRect(-50, -50, 100, 100);
addChild(Box);
addChild(Circle);
}
private function addLabel():void
{
textArea = new TextField();
textArea.x = 10;
textArea.y = 10;
textArea.width = 70;
textArea.height = 20;
textArea.border = true;
textArea.wordWrap = false;
textArea.multiline = true;
textArea.selectable = true;
textArea.background = true;
textArea.mouseEnabled = false;
var aFormat:TextFormat;
aFormat = textArea.getTextFormat();
aFormat.font = "_typewriter";
aFormat.size = 12;
aFormat.bold = true;
aFormat.align = TextFormatAlign.CENTER;
textArea.setTextFormat(aFormat);
textArea.defaultTextFormat = aFormat;
stage.addChild(textArea);
textArea.text = "NO HIT";
}
}
}

AS3 / Flash - Error #1009: Cannot access a property or method of a null object reference

I know this is a common question, but I've looked through all of the others and couldn't figure out a solution for my problem.
I've debugged and found the offending line of code, but I'm not sure what exactly it is that's wrong with it or how to fix it.
Code below - the error is thrown when "enemy.movement();" calls the movement function in the Enemy class. The first 2 lines of code(var xDist and var yDist) or specifically flagged.
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
public class zombiestandoffMain extends MovieClip
{
static public var enemy:Enemy;
static public var player:Player;
public var gameTimer:Timer;
public var crosshair:Crosshair;
public var army:Array;
public function zombiestandoffMain()
{
//enemy = new Enemy();
//addChild( enemy );
army = new Array();
var newEnemy = new Enemy;
army.push( newEnemy );
addChild( newEnemy );
player = new Player();
addChild( player );
crosshair = new Crosshair();
addChild( crosshair );
crosshair.x = mouseX;
crosshair.y = mouseY;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
public function onTick( timerEvent:TimerEvent ):void
{
var newEnemy:Enemy = new Enemy;
army.push( newEnemy );
addChild( newEnemy );
crosshair.x = mouseX;
crosshair.y = mouseY;
for each ( var enemy:Enemy in army ) {
enemy.movement();
}
//if ( player.hitTestObject( enemy ) )
//{
//}
}
}
}
And the Enemy class:
package
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.events.Event;
public class Enemy extends MovieClip
{
public var sideSpawn = int(Math.random() * 3)
public function Enemy()
{
if (sideSpawn == 0) {//top
x = Math.random() * 800;
y = 200;
} else if (sideSpawn == 1) {//left
x = -20;
y = (Math.floor(Math.random() * (1 + 800 - 200)) + 200);
} else if (sideSpawn == 2) {//right
x = 800 + 20;
y = (Math.floor(Math.random() * (1 + 800 - 200)) + 200);
} else { //bottom
x = Math.random() * 800;
y = 800 + 20;
//(Math.floor(Math.random() * (1 + high - low)) + low);
}
}
public function movement():void {
var xDist = Math.abs(zombiestandoffMain.enemy.x - zombiestandoffMain.player.x);
var yDist = Math.abs(zombiestandoffMain.enemy.y - zombiestandoffMain.player.y);
if (xDist > yDist) {
if (zombiestandoffMain.enemy.x > zombiestandoffMain.player.x)
zombiestandoffMain.enemy.x-=2;
else zombiestandoffMain.enemy.x+=2;
} else {
if (zombiestandoffMain.enemy.y > zombiestandoffMain.player.y)
zombiestandoffMain.enemy.y-=2;
else zombiestandoffMain.enemy.y+=2;
}
}
}
}
My best guess is that the x and y coords for enemy are null - but I've tried inserting values for the coords and still get the same error.
Thank you for any help!
You've only declared enemy, you must also define it. Set enemy inside zombiestandoffMain to a new Enemy obect:
enemy = new Enemy();
I guess it's with the zombiestandoffMain you are referencing in the movement() method. I do not see any definition of it in the Enemy Class. if it is meant to be defined manually in the flash environment or somewhere make sure that this property is (zombiestandoffMain) is reference properly. Hope that helps

Make three MovieClips appear and disappear inside a snowglobe when shaken

I used a creative cow tutorial to create my own snow globe that moves and snow reactivates - it really is a great tutorial.
What I'm trying to do is Change between 3 Movie clips in the ActionScript - But each time I add my movie clip names - Or try and add a simple visibility code I break my snow globe actions.
I have my MovieClip instances named friendsSceneThree, BuddiesSceneTwo and HatsOffSceneOne. I would think they'd be good but somewhere I'm missing something. Right now I can't get the code to even SEE The movieclips I'm getting a simple:
TypeError: Error #1006: value is not a function.at SnowGlobeContainer/update()
Down in the 'if drag' Update is where I'd like to Change from One MClip to the Next.
What Am I Not Seeing?!?! Any help would be greatly appreciated! Thanks
Here is the ActionScript:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.geom.Point;
public class SnowGlobeContainer extends Sprite {
public var snowForeground:SnowGeneratorCircle;
public var snowBackground:SnowGeneratorCircle;
public var friendsSceneThree:MovieClip;
public var buddiesSceneTwo:MovieClip;
public var hatsOffSceneOne:MovieClip;
public var drag:Boolean = false;
public var over:Boolean = false;
public var startPos:Point = new Point;
public var mouseDownOffset:Point = new Point;
public var bounds:Rectangle = new Rectangle;
public var vel:Point = new Point(0,0);
public var pos:Point = new Point(x,y);
public var old:Point = new Point(x,y);
public var gravity:Number = 5+(Math.random()*1);
public var restitution:Number = 0.5;
public var friction:Number = 0.9;
public function SnowGlobeContainer() {
// save some initial persistant properties
startPos.x = this.x;
startPos.y = this.y;
old.x = this.x;
old.y = this.y;
bounds.x = 0;
bounds.y = 0;
bounds.width = 600;
bounds.height = startPos.y;
// add mouse interaction listeners and show the cursor on rollover
this.mouseChildren = false;
this.useHandCursor = true;
this.buttonMode = true;
this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
this.addEventListener(Event.ENTER_FRAME, update);
}
protected function onMouseOver(e:MouseEvent=null):void { over = true; }
protected function onMouseOut(e:MouseEvent=null):void { over = false; }
protected function onMouseDown(e:MouseEvent=null):void {
// Save the offset of your mouse when you first start dragging. Same functionality as startDrag(false)
mouseDownOffset.x = mouseX;
mouseDownOffset.y = mouseY;
drag = true;
}
protected function onMouseUp(e:MouseEvent=null):void {
vel.x = vel.y = 0;
pos.x = x;
pos.y = y;
drag = false;
}
public function update(e:Event):void {
// this if/else statement controls the mouse over and out instead of using event listeners
if(mouseY < -175 || mouseY > 175 || mouseX < -175 || mouseX > 175){
if(over) onMouseOut();
}else{
if(!over) onMouseOver();
}
if(drag){
// drag around..
this.x = parent.mouseX - mouseDownOffset.x;
this.y = parent.mouseY - mouseDownOffset.y;
// keep this thing on the table :)
if(y >= bounds.height) y = bounds.height;
// if you "shake" or move the mouse quickly, we are going to reset the snow particles
var d:Point = new Point(Math.abs(old.x - x), Math.abs(old.y - y));
if(d.x > 50 || d.y > 50 ){
snowForeground.reset();
snowBackground.reset();
friendsSceneThree.visible = false;
}
// update the history position
old.x = x;
old.y = y;
vel.y = (y-old.y)/2;
}else{
// if you drop this object it should have a bit of realistic falling..
vel.y += gravity;
pos.y += vel.y;
// bounce
if(pos.y > bounds.height){
pos.y = bounds.height;
vel.y *= -(Math.random()*restitution);
}
y = pos.y;
}
}
}
}
I appreciate the help -- If you haven't noticed I'm new to all of this scripting. I'm looking in on lynda.com and other forums. the SnowGeneratorCircle.as is:
package {
import flash.display.Sprite;
import flash.events.Event;
public class SnowGeneratorCircle extends Sprite {
var totalFlakes:int = 500;
var flakes:Array = new Array();
public function SnowGeneratorCircle() {
addSnowFlakes();
addEventListener(Event.ENTER_FRAME, update);
}
protected function addSnowFlakes():void{
for(var i:int=0; i<totalFlakes; i++){
var f:SnowFlake = new SnowFlake();
addChild(f);
flakes.push(f);
}
}
public function reset():void{
for(var i:int=0; i<totalFlakes; i++){
var f:SnowFlake = flakes[i];
f.reset();
}
}
public function update(e:Event=null):void {
for(var i:int=0; i<totalFlakes; i++){
var f:SnowFlake = flakes[i];
f.update(0);
}
}
}
}
I debugged - didn't clean up the code, because every time I did - it broke the actions. So I left the code with the double spacing. That's how it went in when I copied and pasted from the tutorial anyway.
Here's the error on line 173 - which is the MovieClip I'd like to have change.
Attempting to launch and connect to Player using URL /Volumes/Lacie Biggest S2S/GRaid/Veronica
/V/Rubio/Work/SUBARU/SnowGlobe Subaru/SnowGlobeAnima/snowGlobeShakev3.swf
[SWF] Volumes:Lacie Biggest S2S:GRaid:Veronica:V:Rubio:Work:SUBARU:SnowGlobe >Subaru:SnowGlobeAnima:snowGlobeShakev3.swf - 468081 bytes after decompression
TypeError: Error #1006: value is not a function.
at SnowGlobeContainer/update()[/Volumes/Lacie Biggest S2S/GRaid/Veronica/V/Rubio/Work/SUBARU
/SnowGlobe Subaru/SnowGlobeAnima/SnowGlobeContainer.as:173]
I just don't know how to get the actionscript to find my MovieClips and then swap them out wt each shake of the globe.

Shooting a bullet in flash CS6 ActionScript 3.0

I keep getting the following error when I fire a Shot I made in Flash CS6 AS 3.0
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.display:DisplayObject.
package
{
import flash.display.MovieClip;
import flash.ui.Mouse;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.media.SoundChannel;
public class AvoiderGame extends MovieClip
{
public var army:Array;
public var reishoot:ReiShoot;
public var enemy:Enemy;
public var avatar:Avatar;
public var gameTimer:Timer;
public var useMouseControl:Boolean;
public var downKey:Boolean;
public var bullets:Array = [];
public var backgroundMusic:BackgroundMusic;
public var enemySound:EnemySound;
public var bgmSoundChannel:SoundChannel;
public var sfxSoundChannel:SoundChannel;
function AvoiderGame()
{
/*useMouseControl = false;
downKey = false;
if( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
avatar.x = 200;
avatar.y = 250;
}
*/
backgroundMusic = new BackgroundMusic();
bgmSoundChannel = backgroundMusic.play();
bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );
enemySound = new EnemySound();
army = new Array();
//Initial Position of the Enemy
var newEnemy = new Enemy( 2700, 600 );
army.push( newEnemy );
addChild( newEnemy );
avatar = new Avatar();
addChild( avatar );
avatar.height = 220;
avatar.width = 120;
avatar.addEventListener(MouseEvent.CLICK, shoot);
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
//addEventListener( Event.ADDED_TO_STAGE, onAddToStage );
}//End AvoiderGame
function shoot(e:MouseEvent):void
{
var b:Shot = new Shot();
b.addEventListener(Event.ENTER_FRAME, bulletflies);
stage.addChild(b);
bullets.push(b);
}
function bulletflies(e:Event):void
{
e.currentTarget.y -= 5;
if(e.currentTarget.y < 0 || e.currentTarget.y > stage.height)
{
stage.removeChild(e.currentTarget);
bullets.splice(bullets.indexOf(e.currentTarget), 1);
}
}
public function onBackgroundMusicFinished( event:Event ):void
{
bgmSoundChannel = backgroundMusic.play();
bgmSoundChannel.addEventListener( Event.SOUND_COMPLETE, onBackgroundMusicFinished );
}
public function onKeyPress(keyboardEvent:KeyboardEvent):void
{
if ( keyboardEvent.keyCode == Keyboard.DOWN )
{
downKey = true;
}
}
public function onKeyRelease( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.DOWN )
{
downKey = false;
}
}
public function onAddToStage(event:Event):void
{
stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
}
public function onTick( timerEvent:TimerEvent ):void
{
if ( Math.random() < 2800 )
{
var randomY:Number = Math.random() * 2800;
var newEnemy:Enemy = new Enemy( width, randomY );
army.push( newEnemy );
addChild( newEnemy );
gameScore.addToValue( 1 );
//sfxSoundChannel = enemySound.play();
}//End if statement
/*
if( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
if ( downKey )
{
avatar.moveDown();
}
}
*/
avatar.x = mouseX;
avatar.y = mouseY;
for each ( var enemy:Enemy in army )
{
enemy.moveDownABit();
if ( avatar.hitTestObject( enemy ) )
{
bgmSoundChannel.stop();
gameTimer.stop();
dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );
}//End if statement
}//End for loop
}//End onTick function
public function getFinalScore():Number
{
return gameScore.currentValue;
}
}//End AvoiderGame class
}//End package
Line 90 is stage.removeChild(e.currentTarget);
With this, you need to cast e.currentTarget to a DisplayObject:
stage.removeChild(e.currentTarget as DisplayObject);
Just a guess: you've started your ENTER_FRAME loop, (which will remove 'b') before you've said addChild(b). Try putting 'b' on the display list before you try to remove it!!
Aha! I think I may have found your problem, though I am unsure of how it relates to the error code...
Take a look at your Shot class (which I have found here https://stackoverflow.com/questions/22244959/why-does-this-not-shoot). Every frame, you tell the Shot class to test whether it is in the boundaries of the stage still, and if so, to remove itself from the stage. In line 90, you also tell the stage to determine if the bullet is still in bounds, and if so, to remove it again.
You have tried to remove the bullet from the stage twice!
Again, I stress, this seems to be unrelated to the error code, but hopefully it points you in the right direction.

AS3: Issues with multiple save/load slots

I'm trying to take this very simple "game" and give it three save/load slots. Following a separate tutorial I can make it work with a single save slot but once I try adding more, it gives me the following error message.
1046:Type was not found or was not compile-time constant: save2.
1046:Type was not found or was not compile-time constant: save3.
I am new to actionscript 3 so I'm sure I'm being very newbish but I have tried to figure this out for quite some time now but just can't seem to. The whole thing is controlled by buttons already placed on the scene. I appreciate any help I can get.
The code:
import flash.net.SharedObject;
var saveDataObject:SharedObject;
var currentScore:Number = 0
init();
function init():void{
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save1);
btnSave1.addEventListener(MouseEvent.CLICK, saveData);
btnSave2.addEventListener(MouseEvent.CLICK, save2);
btnSave2.addEventListener(MouseEvent.CLICK, saveData);
btnSave3.addEventListener(MouseEvent.CLICK, save3);
btnSave3.addEventListener(MouseEvent.CLICK, saveData);
btnLoad1.addEventListener(MouseEvent.CLICK, save1);
btnLoad1.addEventListener(MouseEvent.CLICK, loadData);
btnLoad2.addEventListener(MouseEvent.CLICK, save2);
btnLoad2.addEventListener(MouseEvent.CLICK, loadData);
btnLoad3.addEventListener(MouseEvent.CLICK, save3);
btnLoad3.addEventListener(MouseEvent.CLICK, loadData);
}
function save1(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile1");
}
function save2(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile2");
}
function save3(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile3");
}
function addScore(e:MouseEvent):void{
currentScore += 1;
updateScoreText();
}
function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function loadData(e:MouseEvent):void{
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}
I tried your code and it works like a charm...
Anyways, I've made a simpler version that doesn't use so many functions and Events.
Here is a pure AS3 version of it (just save it as Test.as3 and use as Document Class in Flash), but you can copy the content of the Test() method and paste in a action frame.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.text.TextField;
public class Test extends Sprite
{
public function Test()
{
/***** START: Faking buttons and field *****/
var txtScore:TextField = new TextField();
addChild(txtScore);
var btnAdd:Sprite = new Sprite();
var btnSave1:Sprite = new Sprite();
var btnSave2:Sprite = new Sprite();
var btnSave3:Sprite = new Sprite();
var btnLoad1:Sprite = new Sprite();
var btnLoad2:Sprite = new Sprite();
var btnLoad3:Sprite = new Sprite();
var items:Array = [btnAdd, null, btnSave1, btnSave2, btnSave3, null, btnLoad1, btnLoad2, btnLoad3];
for (var i:int = 0; i < items.length; ++i)
{
var item:Sprite = items[i];
if (item)
{
item.graphics.beginFill(Math.random() * 0xFFFFFF);
item.graphics.drawRect(0, 0, 100, 25);
item.graphics.endFill();
item.x = 25;
item.y = i * 30 + 25;
addChild(item);
}
}
/***** END: Faking buttons and field *****/
var saveDataObject:SharedObject;
var currentScore:Number = 0
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save);
btnSave2.addEventListener(MouseEvent.CLICK, save);
btnSave3.addEventListener(MouseEvent.CLICK, save);
btnLoad1.addEventListener(MouseEvent.CLICK, load);
btnLoad2.addEventListener(MouseEvent.CLICK, load);
btnLoad3.addEventListener(MouseEvent.CLICK, load);
function getLocal(target:Object):String
{
if (target == btnSave1 || target == btnLoad1)
{
return "savefile1";
}
else if (target == btnSave3 || target == btnLoad2)
{
return "savefile2";
}
else if (target == btnSave2 || target == btnLoad3)
{
return "savefile3";
}
}
function save(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function load(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function addScore(e:MouseEvent):void
{
currentScore += 1;
updateScoreText();
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}
}
}
}