I am loading a mc called Spiri into a mc called Box. Later I want to remove both from memory usage and off screen. I have the off screen in a tween not shown here.
If I use removeChild(box); will it also remove all Children with in?
Basically I am loading 3 movies from library with a function call. Then trying to remove them and call the same function multiple times. Which means the same movies are loaded again and again with the same names. This IS SUPPOSED TO replace the old ones but maybe its not because I am not removing them properly because by the 10th or 15th call it is getting very slow.
I am also adding an event-listener in a function too. Is that then adding a some event-Listner every single time and taking up resources as well?
It seems to be very slow after several times running a that function which makes me believe something is not getting unloaded correctly.
//I tried
box.removeChild(Spiri);
Spiri = null;
//then remove the parent like this
removeChild(box); /// but this gets an error.
again if i just do this
removeChild(Spiri); // it makes me wondering if they are getting removed.
How what is the best way to remove parent and all children in an mc?
Yes and no. The children are no longer located on the stage, but they are still children to the parent until removeChild() is called. That can be good and bad. Obviously, it is great for reusing objects but can be terrible for memory management because those objects can only be garbage collected when their parent is garbage collected. For a simple app, that is usually fine. But for something massive... not so much.
For the project I am working on now (a massive 30 page, 50,000 liner), I created a light-weight GUI framework to handle all of my DisplayObjects. Everything except basic Bitmap and Shape DisplayObjects extend a single class which extends Sprite. In that class, I have this function:
final public function destroy():void {
this.removeAllEventListeners();
var i:int, l:int, cur:DisplayObject;
l = this.numChildren;
for ( i = 0; i < l; i++ ) {
cur = this.getChildAt( i );
if ( cur is XISprite && !this.stopChildXISpriteDestroy ) {
( cur as XISprite ).destroy();
}
else if ( cur is Sprite ) {
( cur as Sprite ).removeChildren();
}
if ( cur is Bitmap && ( cur as Bitmap ).bitmapData && !this.stopBitmapDestroy ) {
( cur as Bitmap ).bitmapData.dispose();
}
if ( cur is Loader && !this.stopLoaderDestroy ) {
( cur as Loader ).unload();
}
if ( cur is Shape ) {
( cur as Shape ).graphics.clear();
}
}
cur = null;
i = l = NaN;
this.removeChildren();
}
It basically does a hard wipe of all the objects and allows me to easily qualify all children of that class for Garbage Collection. I also am keeping track of all event listeners so there is no chance at all a rogue listener could prevent GC (by calling removeAllEventListeners()). I also have some protected flags in the class that allow you to stop the destroy on a certain object type (so I can leave a SWF or an image loaded in memory if needed)
It might be overkill, but memory consumption has been an issue in this app and that function has really helped manage it. This may be more than you need, so you can just call removeChildren() with default params and it will remove all children from the parent object.
As an afterhthought: Keep your DisplayObjectContainers as simple as possible. Avoid nesting them as often as possible. The first conditional, where I call destroy on every single XISprite that is a child of an XISprite is great but it could be disastrous if there were loads and loads of XISprite children as the destroy() calls would pile up on each other and freeze the app.
Related
I'm wandering if this is the optimal way of doing it with ScalaFx: A GUI is composed of bunch of nodes, to which I suck content from a SQL-DB. Main Pane is a FlowPane populated with few hundred elements. Each element is composed of four level hierarchy (see numbers describing the levels):
1 2 3 4
VBox -+-> VBox ---> StackPane -+-> ImageView
+-> Label +-> Rectangle
As far as I have experienced the I can access the nodes and their attributes in different levels. Ie. I can give user feedback by changing the Rectangle color below the ImageView Node as the compound element is chosen by mouse click or by ContextMenu.
I could access the Rectangle attributes directly, but it is easy to make mistakes as the list references children.get(0) are directly dependent from order of the children as the nodes are positioned in parent.
val lvone = vbnode.children // VBox (main)
val lvtwo = lvone.get(0) // VBox
val lvthree = lvtwo.asInstanceOf[javafx.scene.layout.VBox].children.get(0) // StackPane
val lvfour = lvthree.asInstanceOf[javafx.scene.layout.StackPane].children.get(0) // Rectangle
if (lvfour.isInstanceOf[javafx.scene.shape.Rectangle]) lvfour.asInstanceOf[javafx.scene.shape.Rectangle].style = "-fx-fill: #a001fc;"
println("FOUR IS:"+lvfour.getClass)
Here's sample to demonstrate the "safer" access to the elements in node hierarchy (node hierarchy creation is in rather annoying structure of code, so it is not included):
val levelone = vbnode.children
println("LV1 Node userData:"+vbnode.userData) // my database reference for the main / container element
println("LV1 Parent children class:"+levelone.get(0).getClass) // class javafx.scene.layout.VBox
for (leveltwo <- levelone) {
println("LV2 Children Class:"+leveltwo.getClass)
println("LV2 Children Class Simple Name:"+leveltwo.getClass.getSimpleName) // VBox
if (leveltwo.getClass.getSimpleName == "VBox") {
leveltwo.style = "-fx-border-width: 4px;" +
"-fx-border-color: blue yellow blue yellow;"
for (levelthree <- leveltwo.asInstanceOf[javafx.scene.layout.VBox].children) {
println("LV3 children:"+levelthree.getClass.getName)
if (levelthree.getClass.getSimpleName == "StackPane") {
for (levelfour <- levelthree.asInstanceOf[javafx.scene.layout.StackPane].children) {
println("LV4 children:"+levelfour.getClass.getName)
if (levelfour.getClass.getSimpleName == "Rectangle") {
if (levelfour.isInstanceOf[javafx.scene.shape.Rectangle]) println("Rectangle instance confirmed")
println("LV4 Found a Rectangle")
println("original -fx-fill / CSS:"+ levelfour.asInstanceOf[javafx.scene.shape.Rectangle].style)
levelfour.asInstanceOf[javafx.scene.shape.Rectangle].style = "-fx-fill: #a001fc;"
} // end if
} // end for levelfour
} // end if
} // end for levelthree
} // end if
} // end for leveltwo
Questions:
Is there smarter way to do the type casting of node types, since only javafx API based references are acceptable (BTW I'm using ScalaIDE)? Options I am using are:
1- simple / shortcut way: evaluation by using leveltwo.getClass.getSimpleName == "VBox" , which is the shortcut from API jungle. But is it efficient and safe?
2- cluttering way by using probably the by the book style:
if (levelfour.isInstanceOf[javafx.scene.shape.Rectangle])
Other question: Now in reference to the fully qualified reference based on javafx ie. javafx.scene.shape.Rectangle, I would like to use scala reference instead, but I get an error which enforces me to adopt the javafx based reference. Not a big deal as I can use javafx reference, but I wander if there is scalafx based option?
Happy to get constructive feedback.
If I understand you correctly, you seem to be wanting to navigate the nodes of a sub-scene (that belongs to a higher-level UI element construct) in order to change the appearance of some of the nodes within it. Do I have that right?
You raise a number of different issues, all within the one question, so I'll do my best to address them all. As a result, this is going to be a long answer, so please bear with me. BTW, In future, it would help if you ask one question for each issue. ;-)
Firstly, I'm going to take your problem at face value: that you need to browse through a scene in order to identify a Rectangle instance and change its style. (I note that your safe version also changes the style of the second VBox, but I'm going to ignore that for the sake of simplicity.) This is a reasonable course of action if you have little to no control over the structure of each element's UI. (If you directly control this structure, there are far better mechanisms, which I'll come to later.)
At this point, it might be worth expanding on the relationship between ScalaFX and JavaFX. The former is little more than a set of wrappers for the latter, to give the library a Scala flavor. In general, it works like this: the ScalaFX version of a UI class takes a corresponding JavaFX class instance as an argument; it then applies Scala-like operations to it. To simplify things, there are implicit conversions between the ScalaFX and JavaFX instances, so that it (mostly) appears to work by magic. However, to enable this latter feature, you must add the following import to each of your source files that reference ScalaFX:
import sclafx.Includes._
For example, if JavaFX has a javafx.Thing (it doesn't), with setSize and getSize accessor methods, then the ScalaFX version would look like this:
package scalafx
import javafx.{Thing => JThing} // Rename to avoid confusion with ScalaFX Thing.
// ScalaFX wrapper for a Thing.
class Thing(val delegate: JThing) {
// Axilliary default constructor. Let's assume a JThing also has a default
// constructor.
//
// Creates a JavaFX Thing when we don't have one available.
def this() = this(new JThing)
// Scala-style size getter method.
def size: Int = delegate.getSize
// Scala-style size setter method. Allows, say, "size = 5" in your code.
def size_=(newSize: Int): Unit = delegate.setSize(newSize)
// Etc.
}
// Companion with implicit conversions. (The real implementation is slightly
// different.)
object Thing {
// Convert a JavaFX Thing instance to a ScalaFX Thing instance.
implicit def jfxThing2sfx(jThing: JThing): Thing = new Thing(jThing)
// Convert a ScalaFX Thing instance to a JavaFX Thing instance.
implicit def sfxThing2jfx(thing: Thing): JThing = thing.delegate
}
So, quite a lot of work for very little gain, in all honesty (although ScalaFX does simplify property binding and application initialization). Still, I hope you can follow me here. However, this allows you to write code like the following:
import javafx.scene.shape.{Rectangle => JRectangle} // Avoid ambiguity
import scalafx.Includes._
import scalafx.scene.shape.Rectangle
// ...
val jfxRect: JRectangle = new JRectangle()
val sfxRect: Rectangle = jfxRect // Implicit conversion to ScalaFX rect.
val jfxRect2: JRectangle = sfxRect // Implicit conversion to JavaFX rect.
// ...
Next, we come to type checking and casting. In Scala, it's more idiomatic to use pattern matching instead of isInstanceOf[A] and asInstanceOf[A] (both of which are frowned upon).
For example, say you have a Node and you want to see if it is actually a Rectangle (since the latter is a sub-class of the former). In the style of your example, you might write something like the following:
def changeStyleIfRectangle(n: Node): Unit = {
if(n.isInstanceOf[Rectangle]) {
val r = n.asInstanceOf[Rectangle]
r.style = "-fx-fill: #a001fc;"
}
else println("DEBUG: It wasn't a rectangle.")
}
The more idiomatic Scala version of the same code would look like this:
def changeStyleIfRectangle(n: Node): Unit = n match {
case r: Rectangle => r.style = "-fx-fill: #a001fc;"
case _ => println("DEBUG: It wasn't a rectangle.")
}
This may seem a little finicky, but it tends to result in simpler, cleaner code, as I hope you'll see. In particular, note that case r: Rectangle only matches if that is the real type of n, and it then casts n to r as a Rectangle.
BTW, I would expect that comparing types is more efficient than getting the name of the class, via getClass.getSimpleName and comparing to a string, and there's less chance of error. (For example, if you mistype the class name of the string you're comparing to, e.g. "Vbox", instead of "VBox", then this will not result in a compiler error, and the match will always fail.)
As you point out, your direct approach to identifying the Rectangle is limited by the fact that it requires a very specific scene structure. If you change how each element is represented, then you must change your code accordingly, or you'll get a bunch of exceptions.
So let's move on to your safe approach. Clearly, it's going to be a lot slower and less efficient than the direct approach, but it still relies upon the structure of the scene, even if it's less sensitive to the order in which the children are added at each level of hierarchy. If we change the hierarchy, it will likely stop working.
Here's an alternative approach that uses the class hierarchy of the library to assist us. In a JavaFX scene, everything is a Node. Furthermore, nodes that have children (such as VBox and StackPane) are subclasses of Pane as well. We'll use a recursive function to browse the elements below a specified starting Node instance: every Rectangle it encounters will have its style changed.
(BTW, in this particular case, there are some issues with implicit conversions, which makes a pure ScalaFX solution a little cumbersome, so I'm going to match directly on the JavaFX versions of the classes instead, renamed to avoid any ambiguity with the equivalent ScalaFX types. The implicit conversions will work fine when calling this function.)
import javafx.scene.{Node => JNode}
import javafx.scene.layout.{Pane => JPane}
import javafx.scene.shape.{Rectangle => JRectangle}
import scala.collection.JavaConverters._
import scalafx.Includes._
// ...
// Change the style of any rectangles at or below starting node.
def setRectStyle(node: JNode): Unit = node match {
// If this node is a Rectangle, then change its style.
case r: JRectangle => r.style = "-fx-fill: #a001fc;"
// If the node is a sub-class of Pane (such as a VBox or a StackPane), then it
// will have children, so apply the function recursively to each child node.
//
// The observable list of children is first converted to a Scala list to simplify
// matters. This requires the JavaConverters import above.
case p: JPane => p.children.asScala.foreach(setRectStyle)
// Otherwise, just ignore this particular node.
case _ =>
}
// ...
A quick few observations on this function:
You can now use any hierarchy of UI nodes that you like, however, if you have more than one Rectangle node, it will change the style of all of them. If this doesn't work for you, you could add code to check other attributes of each Rectangle to determine which one to modify.
The asScala method is used to convert the children of the Pane node to a Scala sequence, so we can then use the foreach higher-order function to recursively pass each child in turn to the setRectStyle method. asScala is made available by the import scala.collection.JavaConverters._ statement.
Because the function is recursive, but the recursive call is not in the tail position (the last statement of the function), it is not tail-recursive. What this means is if you pass a huge scene to the function, you might get a StackOverflowException. You should be fine with any reasonable size of scene. (However, as an exercise, you might want to write a tail-recursive version so that the function is stack safe.)
This code is going to get slower and less efficient the bigger the scene becomes. Possibly not your top concern in UI code, but a bad smell all the same.
So, as we've seen, having to browse through a scene is challenging, inefficient and potentially error prone. Is there a better way? You bet!
The following will only work if you have control over the definition of the scene for your data elements. If you don't, you're stuck with solutions based upon the above.
The simplest solution is to retain a reference to the Rectangle whose style you want to change as part of a class, then access it directly as needed. For example:
import scalafx.Includes._
import scalafx.scene.control.Label
import scalafx.scene.layout.{StackPane, VBox}
import scalafx.scene.shape.Rectangle
final class Element {
// Key rectangle whose style is updated when the element is selected.
private val rect = new Rectangle {
width = 600
height = 400
}
// Scene representing an element.
val scene = new VBox {
children = List(
new VBox {
children = List(
new StackPane {
children = List(
// Ignore ImageView for now: not too important.
rect // Note: This is the rectangle defined above.
)
}
)
},
new Label {
text = "Some label"
}
)
}
// Call when element selected.
def setRectSelected(): Unit = rect.style = "-fx-fill: #a001fc;"
// Call when element deselected (which I assume you'll require).
def setRectDeselected(): Unit = rect.style = "-fx-fill: #000000;"
}
Clearly, you could pass a data reference as an argument to the class and use that to populate the scene as you like. Whenever you need to change the style, calling one of the two latter functions achieves what you need with surgical precision, no matter what the scene structure looks like.
But there's more!
One of the truly great features about ScalaFX/JavaFX is that it has observable properties that can be used to make the scene manage itself. You will find that most fields on a UI node are of some type "Property". What this allows you to do is to bind a property to the field, such that when you change the property, you change the scene accordingly. When combined with event handlers, the scene takes care of everything all by itself.
Here, I've reworked the latter class. Now, it has a handler that detects when the scene is selected and deselected and reacts by changing the property that defines the style of the Rectangle.
import scalafx.Includes._
import scalafx.beans.property.StringProperty
import scalafx.scene.control.Label
import scalafx.scene.input.MouseButton
import scalafx.scene.layout.{StackPane, VBox}
import scalafx.scene.shape.Rectangle
final class Element {
// Create a StringProperty that holds the current style for the Rectangle.
// Here we initialize it to be unselected.
private val unselected = "-fx-fill: #000000;"
private val selected = "-fx-fill: #a001fc;"
private val styleProp = new StringProperty(unselected)
// A flag indicating whether this element is selected or not.
// (I'm using a var, but this is heavily frowned upon. A better mechanism might be
// required in practice.)
private var isSelected = false
// Scene representing an element.
val scene = new VBox {
children = List(
new VBox {
children = List(
new StackPane {
children = List(
// Ignore ImageView for now: not too important.
// Key rectangle whose style is bound to the above property.
new Rectangle {
width = 600
height = 400
style <== styleProp // <== means "bind to"
}
)
}
)
},
new Label {
text = "Some label"
}
)
// Add an event handler. Whenever the VBox (or any of its children) are
// selected/unselected, we just change the style property accordingly.
//
// "mev" is a "mouse event".
onMouseClicked = {mev =>
// If this is the primary button, then change the selection status.
if(mev.button == MouseButton.Primary) {
isSelected = !isSelected // Toggle selection setting
styleProp.value = if(isSelected) selected
else unselected
}
}
}
}
Let me know how you get on...
MetaTrader4 Expert Advisor for Trade Panel.
How can I link some OBJ_RECTANGLE_LABEL for moving with another single object?
Link 'em indirectly
There is no direct support for linking a few GUI-objects to move with another one.
This does not mean, it is not possible to have it working like this.
In one Augmented Trader UI-tool, I needed to have both all the GUI-components and some computed values behaving under some similar logic ( keeping all the lines, rectangles, text labels and heat-map colors, under some common UI-control-logic ). All the live-interactive-GUI orchestration was locked onto a few permited user-machine interactions, where the user was able to move with a set of UI-control-objects, some of which were freely modify-able, whereas some were restricted ( with the use of the augmented reality controllers ) to move just vertically or just horizontally or were just locked to start as tangents from the edges of Bollinger Bands in such a place, where the vertical line of the UI-control-object was moved by the user, etc.
The Live-interactive-GUI solution is simple:
Besides the [ Expert Advisor ] create and run another process, the [ Script ] that would be responsible for the GUI-object automation. Within this script, use some read-only values from objects, let's say a blue vertical line, as a SENSOR_x1, an input to the GUI-composition.
If someone or something moves this blue vertical line, your event-watching loop inside the script will detect a new value for the SENSOR_x1andre-process all the UI-layout scheme by adding the just observed / detected motion of a SENSOR_x1_delta = SENSOR_x1 - SENSOR_x1_previous;This way, one can update the motion detector-loop in the [ Script ], chasing all the SENSOR_* actual values and promoting the detected SENSOR_*_delta-s onto all objects, that are being used in the GUI-layout composition.
Finally it is worth to stage the updates of the screen with a few enforced WindowRedraw(); instructions, throughout the re-processing of the augmented reality in the Live-interactive-GUI.
Code from a PoC-demonstrator
One may notice, the code is in a pre-New-MQL4.56789 syntax, using some there permitted variable naming conventions, that ceased to be permitted now. The scope of the Event-Monitor function ( a self-contained function, optimised for max speed / min latency in handling all the three corners of the MVC-framework ( Model-is Live-GUI project-specific, Visual-is the Live-GUI augmentation-specific, Controller-is flexible and composed as a sort of Finite-State-Machine, from principal building blocks and implemented via "object.method" calls in the switch(){}. Loop sampling rate works great down to few tens of milliseconds, so the Live-GUI is robust and smoothly floating on the Trader's Desk.
This is not best way but schematically shows what to do.
string mainObjectNAME,
dependantObjectNAME; // dependant - your obj label
void OnChartEvent( const int id,
const long &lparam,
const double &dparam,
const string &sparam
){
if ( id == CHARTEVENT_OBJECT_DRAG
|| id == CHARTEVENT_OBJECT_ENDEDIT
){
if ( StringCompare( sparam, mainObjectNAME ) == 0 ){
datetime time1 = (datetime) ObjectGetInteger( 0, mainObjectNAME, OBJPROP_TIME1 );
double price1 = ObjectGetDouble( 0, dependantObjectNAME, OBJPROP_PRICE1 );
if ( !ObjectMove( 0, dependantObjectNAME, 0, time1, price1 ) )
Print( __LINE__,
"failed to move object ",
dependantObjectNAME
);
}
ChartRedraw();
}
}
if you modify the mainObject by any of the recognised means ( by dragging or passing other parameters ) - then dependant object ( OBJ_RECT_LABEL in your case ) is moved with ObjectMove() or ObjectSet() functions.
I am new to game development but familiar with programming languages. I have started using Flixel and have a working Breakout game with score and lives.
I am just stuck on how I can create a new screen/game over screen if a player runs out of lives. I would like the process to be like following:
Check IF lives are equal to 0
Pause the game and display a new screen (probably transparent) that says 'Game Over'
When a user clicks or hits ENTER restart the level
Here is the function I currently have to update the lives:
private function loseLive(_ball:FlxObject, _bottomWall:FlxObject):void
{
// check for game over
if (lives_count == 0)
{
}
else
{
FlxG:lives_count -= 1;
lives.text = 'Lives: ' + lives_count.toString()
}
}
Here is my main game.as:
package
{
import org.flixel.*;
public class Game extends FlxGame
{
private const resolution:FlxPoint = new FlxPoint(640, 480);
private const zoom:uint = 2;
private const fps:uint = 60;
public function Game()
{
super(resolution.x / zoom, resolution.y / zoom, PlayState, zoom);
FlxG.flashFramerate = fps;
}
}
}
There are multiple ways to go about doing this...
You could use different FlxStates, like I described in the answer to your other post: Creating user UI using Flixel, although you'll have to get smart with passing the score or whatever around, or use a Registry-type setup
If you want it to actually work like you described above, with a transparent-overlay screen, you can try something like this (keep in mind, the exact details may differ for your project, I'm just trying to give you an idea):
First, make sure you have good logic for starting a level, lets say it's a function called StartLevel.
You'll want to define a flag - just a Boolean - that tracks whether or not the game is still going on or not: private var _isGameOver:Boolean; At the very end of StartLevel(), set this to false.
In your create() function for your PlayState, build a new FlxGroup which has all the things you want on your Game Over screen - some text, an image, and something that says "Press ENTER to Restart" (or whatever). Then set it to visible = false. The code for that might look something like:
grpGameOver = new FlxGroup();
grpGameOver.add(new FlxSprite(10,10).makeGraphic(FlxG.Width-20,FlxG.Height-20,0x66000000)); // just a semi-transparent black box to cover your game screen.
grpGameOver.add(new FlxText(...)); // whatever you want to add to the group...
grpGameOver.visible = false;
add(grpGameOver); // add the group to your State.
Depending on how your game is setup, you may also want to set the objects in your group's scrollFactor to 0 - if your game screen scrolls at all:
grpGameOver.setAll("scrollFactor", new FlxPoint(0,0));
In your update() function, you'll need to split it into 2 parts: one for when the game is over, and one for if the game is still going on:
if (_isGameOver)
{
if (FlxG.keys.justReleased("ENTER"))
{
grpGameOver.visible = false;
StartLevel();
}
}
else
{
... the rest of your game logic that you already have ...
}
super.update();
Keep in mind, if you have things that respond to user input anywhere else - like a player object or something, you might need to change their update() functions to check for that flag as well.
Then, the last thing you need to do is in your loseLive() logic:
if (lives_count == 0)
{
_isGameOver = true;
grpGameOver.visible = true;
}
else
...
That should do it!
I would highly recommend spending some time with different tutorials and sample projects to kind of get a better feel for Flixel in general. Photon Storm has some great material to play with (even though he's jumped over to HTML5 games)
I also want to note that if you get comfortable with the way Flixel handles updates, you can get really smart with your state's update() function and have it only call update on the grpGameOver objects, instead of having to change all your other objects updates individually. Pretty advanced stuff, but can be worth it to learn it.
I used spritext() method for the animation, and I tried to release the memory of spritesheets by using the dispose() method, but it is showing error.
How to release the memory of spritesheets?
local spritext = require("spritext")
local arr = {"images/rainbow2.png","images/rainbow1.png"}
local myAnim = spritext.newAnim(arr[1], 600,350, 1, 15);
myAnim.x = display.contentWidth/2;
myAnim.y = display.contentHeight/2 -70;
r:insert(myAnim);
myAnim:play{ startFrame=1, endFrame=15, loop=1 }
local function cleanUp()
myAnim:dispose();
end
Are you using the API for SpriteSheet? I believe that object:dispose is deprecated.
The new way of using it is via SpriteObject, and it inherits from the DisplayObject API.
http://docs.coronalabs.com/api/type/SpriteObject/index.html - SpriteObject
You should able to call object:removeSelf from the DisplayObject API. http://docs.coronalabs.com/api/type/DisplayObject/removeSelf.html
Here is a snippet of how I handle my spritesheets.
-- Import sprite sheet
local someSheet = graphics.newImageSheet( "someimages.png", someInfo:getSheet() ) -- ImageSheet.png is the image Texture packer published
-- Set sprite sequence data.
local someSequenceData = {
{ name="dance", frames={8,1,2,3,4,5,4,3,2,1,8}, time=2000, loopCount=1},
{ name="sad", frames={8,9,8}, time=3000, loopCount=1},
{ name="happy", frames={8,5,8}, time=3000, loopCount=1},
{ name="smile", frames={8,10,8}, time=3000, loopCount=1},
{ name="hit", frames={7,8}, time=2000, loopCount=1}
}
-- load sprite object
spriteObject = display.newSprite( someSheet, someSequenceData )
spriteObject.x = display.contentWidth/2
spriteObject.y = display.contentHeight/2
-- play one of the animations
spriteObject:play("dance")
-- to remove the entire sprite object
spriteObject:removeSelf()
A quick note:
For my spritesheets I use a application called "TexturePacker", I just drop some images in, set some settings, and then it builds a packed sprite sheet, along with a data sheet to go along with it.
EDIT:
I didn't realize this question is rather old.. Oh well. I hope this helps someone out anyway. :P
I'm using Actionscript 2.0 for a mobile phone and can't get my head around Events.
I'm creating a class object with all my code and using a group of functions (all as direct 1st level children of the class). There's one function that creates a Movieclip with a square on it and sets the onPress event to another function called hit:
public function draw1Sqr(sName:String,pTL:Object,sSide:Number,rgb:Number){
// create a movie clip for the Sqr
var Sqr:MovieClip=this.canvas_mc.createEmptyMovieClip(sName,this.canvas_mc.getNextHighestDepth());
// draw square
Sqr.beginFill(rgb);
//etc ...more lines
//setup properties (these are accessible in the event)
Sqr.sSide=sSide;
Sqr.sName=sName;
//setup event
Sqr.onPress = hit; // this syntax seems to lead to 'this' within
// the handler function to be Sqr (movieclip)
//Sqr.onPress = Delegate.create(this, hit);
//I've read a lot about Delegate but it seems to make things harder for me.
}
Then in my event handler, I just cannot get the scope right...
public function hit(){
for (var x in this){
trace(x + " == " + this[x]);
}
//output results
//onPress == [type Function]
//sName == bSqr_7_4
//sSide == 20
trace(eval(this["._parent"])); //undefined
trace(eval(this["._x"])); //undefined
}
For some reason, although the scope is set to the calling object (Sqr, a Movieclip) and I can access properties I defined, I can't use the 'native' properties of a Movieclip object.
Any suggestions on how I can access the _x, _y and other properties of the Movieclip object that is pressed.
Use the array accessor or the dot accessor, but not both. For example:
trace(this._parent); // OR
trace(this["_parent"]);
As for the results of your iteration, I recall AS2 being screwy on this front. IIRC only dynamic properties are returned when looping with for ... in. This prevents Objects (which often serve as hash maps) from including their native properties when all you want are the key/value pairs you set yourself.
Also - the eval() function can be easily overused. Unless you absolutely must execute a String of AS2 that you don't have at compile-time I would recommend avoiding it. Happy coding!