How to add a sprite to box2d body? - actionscript-3

I fixed. Problem solved.
I'm new in as3 and box2D, so at least I'm learning. I have a problem to add my sprites(movieclip) to a dynamic body. The sprite appear but it give me an error and because of that all the game-prototype works bad. With the statics I don't have any problem. What can I do?
This is my code:
Before the code I set them as a variable:
private var player:b2Body;
private var mc_player:MovieClip;
Firstly the function of my dynamic body:
public function createPlayer(px:int, py:int):void
{
mc_player = new _pork();
addChild(mc_player);
var playerDef:b2BodyDef = new b2BodyDef();
playerDef.position.Set(px / worldScale, py / worldScale);
playerDef.type = b2Body.b2_dynamicBody;
var playerShape:b2PolygonShape = new b2PolygonShape();
playerShape.SetAsBox(25 / 2 / worldScale, 40 / 2 / worldScale);
var playerForce:b2FixtureDef = new b2FixtureDef();
playerForce.shape = playerShape;
player = world.CreateBody(playerDef);
player.CreateFixture(playerForce);
}
Then a function to add the mc(movieclip):
private function drawPlayer():void
{
mc_player.x = player.GetPosition().x * worldScale;
mc_player.y = player.GetPosition().y * worldScale;
}
And in the update I just call it:
private function update(e:Event):void
{
drawPlayer();
}
The other proprieties I added, like set forces and gravity, this is not the problem.
This are the part where I think is the problem...
The error in flash:
TypeError: Error #1009: No se puede acceder a una propiedad o a un
método de una referencia a un objeto nulo. at Main/drawPlayer() at
Main/update()
I don't have any idea how can I fix it
Any help, please..
Thx everyone!
Edit:
Solution:
Sorry everyone I fail in my code. The error was that I never said to the game call the player when it is in the stage(I means the in the level) and not in the menu...because of this I was calling the player before appear the player. Sorry about my mistake..
So is something like that to call the movieclip player:
private function update(e:Event):void
{
//Call movieclips
if (mc_player) {
drawPlayer(); }
}

When/how is update() getting called? Is it a matter that you've created the callback before the mc_player has been initialized?

Related

as3 1119: Access of possibly undefined property getters/setters

It would be amazing if someone could expand on the current answer, Thanks.
full error
Line 22 1119: Access of possibly undefined property CharacterX through a reference with static type flash.display:DisplayObject.
I'm trying to set a variable for the object shark, that is already defined in the object character
First time using setters in flash, so I might not be doing this right.
code I'm using to set the variable I tried to comment out the stuff I thought was irrelevant to this issue, not actually commented out in real code.
var character:Character;
//var bullet:Bullet=null;
//var bullets:Array = new Array();
//var enemies:Array = new Array();
//character=new Character(bullets);
addChild(character);
var shark:Shark=new Shark();
addChild(shark);
//var enemy:Enemy=null;
////var i:int;
//for (i=0; i<10; i++) {
//enemy = new Enemy(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
//addChild(enemy);
// enemies.push(enemy);
//}
//stage.addEventListener(Event.ENTER_FRAME, colTest);
//function colTest(e:Event ):void {
// if(character.hitTestObject(turtle)){
// character.gotoAndStop("Turtle");
// }
//}
shark.setT(character.x, character.y)
class in which I'm attempting to define a variable using the function above.
package
{
import flash.display.*;
import flash.events.*;
public class Shark extends MovieClip
{
var CharacterX:Number = 0;
var CharacterY:Number = 0;
public function Shark()
{
this.x = 300;
this.y = 200;
addEventListener(Event.ENTER_FRAME,playGame);
}
public function setT(characterx:Number,charactery:Number){
CharacterX = characterx - this.x;
CharacterY = charactery - this.y;
}
function playGame(event:Event):void
{
var ease:int = 20;
var speed:int = 10;
var targetX:int = root.CharacterX - this.x;
var targetY:int = root.CharacterY - this.y;
var rotation = Math.atan2(targetY,targetX) * 180 / Math.PI;
cut code off here, didn't want to make a code dump can get you anything that might be relevant just ask.
Here is a pastebin of all of the code if it might help,
Shark class:
Actions on Frame 1:
Character class
Let me start by saying I can't spot the exact problem here, but I have some ideas. Your error 1999 says that something of the type display object is trying to change your variable. This happens a lot when you use parent.myMethod() because parent is typed as display object. You would fix this by typecasting like (parent as MovieClip).myMethod
In your case I don't see the exact source of this problem. But you could try using this.characterX in your setT function

Actionscript 3 timer is unidentified, how do I fix this?

I'm building a memory Flash game, in which there's a timer that gives you a certain amount of time to finish the deck of cards. The code for this timer is shown below:
public function memory():void
{
levelDuration = 10;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired);
gameTimer.start();
}
function updateTime(e:TimerEvent):void // what happens when the time runs out
{
// your class variable tracking each second,
gameTime--;
//update your user interface as needed
timeText.text = "Tijd : " + String(gameTime); //gameTime is defined before the public function memory
}
function timeExpired(e:TimerEvent):void
{
var gameTimer:Timer = e.target as Timer;
gameTimer.removeEventListener(TimerEvent.TIMER, updateTime);
gameTimer.removeEventListener(TimerEvent.TIMER, timeExpired);
finalScore = score;
musicchannel.stop();
gameTimer.stop();
MovieClip(root).gotoAndStop("gameover");
}
Now, this works fine. The timer counts down, and when it expires, it brings you to the gameover screen. However, when you finish the game BEFORE the time expires, the timer doesn't stop. It will bring you back to the gameover screen when it decides it has run out, even when you've started a new game.
I've tried to fix this by putting gameTimer.stop() in other functions that bring you to the gameover screen, but then there was another problem. This occurred while trying to stop the timer in other functions, like this one (stop button while playing):
function stopplaying(event:MouseEvent){
gameTimer.stop();
finalScore = score;
musicchannel.stop();
MovieClip(root).gotoAndStop("introduction");
}
This will give me a compile error 1120: access of undefined property gameTimer.
I understand that the gameTimer usually can only be influenced within a function if that function listens to a TimerEvent, but I don't see any options to do this in any other way.
I've tried to make gameTimer a public variable, but it won't allow me to do that within the main memory function.
Also, when I try to define it a public variable out of a funcion, but within the class, the timer will still count down. But when it expires, it just gives a random high number in return and doesn't go to the gameover screen.
I hope the explanation of my problem wasn't too vague and that you are able to help me with this. This is a schoolproject and it's due pretty soon! Also, I can't figure this out on my own with internet alone :( Several tries have only made things worse, I'm afraid to screw this up now that I've come this far.
You were doing it probably right-ish by declaring it as a public variable.. but where did you declare it?
In AS (all versions) you have function scope. That means if you declare your variable inside a function, that variable "exists" (is accessible) only inside of that function. Check where you are declaring your variable:
public function memory():void
{
levelDuration = 10;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration); // <-
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired);
gameTimer.start();
}
That means your variable "gameTimer" is local to the function memory(). You won't be able to use your variable anywhere outside of this function because it exists only inside of memory(). To solve this issue, you have move it outside of the function:
private var gameTimer:Timer;
public function memory():void
{
levelDuration = 10;
gameTime = levelDuration;
gameTimer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired);
gameTimer.start();
}
That will solve all your issues.

Noob AS3 question regarding using event handlers to remove MovieClip object from stage

I'm an AS3 noob just trying to get more comfortable working with event handlers in Flash and build interactivity into my application.
In the code below, I have created an instance of the DrawLineChart class called LineChart1. When I test the movie, it shows up on the stage just fine and when I click on it, I can use a trace command to get a string statement written to the output window.
However, now I want to be able to click on LineChart1 on the stage and have it be removed. When I do that, I get an error message 1120: Access of undefined property LineChart1.
Could someone please explain to me why I'm unable to refer to my instance LineChart1 and what I need to do so that I can refer to it and remove it when it gets clicked? Also, I'd love to know why the trace statement works when I click on LineChart1 during runtime, but not the removechild command.
I'm sorry if this question is too simple, but thank you all for your help in advance. I really appreciate it.
package{
import flash.display.*;
import flash.events.*;
public class Main extends MovieClip{
var recWidth:Number = 250;
var recHeight:Number = 550;
var recX:Number = 50;
var recY:Number = 50;
var recScaleY:Number = 30;
public function Main(){
var LineChart1 = new DrawLineChart(recX, recY, recWidth, recHeight, recScaleY);
LineChart1.addEventListener(MouseEvent.CLICK, onClickHandler);
addChild(LineChart1);
}
function onClickHandler(e:Event):void{
trace("hello"); // This works. When I click on the LineChart1 MovieClip on the stage during runtime, I get "hello" as an output.
removeChild(LineChart1); // throws an error 1120: Access of undefined property LineChart1. Why?
}
}
}
Your variable is scoped locally to Main, you need to declare it as an instance variable (class level), to properly define its scope.
private var _lineChart1:DrawLineChart;
//main function
_lineChart1 = new DrawLineChart(...
//handler function
this.removeChild(_lineChart1);
For more information about scope in AS3 = check out the livedocs.
Cheers
Your problem is that you have defined LineChart1 as a local variable. This means that because you declare it inside a function, it is only visible within that function.
Make LineChart1 a property of your class, then you will be able to see it from your event handler. Alternatively, use e.target as DrawLineChart.
All answer's is good but if u have more then one on the stage what can u do ?
You can use an Array to take a list of your mc's and then u can use that Array to remove mc's on the stage.
Here is a Simple Example:
package
{
import flash.display.*;
import flash.events.*;
public class Main extends MovieClip{
private var recWidth:Number = 250;
private var recHeight:Number = 550;
private var recX:Number = 50;
private var recY:Number = 50;
private var recScaleY:Number = 30;
private var lineArray:Array = new Array();
public function Main()
{
for(var i:int = 0;i<10;i++)
{
var LineChart1 = new DrawLineChart(recX, recY, recWidth, recHeight, recScaleY);
LineChart1.addEventListener(MouseEvent.CLICK, onClickHandler);
LineChart1.name = line+i.toString(); // u can use whatever u want for name's
lineArray.push(lineChart1);
addChild(LineChart1);
}
//if u want to place this 10 LineChart1 u can set x and y values like recX += recX and ect.
}
private function onClickHandler(e:Event):void
{
//when u click one of your LineChart1 and want to remove it from stage u can use this
trace(e.currentTarget.name); // if u want to see what is the name of ur mc
var myId:String = e.currentTarget.name.substring(4,10);
removeChild(getChildByName("line"+myId));
}
}
hope it works for u

preloading external .swf with class file as3

so i'm trying to make an external preloader to load my main .swf (loading.swf) file that has a class file named mainLoading.as using this code:
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest("loading.swf"));
var loadingPage:loading = new loading;
function loop (e:ProgressEvent):void{
addChild(loadingPage);
loadingPage.x = stage.stageWidth/2;
loadingPage.y = stage.stageHeight/2;
}
function done (e:Event):void{
removeChild(loadingPage);
addChild(l);
}
so I'm getting an error message saying:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mainLoading()
I think i'm getting the error message because i am accessing the stage in my mainLoading() class file. I tried adding this to the constructor in my class file but it didn't work:
public function mainLoading () {
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event): void {
initStartUpScene ();
}
my initStartUpScene function just throws the intro scene to the loading.swf
any suggestions?
thanks for your help.
(question) is your mainLoading extends either Sprite or Movieclip ?
EDIT
After reading your comment, I would suggest trying this :
Add a function call inside the swf content in your complete progress handler :
function done (e:Event):void{
removeChild(loadingPage);
addChild(l);
Object(l.content).initMethod();
}
content let you access the methods in your loaded .swf main class (e.g. mainLoading)
And replace the event handling in your mainLoading by :
public function mainLoading () {
//no event handling in constructor
}
public function initMethod():void {
//here you go
init();
}
public function init():void { ... //No more event here
Btw it's not the cleanest way to solve your problem.
If that's the exact message you are getting, then yes, adding the ADDED_TO_STAGE listener should have fixed it. Remember to recompile the "loading.swf" if you make any changes to it (a step I always seem to forget)
Does "loading.swf" run just fine without any errors when running it on it's own (not loading it into the "container" SWF)?
This may be unrelated to the question you asked, but you might get better results and avoid some errors by structuring your code like this:
var loadingPage:loading = new loading;
addChild(loadingPage);
loadingPage.x = stage.stageWidth/2;
loadingPage.y = stage.stageHeight/2;
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
l.load(new URLRequest("loading.swf"));
//I renamed this function since I believe "loop" is a reserved keyword.
function onProgress (e:ProgressEvent):void{
//No code needed
}
function onComplete (e:Event):void{
removeChild(loadingPage);
addChild(l);
}
You can remove the "onProgress" function if you won't be needing it as well.
OOOOOOKKKKK, so after about a week of admitting defeat, trying it again, rewriting almost half of my code, trying to convince myself that preloaders are overrated, i finally figured it out (drum roll please):
I had a variable that was referencing the stage being called before my constructor method was called. like this:
private var xScrollPosRight:Number = stage.stageWidth - xScrollPosLeft;
I just changed stage.stageWidth to 750 and it worked.
live and learn.

Why can't my class see an array on the timeline?

I have a class that controls an enemy. From within that class, it checks for collisions with an array on the main timeline. I've done it this way before and it works fine, so I have no idea what I've done wrong this time. It keeps giving me an
ReferenceError: Error #1069: Property
bulletArray not found on
flash.display.Stage and there is no
default value.
error from within the enemy class.
Here's my code (shortened to remove the unimportant parts):
On timeline:
var bulletArray:Array = new Array();
function shoot(e:TimerEvent)
{
var bullet:MovieClip = new Bullet(player.rotation);
bullet.x = player.x;
bullet.y = player.y;
bulletArray.push(bullet);
stage.addChild(bullet);
}
In class:
private var thisParent:*;
thisParent=event.currentTarget.parent;
private function updateBeingShot()
{
for (var i=0; i<thisParent.bulletArray.length; i++) {
if (this.hitTestObject(thisParent.bulletArray[i]) && thisParent.bulletArray[i] != null) {
health--;
thisParent.bulletArray[i].removeEventListener(Event.ENTER_FRAME, thisParent.bulletArray[i].enterFrameHandler);
thisParent.removeChild(thisParent.bulletArray[i]);
thisParent.bulletArray.splice(i,1);
}
}
Any help would be greatly appreciated! Thanks.
My guess is that event.currentTarget is the instance where you declared the bulletArray variable. Using event.currentTarget.parent will refer to stage outside your scope. I don´t know how you declare the listeners. Try using event.target instead of event.currentTarget and see if you get the same error.
My advice is that you put all your code in a class.
If you are going to do it this way you need to pass in a reference to the timeline.
private var _timeline:Object;
// constructor
public function YourClass(timeline:Object) {
_timeline = timeline;
}
private function updateBeginShot() {
// ..
trace(_timeline.bulletArray); // outputs [array contents]
// ..
}