ActionScript 3.0 on animate. Trying to manipulate an instance that was added (addChild) in a frame from another frame. - actionscript

I´m very new to AS. I´m trying to delete an instance that i created in a frame from another frame in animate, but everytime i try i get the same error: 1120:Access of undefined property error. The thing is that this instance is still on stage but i can´t do anything with it if i change from a frame to another.
Code in the frame that the instance was generated:
ico.addEventListener(MouseEvent.CLICK, segui1);
function segui1(event:MouseEvent):void
{
var batata = new pep();
addChild(batata);
batata.x = 448;
batata.y = 277;
resposta[2] = 1;
gotoAndStop(49);
}
heli.addEventListener(MouseEvent.CLICK, segui2);
function segui2(event:MouseEvent):void
{
resposta[2] = 0;
gotoAndStop(49);
}
Code in the frame that i´m trying to delete the instance:
removeChild(batata);

Related

Can't receive value from another class on XNA Framework C#

I have several classes on my project: Game1(main class(default)), Animation and Enemy:
public class Animation
{
public int currentFrameHit;
public Animation ()
{
}
public void Update(GameTime gameTime)
{
timeElapsedHit += gameTime.ElapsedGameTime.Milliseconds;
if (timeElapsedHit > 100)
{
timeElapsedHit = 0;
currentFrameHit = (currentFrameHit + 1) % 9;
}
}
}
How can i get value from variable in Animation class?
In Enemy class i can't receive this value from Animation. I tried that:
Animation animation = new Animation();
Console.WriteLine(animation.currentFrameHit);
But i'm getting null, however in main class Game1 i receive right values with same code.
The problem is that you're making a new Animation() without assigning it to anything. so it'll keep returning it's default value.
So far there isn't enough information given on what the number should be though. Do you have the Animation() class inside the Enemy Class, or do you find the Enemy Class within Animation()?
You need to reference to an existing animation value.
Create an instance in your desire class (here it is Game1) and don't forget to make it public.
public static Animation animationGame1 = new Animation();
Then in your second class:
In LoadContent(): reference it to Game1's variable:
Animation animationNewClass = Game1.animationGame1;
In Update(): do what you want to achieve:
Console.WriteLine(animationNewClass.currentFrameHit);
Hope this helps.

How to get the AutoreleasingUnsafeMutablePointer of a Swift Object

I'm currently the owncloud iOS library for an upload task of my Swift app.
It is written in Objective-C and requires me to pass an AutoreleasingUnsafeMutablePointer<NSProgress?> to the upload method.
Say I create a new object like so
let progress: NSProgress? = NSProgress()
How can I get the AutoreleasingUnsafeMutablePointer<NSProgress?> of this object in Swift?
I tried it the following way:
var progress: NSProgress? = NSProgress()
let unsafeAutoreleasingProgressPointer = AutoreleasingUnsafeMutablePointer<NSProgress?>.init(&progress)
But I get an
EXC_BAD_ACCESS (code=1, address = 0x15942320)
when executing the code. I would like to keep a reference to the progress object because I want to add an observer callback that tells me the upload progress in percent (as also demonstrated in the example link).
AutoreleasingUnsafeMutablePointer is just a struct. All you have to do is create the pointer and then assign the value to its memory property.
var pointer = AutoreleasingUnsafeMutablePointer<NSProgress>.init()
pointer.memory = progress!
There were 2 issues in fact.
We can create an AutoreleasingUnsafeMutablePointer<NSProgress?> object like so:
let progress = NSProgress()
let progressPointer = AutoreleasingUnsafeMutablePointer<NSProgress?>.init(&progress)
It's important to note that you have to keep the pointer around. If you create the pointer in a method, the reference to it will be lost as soon as we exit the method scope. This causes the
EXC_BAD_ACCESS
exception. So your implementation might look like this:
class MyClass: NSObject {
dynamic var progress: NSProgress = NSProgress()
var progressPointer: AutoreleasingUnsafeMutablePointer<NSProgress?> = nil
override init(){
//...
//init non optional variables here
super.init()
progressPointer = AutoreleasingUnsafeMutablePointer<NSProgress?>.init(&progress)
}
}
In my case I did Key-Value Observing because I was using a third party Objective C dependency. Note that you have to put the dynamic keyword in front of the object you want to observe using KVO.
If you still get an
EXC_BAD_ACCESS
exception, use the Singleton pattern.

Debugging trivial functions in Objective-C

Recently I just started working on iOS game programming, and I find several things confusing. (FYI, I am working on a simple game with code provided on makegamewith.us)
First, I just found out that only the main function is executed. By this I mean we use the main function to activate iOS simulator, so that we will be able to load our game. Then I realize that breakpoints only work in main functions. As I put breakpoints in other files (such as creature.m, a game component), despite that I use a function to create creature objects in the game, Xcode won't stop at that function. The iOS simulator will be called, and then the game will be automatically loaded.
So here is the question: how can I debug then?
I assume that function is called when I run the game, but Xcode just ignores any other function in other files except the main function in main.m.
Also, I encountered several "Couldn't find member variable" situations. I wonder how to prevent this from happening. The whole sprite builder publishing to Xcode thing appears blurry. I would appreciate if someone can explain how the whole thing works.
Update:
I realize that I didn't explicitly call any of the functions I have in other files (for instance, Grid.m as shown below). By main function, I mean the int main function in main.m. So the problem might possibly be that I didn't explicitly call that function in main? (but I think what main.m is responsible for is launching the program.)
In main.m:
int main(int argc, char *argv[]) {
#autoreleasepool //if I put a breakpoint here this will definitely work
{
int retVal = UIApplicationMain(argc, argv, nil, #"AppController");
return retVal;
}
}
Grid.m
#import "Grid.h"
#import "Creature.h"
// these are variables that cannot be changed
static const int GRID_ROWS = 8;
static const int GRID_COLUMNS = 10;
#implementation Grid {
NSMutableArray *_gridArray;
float _cellWidth;
float _cellHeight;
}
- (void)onEnter
{
[super onEnter];
[self setupGrid];
// accept touches on the grid
self.userInteractionEnabled = YES;
}
- (void)setupGrid //****if I put breakpoint here, it doesn't work****
{
// divide the grid's size by the number of columns/rows to figure out the right width and height of each cell
_cellWidth = self.contentSize.width / GRID_COLUMNS;
_cellHeight = self.contentSize.height / GRID_ROWS;
float x = 0;
float y = 0;
// initialize the array as a blank NSMutableArray
_gridArray = [NSMutableArray array];
// initialize Creatures
for (int i = 0; i < GRID_ROWS; i++) {
// this is how you create two dimensional arrays in Objective-C. You put arrays into arrays.
_gridArray[i] = [NSMutableArray array];
x = 0;
for (int j = 0; j < GRID_COLUMNS; j++) {
Creature *creature = [[Creature alloc] initCreature];
creature.anchorPoint = ccp(0, 0);
creature.position = ccp(x, y);
[self addChild:creature];
// this is shorthand to access an array inside an array
_gridArray[i][j] = creature;
// make creatures visible to test this method, remove this once we know we have filled the grid properly
creature.isAlive = YES;
x+=_cellWidth;
}
y += _cellHeight;
}
}
#end
Take a look at your main() function -- almost the only thing it does is to call UIApplicationMain(). This is true for any iOS application. So the real work is being done by UIApplicationMain(), and we should find out about that. Here's the description from the docs:
This function instantiates the application object from the principal
class and instantiates the delegate (if any) from the given class and
sets the delegate for the application. It also sets up the main event
loop, including the application’s run loop, and begins processing
events. If the application’s Info.plist file specifies a main nib file
to be loaded, by including the NSMainNibFile key and a valid nib file
name for the value, this function loads that nib file.
So if there's a problem with your app, it's likely related to the application delegate, your AppController class. Set a breakpoint in your -[AppController application:willFinishLaunchingWithOptions:] method -- that's what the application itself will call on its delegate when the app is ready to run. Your UIApplicationMain() call in main() looks OK, so the debugger should hit a breakpoint in your ...didFinishLaunching... method. Step through that method and make sure that you're setting up a window, setting a root view controller, etc. If you're not sure what needs to happen, try creating a new single-view project and looking at the code that's provided there.

Actionscript 2 Proper way to define function on MovieClip

I'm trying to write a function on a MovieClip, and call it from the root clip. What works fine in ActionScript 3 doesn't seem to be working properly in ActionScript 2.
Frame 1 of the _root MovieClip:
var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
newMovieClip.SetNotificationText("Test text");
Frame 1 of the Notification MovieClip:
function SetNotificationText(inputText : String){
notificationText.text = inputText;
}
The result is that the MovieClip is created but the text is not changed.
Am I doing this wrong?
To add functions to a MovieClip in AS2, you need to use one of these methods:
Add the method to the prototype of MovieClip:
MovieClip.prototype.SetNotificationText = function(inputText:String):Void
{
if(this["notificationText"] !== undefined)
{
// If we're going to use the prototype, at least do some checks
// to make sure the caller MovieClip has the text field we expect.
this.notificationText.text = inputText;
}
}
newMovieClip.SetNotificationText("Test text");
Make the MovieClip and argument of the function:
function SetNotificationText(mc:MovieClip, inputText:String):Void
{
mc.notificationText.text = inputText;
}
SetNotificationText(newMovieClip, "Test text");
Add the method directly to the newly created MovieClip:
var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
newMovieClip.SetNotificationText(inputText:String):Void
{
notificationText.text = inputText;
}
newMovieClip.SetNotificationText("Test text");
Option 2 is best overall - it's the cleanest and avoids overhead of creating a new function for every new MovieClip. It also avoids messing around with the prototype, which at best should be used to add generic methods, like a removeItem() method on Array.

XNA 4.0 - What happens when the window is minimized?

I'm learning F#, and decided to try making simple XNA games for windows using F# (pure enthusiasm) , and got a window with some images showing up.
Here's the code:
(*Methods*)
member self.DrawSprites() =
_spriteBatch.Begin()
for i = 0 to _list.Length-1 do
let spentity = _list.List.ElementAt(i)
_spriteBatch.Draw(spentity.ImageTexture,new Rectangle(100,100,(int)spentity.Width,(int)spentity.Height),Color.White)
_spriteBatch.End()
(*Overriding*)
override self.Initialize() =
ChangeGraphicsProfile()
_graphicsDevice <- _graphics.GraphicsDevice
_list.AddSprite(0,"NagatoYuki",992.0,990.0)
base.Initialize()
override self.LoadContent() =
_spriteBatch <- new SpriteBatch(_graphicsDevice)
base.LoadContent()
override self.Draw(gameTime : GameTime) =
base.Draw(gameTime)
_graphics.GraphicsDevice.Clear(Color.CornflowerBlue)
self.DrawSprites()
And the AddSprite Method:
member self.AddSprite(ID : int,imageTexture : string , width : float, height : float) =
let texture = content.Load<Texture2D>(imageTexture)
list <- list # [new SpriteEntity(ID,list.Length, texture,Vector2.Zero,width,height)]
The _list object has a ContentManager, here's the constructor:
type SpriteList(_content : ContentManager byref) =
let mutable content = _content
let mutable list = []
But I can't minimize the window, since when it regains its focus, i get this error:
ObjectDisposedException
Cannot access a disposed object.
Object name: 'GraphicsDevice'.
What is happening?
Well after struggling for some time I got it to work. But it doesn't seem "right"
(thinking that way, using XNA and F# doesn't seem right either, but it's fun.)
(*Methods*)
member self.DrawSprites() =
_spriteBatch.Begin()
for i = 0 to _list.Length-1 do
let spentity = _list.List.ElementAt(i)
if spentity.ImageTexture.IsDisposed then
spentity.ImageTexture <- _list.Content.Load<Texture2D>(spentity.Name)
_spriteBatch.Draw(spentity.ImageTexture,new Rectangle(100,100,(int)spentity.Width,(int)spentity.Height),Color.White)
_spriteBatch.End()
(*Overriding*)
override self.Initialize() =
ChangeGraphicsProfile()
_list.AddSprite(0,"NagatoYuki",992.0,990.0)
base.Initialize()
override self.LoadContent() =
ChangeGraphicsProfile()
_graphicsDevice <- _graphics.GraphicsDevice
_spriteBatch <- new SpriteBatch(_graphicsDevice)
base.LoadContent()
I adjust the graphicsDevice whenever my game needs to LoadContent, and in the DrawSprites() method I check if the texture is disposed, if it is, load it up again.
But this thing bugs me. I didn't know I had to Load all Content again everytime the window is minimized.
(And the code makes it look like Initialize() loads Content, and LoadContent() initializes, but oh well)
What you are observing is normal behaviour, it's by the way not specific to F#. See http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent.aspx
This method is called by Initialize. Also, it is called any time the game content needs to be reloaded, such as when the DeviceReset event occurs.
Are you loading all of your content in Game.LoadContent? If you do, you should not be getting these errors.

Resources