Actionscript 3.0 - Trying to remove a child - actionscript

Simple simple problem but I can't get it to work.
So I just have a class with a display object, a ball. I create instances of it from Main.as
and run a for loop to check if I hit the ball and if I do, I want to remove the object.
But I can't.
What's wrong with my code?
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite
{
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var crash:Crash;
private var crashCollection:Vector.<Crash> = new Vector.<Crash>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main()
{
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
stage.addEventListener(MouseEvent.CLICK, checkForHit);
}
private function checkForHit(e:MouseEvent):void
{
if (clayCollection.length > 0)
{
for (var i:int = 0; i < clayCollection.length; i++)
{
if (e.target.hitTestObject(clayCollection[i]))
{
clayCollection.splice(i, 1);
removeChild(clayCollection[i]);
}
}
}
}
private function addNewClay(e:TimerEvent):void
{
clay = new Clay();
addChild(clay);
clayCollection.push(clay);
}
}
}

Try something like this
for (var i:int = 0; i < clayCollection.length; i++) {
var clay:Clay = clayCollection[i];
if (e.target.hitTextObject) {
//seems to me all clays will hit test as true with the stage?
removeChild(clay);
clayCollection.splice(i, 1);
}
}
That way you know that the object that you're trying to remove is definitely the one that hit tested true.

I agree with Amy, listen for a click on the instance of clay, not the stage. You can still remove it from your array, something like this (untested code):
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite
{
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var crash:Crash;
private var crashCollection:Vector.<Crash> = new Vector.<Crash>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main()
{
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
}
private function checkForHit(e:MouseEvent):void
{
// identify the target as Clay
var clay:Clay = e.target as Clay;
if(contains(clay)) removeChild(clay);
// remove it from your array
for each (var c:Clay in clayCollection) {
if (c == clay) clayCollection.splice(clayCollection.indexOf(c), 1);
}
}
private function addNewClay(e:TimerEvent):void
{
clay = new Clay();
clay.addEventListener(MouseEvent.CLICK, checkForHit);
addChild(clay);
clayCollection.push(clay);
}
}
}

When the program created a instance of the object and you mouse click it, the debugger threw this error.
Main Thread (Suspended: RangeError: Error #1125: The index 0 is out of range 0.)
Main/checkForHit
The fix is that you need to delimit the index of the loop as you slice it. Also the sequence of when you apply the splice and delimit is important.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite {
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main(){
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
stage.addEventListener(MouseEvent.CLICK, checkForHit);
}//END MAIN()
private function checkForHit(e:MouseEvent):void{
if (clayCollection.length > 0)
{
for (var i:int = 0; i != clayCollection.length; i++)
{
trace(i,clayCollection.length);
if (e.target.hitTestObject(clayCollection[i]))
{
removeChild(clayCollection[i]);
clayCollection.splice(i, 1);
i--;
}
}
}
}//END checkForHit()
private function addNewClay(e:TimerEvent):void{
clay = new Clay();
addChild(clay);
clayCollection.push(clay);
}//END addNewClay()
}//END MAINCLASS
}//END PACKAGE

Related

mystery Error #1063: Argument count mismatch

So I'm getting a "Error #1063: Argument count mismatch" error. The weird thing is that it isn't keeping the game from running, but I would like to know why I'm even getting an error in the first place. The full error is:
ArgumentError: Error #1063: Argument count mismatch on Hock(). Expected 3, got 0.
at flash.display::Sprite/constructChildren()
at flash.display::Sprite()
at flash.display::MovieClip()
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
at Main/addPlayscreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:17]
at Main()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:13]
at runtime::ContentPlayer/loadInitialContent()
at runtime::ContentPlayer/playRawContent()
at runtime::ContentPlayer/playContent()
at runtime::AppRunner/run()
at ADLAppEntry/run()
at global/runtime::ADLEntry()
The Code for PlayScreen is:
import flashx.textLayout.formats.BackgroundColor;
import flash.display.SimpleButton;
import flash.ui.Mouse;
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class PlayScreen extends MovieClip
{
public var batArmy:Array;
public var hockArmy:Array;
public var shadow:Shadow;
public var crossHairs:CrossHairs;
var Layer01:MovieClip;
var Layer02:MovieClip;
var Layer03:MovieClip;
var Layer04:MovieClip;
var Layer05:MovieClip;
var randomX:Number = 300 + (660 - 300) * Math.random();
public function PlayScreen()
{
//Mouse.hide();
addBatButton.addEventListener(MouseEvent.CLICK, addBat);
addHockButton.addEventListener(MouseEvent.CLICK, addHock);
batArmy = new Array();
hockArmy = new Array();
//addEventListener(Event.ENTER_FRAME, crossHairsMove);
//stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
Layer01 = new MovieClip;
this.addChild(Layer01);
Layer02 = new MovieClip;
this.addChild(Layer02);
Layer03 = new MovieClip;
this.addChild(Layer03);
Layer04 = new MovieClip;
this.addChild(Layer04);
Layer05 = new MovieClip;
this.addChild(Layer05);
//add crossHair
/*crossHairs = new CrossHairs(mouseX,mouseY,this);
Layer05.addChild (crossHairs);
addEventListener(Event.ENTER_FRAME, crossHairsMove);*/
}
/*public function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.DOWN )
{
trace("yar");
addBat;
}
}*/
public function addBat( mouseEvent:MouseEvent ):void
{
var randomX:Number = 300 + (660 - 300) * Math.random();
var newBat = new Bat( randomX, -50, this);
batArmy.push ( newBat );
Layer02.addChild (newBat);
}
public function addHock( mouseEvent:MouseEvent ):void
{
var newHock = new Hock(-72, 170, this);
hockArmy.push ( newHock );
Layer02.addChild (newHock);
}
/*public function crossHairsMove ( e:Event ):void
{
crossHairs.x = mouseX;
crossHairs.y = mouseY;
}*/
}
and from the looks of it the error has something to do with the Hock class, so here's the code for that:
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Hock extends MovieClip
{
private var _screen: PlayScreen;
public var xSpeed:Number;
public function Hock( startX:Number, startY:Number, screen:PlayScreen )
{
_screen = screen;
x = startX;
y = startY;
width = 100;
scaleY = scaleX;
addEventListener(Event.ENTER_FRAME, moveRightFar);
addEventListener(Event.ENTER_FRAME, moveSpeed)
}
public function moveSpeed( e:Event ):void
{
x += xSpeed;
}
public function moveRightFar ( e:Event): void
{
if (x < 0)
{
gotoAndStop("rollRight");
xSpeed = 13;
}
else if (x >= 240)
{
gotoAndStop("still")
xSpeed = 0;
}
}
}
Now I could be wrong but I think it's having a problem with var newHock = new Hock(-72, 170, this); in the "addHock" function, but I have 3 arguments there, not 0. Right? Anyway, like I said, it's not keeping the game from running but it is kind of annoying, so any insight is welcome. I'm sure it's something obvious. Thanks!
I have a guess, but I'll explain how i got there first ...
the first line of the stacktrace pointing at your source code is
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
which points at the first line of the constructor of PlayScreen: addBatButton.addEventListener(MouseEvent.CLICK, addBat);
but obviously the problem is not there ...
But PlayScreen extends MovieClip and since you didn't specifically included a super() statement, the compiler will put that at as the first command. In fact, the previous lines of the stack point to the constructor of MovieClip and then to a mysterious constructChildren() method of Sprite
That happens to be an internal method used to create the childs of the Sprite that you might have setup on your clip's stage directly from Animate.
So my guess is, the player is trying to instantiate a symbol that extends Hock and that you positioned on the stage somewhere, and of course is doing it by passing zero arguments because that's what a normal Sprite would expect.
Check your library to see what extends Hock and then see which one of those is placed in some other symbol's stage. Your options then will be to remove that and create it from code or to rework the class signature to take zero arguments.

Actionscript 3 - Facebook loading User Image from Graph API

Im using Facebook Graph API to login to Facebook in my App, but after onLogin is fired i get the user image but I'm trying to load the image. But the image is not loading
Could someone advise please?
Code is below:
package {
import flash.display.MovieClip;
import flash.media.*;
import flash.media.Camera;
import flash.media.CameraUI;
import flash.events.Event;
import flash.events.*;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import com.facebook.graph.FacebookMobile;
import com.facebook.graph.Facebook;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Loader;
import flash.utils.*;
import flash.net.URLRequest;
import flash.system.*;
public class test extends MovieClip {
var webView:StageWebView;
var vidCon:Video = new Video();
const APP_ID:String = "299210093578823";
var extendedPermissions:Array = ["publish_stream","user_about_me"];
var user:User;
var loader:Loader;
public function test() {
//Security.allowDomain("*");
//Security.allowInsecureDomain("*");
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
FacebookMobile.init(APP_ID, onInit, "CAACEdEose0cBAMy735qLgTobu9YZB1Xas0l5NS5BF02NyXTeDoPjnh1vZBel1LQGdxZA2v4AKOGVqWDSUVOthn3accqiXzyMgrZAqMwKHNZB2Cu27Fzn70WWxc6rvuixgb4bgZAiat3yKtPccRxSFCPPW7CTKbIN6ctFCBzGmw3oeNfhZAZBktPONdhJ2R2SGYxHCDKbUuTZCtwZDZD");
btn_fb.addEventListener(MouseEvent.CLICK,onFBLoginClick);
}
private function onAddedToStage(event:Event):void
{
// Generally good practice to remove this listener from the object now because it stops addedToStageHandler from being called again if the object is removed and added back to the stage or display list.
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.NO_SCALE;
//stage.align = StageAlign.TOP_LEFT;
stage.stageWidth = Math.max(stage.fullScreenWidth, stage.fullScreenHeight);
stage.stageHeight = Math.min(stage.fullScreenWidth, stage.fullScreenHeight);
var yBotButton = stage.stageWidth - botButton.height;
//botButton.y = yBotButton;
}
private function onInit(success:Object, fail:Object):void
{
setTimeout(startOnINit, 3000, success);
}
public function startOnINit()
{
if (arguments[0])
{
trace(JSON.stringify(arguments[0]));
trace("Already logged in");
btn_fb.visible = false;
}
else
{
//btn.enabled = true;
trace("Not logged in-");
}
trans.visible = false;
}
private function onFBLoginClick(e:MouseEvent):void
{
trace("ddddd");
FacebookMobile.login(onLogin,this.stage, extendedPermissions,getWebView());
}
private function getWebView():StageWebView
{
if(webView) webView.dispose();
webView = new StageWebView();
webView.stage=this.stage;
webView.assignFocus();
webView.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
return webView;
}
public function onLogin(success:Object, fail:Object):void
{
trace("fjfjfj");
trace(JSON.stringify(success));
if (success)
{
btn_fb.visible = false;
setupUserLoginProfile(success);
trace("Logged In\n");
}
else
{
trace("Login Failed\n");
}
}
public function setupUserLoginProfile(userProfile:Object)
{
trace("111111111111");
var imageUrl = Facebook.getImageUrl(userProfile.user.id);
trace(userProfile.user.link);
trace(imageUrl);
user = new User(imageUrl);
var shape1:MovieClip = new MovieClip();
shape1.graphics.beginFill(0xcccccc,1);
shape1.graphics.drawRect(0,0,320,140);
shape1.graphics.endFill();
addChild(shape1);
Security.loadPolicyFile("http://graph.facebook.com/crossdomain.xml");
Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");
Security.loadPolicyFile("https://graph.facebook.com/crossdomain.xml");
Security.loadPolicyFile("https://profile.ak.fbcdn.net/crossdomain.xml");
trace("sss" + user.userImage);
loader = new Loader();
loader.load(new URLRequest(user.userImage));
shape1.addChild(loader);
loader.x=25;
loader.y=25;
loader.width = 80;
loader.height = 80;
}
}
}
MODIFIED
I get an error in the try catch syntax
Error: [strict] Ignoring policy file at
http://profile.cc.fbcdn.net/crossdomain.xml due to incorrect syntax.
See http://www.adobe.com/go/strict_policy_files to fix this problem.
SecurityError: Error #3207: Application-sandbox content cannot access
this feature.
package {
import flash.display.MovieClip;
import flash.media.*;
import flash.media.Camera;
import flash.media.CameraUI;
import flash.events.Event;
import flash.events.*;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import com.facebook.graph.FacebookMobile;
import com.facebook.graph.Facebook;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Loader;
import flash.utils.*;
import flash.net.URLRequest;
import flash.system.*;
public class test extends MovieClip {
var webView:StageWebView;
var vidCon:Video = new Video();
const APP_ID:String = "299210093578823";
var extendedPermissions:Array = ["publish_stream","user_about_me"];
var user:User;
var loader:Loader;
public function test() {
//Security.allowDomain("*");
//Security.allowInsecureDomain("*");
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
FacebookMobile.init(APP_ID, onInit, "CAACEdEose0cBAMy735qLgTobu9YZB1Xas0l5NS5BF02NyXTeDoPjnh1vZBel1LQGdxZA2v4AKOGVqWDSUVOthn3accqiXzyMgrZAqMwKHNZB2Cu27Fzn70WWxc6rvuixgb4bgZAiat3yKtPccRxSFCPPW7CTKbIN6ctFCBzGmw3oeNfhZAZBktPONdhJ2R2SGYxHCDKbUuTZCtwZDZD");
btn_fb.addEventListener(MouseEvent.CLICK,onFBLoginClick);
}
private function onAddedToStage(event:Event):void
{
// Generally good practice to remove this listener from the object now because it stops addedToStageHandler from being called again if the object is removed and added back to the stage or display list.
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.NO_SCALE;
//stage.align = StageAlign.TOP_LEFT;
stage.stageWidth = Math.max(stage.fullScreenWidth, stage.fullScreenHeight);
stage.stageHeight = Math.min(stage.fullScreenWidth, stage.fullScreenHeight);
var yBotButton = stage.stageWidth - botButton.height;
//botButton.y = yBotButton;
}
private function onInit(success:Object, fail:Object):void
{
setTimeout(startOnINit, 3000, success);
}
public function startOnINit()
{
if (arguments[0])
{
trace(JSON.stringify(arguments[0]));
trace("Already logged in");
btn_fb.visible = false;
}
else
{
//btn.enabled = true;
trace("Not logged in-");
}
trans.visible = false;
}
private function onFBLoginClick(e:MouseEvent):void
{
trace("ddddd");
FacebookMobile.login(onLogin,this.stage, extendedPermissions,getWebView());
}
private function getWebView():StageWebView
{
if(webView) webView.dispose();
webView = new StageWebView();
webView.stage=this.stage;
webView.assignFocus();
webView.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
return webView;
}
public function onLogin(success:Object, fail:Object):void
{
trace("fjfjfj");
trace(JSON.stringify(success));
if (success)
{
btn_fb.visible = false;
setupUserLoginProfile(success);
trace("Logged In\n");
}
else
{
trace("Login Failed\n");
}
}
public function setupUserLoginProfile(userProfile:Object)
{
trace("111111111111");
var imageUrl = Facebook.getImageUrl(userProfile.user.id);
trace(userProfile.user.link);
trace(imageUrl);
user = new User(imageUrl);
var shape1:MovieClip = new MovieClip();
shape1.graphics.beginFill(0xcccccc,1);
shape1.graphics.drawRect(0,0,320,140);
shape1.graphics.endFill();
addChild(shape1);
Security.loadPolicyFile("http://graph.facebook.com/crossdomain.xml");
Security.loadPolicyFile("https://graph.facebook.com/crossdomain.xml");
Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");
Security.loadPolicyFile("https://profile.ak.fbcdn.net/crossdomain.xml");
Security.loadPolicyFile('http://profile.cc.fbcdn.net/crossdomain.xml');
Security.loadPolicyFile('https://profile.cc.fbcdn.net/crossdomain.xml');
Security.loadPolicyFile('http://fbcdn-profile-a.akamaihd.net/crossdomain.xml');
Security.loadPolicyFile('https://fbcdn-profile-a.akamaihd.net/crossdomain.xml');
Security.loadPolicyFile('http://fbcdn-sphotos-a.akamaihd.net/crossdomain.xml');
Security.loadPolicyFile('https://fbcdn-sphotos-a.akamaihd.net/crossdomain.xml');
try {
Security.allowDomain("*");
Security.allowInsecureDomain("*");
}
catch(error:Error){
trace(error);
}
trace("sss" + user.userImage);
loader = new Loader();
loader.load(new URLRequest(user.userImage));
shape1.addChild(loader);
loader.x=25;
loader.y=25;
loader.width = 80;
loader.height = 80;
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadingError);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,doneLoad);
}
function loadingError(e:IOErrorEvent):void {
trace("There has been an error loading the image. The server may be busy. Refresh the page and try again.");
}
function doneLoad(e:Event):void {
trace("doneload");
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,doneLoad);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loadingError);
}
}
}
I had to load the bitmap then append the bitmap:
Code is below:
package {
import flash.display.MovieClip;
import flash.media.*;
import flash.media.Camera;
import flash.media.CameraUI;
import flash.events.Event;
import flash.events.*;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import com.facebook.graph.FacebookMobile;
import com.facebook.graph.Facebook;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.utils.*;
import flash.net.URLRequest;
import flash.system.*;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class test extends MovieClip {
var webView:StageWebView;
var vidCon:Video = new Video();
const APP_ID:String = "299210093578823";
var extendedPermissions:Array = ["publish_stream","user_about_me"];
var user:User;
var loader:Loader;
var shape1:MovieClip;
public function test() {
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
FacebookMobile.init(APP_ID, onInit, "CAACEdEose0cBAMy735qLgTobu9YZB1Xas0l5NS5BF02NyXTeDoPjnh1vZBel1LQGdxZA2v4AKOGVqWDSUVOthn3accqiXzyMgrZAqMwKHNZB2Cu27Fzn70WWxc6rvuixgb4bgZAiat3yKtPccRxSFCPPW7CTKbIN6ctFCBzGmw3oeNfhZAZBktPONdhJ2R2SGYxHCDKbUuTZCtwZDZD");
btn_fb.addEventListener(MouseEvent.CLICK,onFBLoginClick);
}
private function onAddedToStage(event:Event):void
{
// Generally good practice to remove this listener from the object now because it stops addedToStageHandler from being called again if the object is removed and added back to the stage or display list.
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.NO_SCALE;
//stage.align = StageAlign.TOP_LEFT;
stage.stageWidth = Math.max(stage.fullScreenWidth, stage.fullScreenHeight);
stage.stageHeight = Math.min(stage.fullScreenWidth, stage.fullScreenHeight);
var yBotButton = stage.stageWidth - botButton.height;
//botButton.y = yBotButton;
}
private function onInit(success:Object, fail:Object):void
{
setTimeout(startOnINit, 3000, success);
}
public function startOnINit()
{
if (arguments[0])
{
trace(JSON.stringify(arguments[0]));
trace("Already logged in");
btn_fb.visible = false;
}
else
{
//btn.enabled = true;
trace("Not logged in-");
}
trans.visible = false;
}
private function onFBLoginClick(e:MouseEvent):void
{
trace("ddddd");
FacebookMobile.login(onLogin,this.stage, extendedPermissions,getWebView());
}
private function getWebView():StageWebView
{
if(webView) webView.dispose();
webView = new StageWebView();
webView.stage=this.stage;
webView.assignFocus();
webView.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
return webView;
}
public function onLogin(success:Object, fail:Object):void
{
trace("fjfjfj");
trace(JSON.stringify(success));
if (success)
{
btn_fb.visible = false;
setupUserLoginProfile(success);
trace("Logged In\n");
}
else
{
trace("Login Failed\n");
}
}
public function setupUserLoginProfile(userProfile:Object)
{
trace("111111111111");
var imageUrl = Facebook.getImageUrl(userProfile.user.id);
trace(userProfile.user.link);
trace(imageUrl);
user = new User(imageUrl);
shape1 = new MovieClip();
shape1.graphics.beginFill(0xcccccc,1);
shape1.graphics.drawRect(0,0,320,140);
shape1.graphics.endFill();
addChild(shape1);
trace("sss" + user.userImage);
loadPic();
}
function loadingError(e:IOErrorEvent):void {
trace("There has been an error loading the image. The server may be busy. Refresh the page and try again.");
}
function loadPic():void{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadingError);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,doneLoad);
var context:LoaderContext = new LoaderContext();
context.checkPolicyFile = true;
context.applicationDomain = ApplicationDomain.currentDomain;
Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");
try {
Security.allowDomain("*");
Security.allowInsecureDomain("*");
}
catch(error:Error){
trace(error);
}
loader.load(new URLRequest("https://graph.facebook.com/654358964644178/picture?type=normal"),context);
loader.x=25;
loader.y=25;
loader.width = 80;
loader.height = 80;
//shape1.addChild(loader);
}
function doneLoad(e:Event):void {
trace("doneload");
var bm:Bitmap = e.target.content as Bitmap;
bm.smoothing = true;
bm.x = 10;
bm.y = 10;
bm.width = 80;
bm.height = 80;
shape1.addChild(bm);
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,doneLoad);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loadingError);
loader = null;
}
}
}

1067: Implicit Coercion of a value

So I'm currently trying to run my collision test on my two sprites, and I'm getting the following error:
C:\\Code\\Game\Game.as, Line 54, Column 34 1067: Implicit coercion of a value of type mvc:PlayerModel to an unrelated type assets.Scripts:SpriteAnimation.
Which is pointing to the following line of code:
handleSpriteToSpriteCollision(_player, _boss);
The function is as follows:
private function handleSpriteToSpriteCollision(sprite1:SpriteAnimation, sprite2:SpriteAnimation):void
{
var toSprite2 : VectorModel = new
VectorModel(0,0,0,0, sprite2.x - sprite1.x, sprite2.y - sprite1.y);
var bitmapData1:BitmapData = new BitmapData(sprite1.width, sprite1.height);
while(testBitmapCollision(sprite1.spriteFrameBitmapData, sprite1.topLeftX, sprite1.topLeftY, sprite2.spriteFrameBitmapData, sprite2.topLeftX, sprite2.topLeftY))
{
sprite2.x -= toSprite2.dx;
sprite2.y -= toSprite2.dy;
}
}
Both sprites display just fine, but as soon as I make the function call it all comes crumbling down. At this point I just need some fresh eyes to take a look at the code to see what's going wrong.
Edit: Here is the PlayerModel.as
package mvc
{
import flash.events.Event;
import flash.events.EventDispatcher;
import assets.Scripts.SpriteAnimation;
public class PlayerModel extends EventDispatcher
{
private var _previousX:Number = 0;
private var _previousY:Number = 0;
private var _xPos:Number = 0;
private var _yPos:Number = 0;
public var vx:Number = 0;
public var vy:Number = 0;
private var _height:uint = 30;
private var _width:uint;
private var _color:uint;
public function PlayerModel():void
{
}
public function update():void
{
xPos += vx;
yPos += vy;
}
public function get height():uint
{
return _height;
}
public function get color():uint
{
return _color;
}
public function get xPos():Number
{
return _xPos;
}
public function set xPos(value:Number):void
{
_xPos = value;
dispatchEvent(new Event(Event.CHANGE));
}
public function get yPos():Number
{
return _yPos;
}
public function set yPos(value:Number):void
{
_yPos = value;
dispatchEvent(new Event(Event.CHANGE));
}
public function set setX(value:Number):void
{
_previousX = value - vx;
xPos = value;
}
public function set setY(value:Number):void
{
_previousY = value - vy;
yPos = value;
}
}
}
The first thing i would check is the class of your boss and player objects inherit your SpriteAnimation class:
class PlayerModel extends SpriteAnimation
{ ...
Seems as though your handleSpriteToSpriteCollision function is looking for two SpriteAnimations and at least the PlayerModel being passed isn't one
Sprite inherits EventDispatcher so as long as your SpriteAnimation inherits Sprite as well, you shouldn't lose any functionality

Actionscript 3: How to access an object after adding it as child to another?

I have a problem regarding zoom functionality. I simply cannot access my sprite anymore after I've added it as child to another sprite.
Here is the relevant part of my code (ask for more if you need to)
If I try to scale the bg_image in my init function, before the line spImage.addChild(bg_image);, there are no complications. However I simply cannot edit the bg_image's properties after this line (the zoom function, for example)
Please help!
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import fl.controls.List;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
// Zoom
public static var scale:Number = 1;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var board:Sprite;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public const scaleFactor:Number = 0.8;
public var minScale:Number = 0.25;
public var maxScale:Number = 10.0;
public var bg_image:Sprite;
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
bg_image = new Image();
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
public function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
}
}

AS3 AIR For iOS - StageVideo not working correctly

I'm trying to get StageVideo to work in my app but I'm having problems. I need to play a series of videos one after the other, the first video always plays fine but the others will only play the audio, and the StageVideo will show the last frame from the first video.
It's as if the StageVideo has frozen and is playing the video but I can't see it (only hear it). I've posted my complete code here:
I'm testing on iPad2 with Adobe Air 3.2 beta, but have also tested with 3.1 and same results.
Here is my video class:
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.Event;
import flash.media.StageVideo;
import flash.events.StageVideoEvent;
import flash.events.StageVideoAvailabilityEvent;
import flash.media.StageVideoAvailability;
import flash.net.NetStream;
import flash.net.NetConnection;
import flash.geom.Rectangle;
import flash.events.NetStatusEvent;
public class SVideo2 extends MovieClip {
public static const VIDEO_FINISHED:String = 'videoFinished';
private var debugPanel:TextField;
private var addedToStage:Boolean = false;
private var videoFile:String;
private var hwaEnabled:Boolean = false;
private var video:StageVideo;
private var ns:NetStream;
private var nc:NetConnection;
public function SVideo2() {
addDebugPanel();
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event) :void{
output('ADDED TO STAGE');
addedToStage = true;
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, onAvail);
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function playVideo(videoFile:String) :void{
output('playVideo: '+videoFile);
if(addedToStage){
this.videoFile = videoFile;
if(hwaEnabled){
startPlaying();
}
else{
output('HWA NOT AVAILABLE');
}
}
else{
output('NOT ON STAGE');
}
}
private function onAvail(e:StageVideoAvailabilityEvent) :void{
output(e.availability);
if(e.availability == StageVideoAvailability.AVAILABLE){
output('VIDEO AVAILABLE');
hwaEnabled = true;
}
}
private function startPlaying() :void{
output('STARTING TO PLAY');
video = stage.stageVideos[0];
video.addEventListener(StageVideoEvent.RENDER_STATE, onRender);
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
ns.client = this;
video.attachNetStream(ns);
ns.play(videoFile);
}
private function onRender(e:StageVideoEvent) :void{
output('onRender');
video.viewPort = new Rectangle(192, 50, 640, 480);
}
private function onNetStatus(e:NetStatusEvent) :void{
output(e.info.code);
if(e.info.code == 'Netstream.Play.Stop'){
output('VIDEO STOPPED');
dispatchEvent(new Event(VIDEO_FINISHED));
}
}
private function addDebugPanel() :void{
var tFormat:TextFormat = new TextFormat('Arial', 14, 0x000000, true);
var tField:TextField = new TextField();
tField.setTextFormat(tFormat);
tField.multiline = true;
tField.border = true;
tField.borderColor = 0x000000;
tField.background = true;
tField.backgroundColor = 0xFFFFFF;
tField.x = 0;
tField.y = 568;
tField.width = 1024;
tField.height = 200;
this.debugPanel = tField;
addChild(debugPanel);
}
private function output(what:String) :void{
debugPanel.appendText("\n"+what);
}
public function onXMPData(info:Object) :void{}
public function onMetaData(info:Object) :void{}
public function onCuePoint(info:Object) :void{}
public function onPlayStatus(info:Object) :void{}
}
}
And here's the code I'm using in frame:
import flash.display.Sprite;
import flash.events.MouseEvent;
var vid:SVideo2 = new SVideo2();
addChild(vid);
var btn:Sprite = new Sprite();
btn.graphics.beginFill(0x333333);
btn.graphics.drawRect(0, 0, 100, 40);
btn.x = 462;
btn.y = 518;
btn.width = 100;
btn.height = 40;
addChild(btn);
btn.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent) :void{
var rand:String = String(Math.floor(Math.random() * 37));
vid.playVideo('mp4/result_'+rand+'.mp4');
}
After fighting with this bug, and completely re-writing the code, I found that the reason was because I did not clear the netStream reference attached to the StageVideo, i.e; StageVideo.attachNetStream(null);
This needs to be cleared before/after each new video is played.
Before calling attachNetStream() a second time, call the currently
attached NetStream object's close() method. Calling close() releases
all the resources, including hardware decoders, involved with playing
the video. Then you can call attachNetStream() with either another
NetStream object or null.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/StageVideo.html#attachNetStream%28%29
have you set backgroundAlpha = 0 ? -> s:Application backgroundAlpha=0

Resources