How to add new increase the pool rather then trowing a error.

Im trying to build a game and after many attempts and hours of thinking i did manage to create something that looks like a game.The problem now is that there are so many objects that are constantly creating and removing from the stage. that the game is starting to slow down(it is laggy.).So i have searched the net and understood that i will have to use a "Object pooling Method" rather than creating and removing the objects after i dont have any use of them any more, if i want to make the game more memory friendly.
At first i didnt want to use this method (object pooling) ,but after a while i understood that i dont have a lot of options.So i started to search how and why and how.
Yet in this example im just trying this for the bullets (for now) cause if i can do it for them, i can manage to do it for other objects and projects (it will be simple for me to understand what is happening ., what am i doing , when do i add an existing object from the pool and when im creating a new one(when there are non left, things like this)
i did copy some part of this code from a tutorial that i found in the net but , from then i dont know how to increase the pool rather than throwing this error. I did try to create a new object or to increase the pool length but .... it is not working so im sure that im not doing something the way it must be done.
so i have this so far :
its a "simple" pool that calls a simple shape class (circle dot) and gives that to the main stage when the "SPACE" button is pressed
package
          import flash.display.Sprite;
          import flash.events.Event;
          import flash.display.Bitmap;
          import flash.display.BitmapData;
          import flash.display.Shape;
          public class Bullet extends Sprite{
                    public var  rectangle:Shape = new Shape();
                    public function Bullet(){
                              super();
                              addEventListener(Event.ADDED_TO_STAGE, init);
                              graphics.beginFill(0xFF0000);
                              graphics.drawRect(-5, -5, 10,10);
                              graphics.endFill();
                    private function init(event:Event):void{
the SpritePool where i cant figure out how to replace the throw new error with some new code that will increase the pool
package {
          import flash.display.DisplayObject;
          public class SpritePool {
                    private var pool:Array;
                    private var counter:int;
                    public function SpritePool(type:Class, len:int) {
                              pool = new Array();
                              counter = len;
                              var i:int = len;
                              while (--i > -1) {
                                        pool[i] = new type();
                    public function getSprite():DisplayObject {
                              if (counter > 0) {
                                        return pool[--counter];
                              } else {
                                        throw new Error("You exhausted the pool!");
                    public function returnSprite(s:DisplayObject):void {
                              pool[counter++] = s;
and the Game class (the documents class)
package {
          import flash.ui.Keyboard;
          import flash.display.Sprite;
          import flash.events.Event;
          import flash.events.KeyboardEvent;
          import flash.display.Bitmap;
          import flash.display.BitmapData;
          import flash.display.Shape;
          public class Game extends Sprite {
                    private var ship:Shape;
                    private var bullets:Array;
                    private var pool:SpritePool;
                    public function Game() {
                              Assets.init();
                              addEventListener(Event.ADDED_TO_STAGE, init);
                    private function init(event:Event):void {
                              pool = new SpritePool(Bullet,10);
                              bullets = new Array();
                              ship = new Shape();
                              ship.graphics.beginFill(0xFF00FF);
                              ship.graphics.drawRect(0,0, 60, 60);
                              ship.graphics.endFill();
                              ship.x = stage.stageWidth / 2 - ship.width / 2;
                              ship.y = stage.stageHeight - ship.height;
                              addChild(ship);
                              stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
                              addEventListener(Event.ENTER_FRAME, loop);
                    private function onDown(event:KeyboardEvent):void {
                              if (event.keyCode == Keyboard.SPACE) {
                                        var b:Bullet = pool.getSprite() as Bullet;
                                        b.x = ship.x + ship.width / 2;
                                        b.y = ship.y;
                                        addChild(b);
                                        bullets.push(b);
                                        trace("Bullet fired");
                    private function loop(event:Event):void {
                              for (var i:int=bullets.length-1; i>=0; i--) {
                                        var b:Bullet = bullets[i];
                                        b.y -=  10;
                                        if (b.y < 0) {
                                                  bullets.splice(i, 1);
                                                  removeChild(b);
                                                  pool.returnSprite(b);
                                                  trace("Bullet disposed");
any suggestions/help how to do it

To put you on the path (the errors/events needs formalization), here would be a quick example. Your pool class:
package
          import flash.display.DisplayObject;
          public class SpritePool
                    private var pool:Array;
                    private var counter:int;
                    private var classRef:Class;
                    // public get to know what's left in the pool
                    public function get availableObjects():int
                              return counter;
                    public function SpritePool(type:Class, len:int)
                              classRef = type;
                              pool = new Array();
                              counter = len;
                              var i:int = len;
                              while (--i > -1)
                                        pool[i] = new classRef();
                    public function getSprite():DisplayObject
                              if (counter > 0)
                                        return pool[--counter];
                              else
                                        throw new Error("PoolExhausted");
                    public function returnSprite(s:DisplayObject):void
                              pool[counter++] = s;
                    public function increasePool(amount:int):void
                              counter += amount;
                              while (--amount > -1)
                                        pool.push(new classRef());
                    public function decreasePool(amount:int):void
                              if (counter >= amount)
                                        counter -= amount;
                                        pool.splice(counter - amount,amount);
                              else
                                        throw new Error("PoolDecreaseFail");
Now you'd need to be catching those errors. Again, the errors should be formalized or you could use events by extending IEventDispatcher. I kept it simple.
Here would be the simple Bullet class I'm using:
package
          import flash.display.Sprite;
          public class Bullet extends Sprite
                    private var bullet:Sprite;
                    public function Bullet():void
                              var bullet:Sprite = new Sprite();
                              bullet.graphics.beginFill(0xFF0000,1);
                              bullet.graphics.drawCircle(-5,-5,10);
                              bullet.graphics.endFill();
                              addChild(bullet);
Just draws a red circle just to visualize it..
Here would be a full example of using it. It will import both of these classes (saved as SpritePool.as and Bullet.as in the same folder). Paste this in the actions panel on frame 1:
import SpritePool;
import Bullet; // a simple red 10px circle
import flash.display.Sprite;
import flash.utils.setTimeout;
// fill the pool, swim trunks optional
var pool:SpritePool = new SpritePool(Bullet, 10);
// grab some objects from the pool
// array of currently held objects
var myBullets:Array = new Array();
while (pool.availableObjects > 0)
          myBullets.push(pool.getSprite());
// display in random positions
for (var i:int = 0; i < myBullets.length; i++)
          addChild(myBullets[i]);
          // position
          myBullets[i].x = int(Math.random()*stage.stageWidth);
          myBullets[i].y = int(Math.random()*stage.stageHeight);
trace("myBullets has " + myBullets.length + " bullets! pool has " + pool.availableObjects + " left.");
// now I want one more, but I should check for errors
try
          // fail, none left!
          myBullets.push(pool.getSprite());
catch (e:*)
          // this should be a custom event, but for speed, quick and dirty
          if (e == 'Error: PoolExhausted')
                    trace("D'oh no more bullets! I need more!");
                    pool.increasePool(10);
                    trace("Added 10 more, now available in pool " + pool.availableObjects);
// try to reduce the pool by 15, which should error
try
          pool.decreasePool(15);
catch (e:*)
          // again should be a formal error
          if (e == 'Error: PoolDecreaseFail')
                    trace("Oops, can't reduce pool by 15! Let's trim all extras, available is " + pool.availableObjects);
                    // we know it'll work, no error checking
                    pool.decreasePool(pool.availableObjects);
                    trace("Left in pool: " + pool.availableObjects);
// now lets wait 5 seconds and remove it all back to the pool
setTimeout(ReturnToPool,5000);
function ReturnToPool():void
          // now let's just return all the objects to the pool
          while (myBullets.length > 0)
                    removeChild(myBullets[myBullets.length - 1]);
                    pool.returnSprite(myBullets.pop());
          // now check the pool, should have 10
          trace("Amount of bullets in use " + myBullets.length + ", in pool " + pool.availableObjects);
For ease you can just download my example source (saved down to CS5).
Anything from here is just symantics. For example instead of throwing an error because the pool is too small you could simply increase the pool by a fixed amount yourself and return the objects requested.
To keep objects as low as possible you could use a timer to measure the amount of objects in use over a duration and reduce the pool appropriately, knowing the pool will grow as it needs.
All of this is just to avoid unnecessary object creation.
BTW here's my trace which should match yours:
myBullets has 10 bullets! pool has 0 left.
D'oh no more bullets! I need more!
Added 10 more, now available in pool 10
Oops, can't reduce pool by 15! Let's trim all extras, available is 10
Left in pool: 0
(after 5 seconds)
Amount of bullets in use 0, in pool 10

Similar Messages

  • How to add new row and update existing rows at a time form the upload file

    hi
    How to add new row and update existing rows at a time form the upload file
    example:ztable(existing table)
    bcent                      smh            nsmh         valid date
    0001112465      7.4                       26.06.2007
    0001112466      7.5                       26.06.2007
    000111801                      7.6                       26.06.2007
    1982                      7.8                       26.06.2007
    Flat file structure
    bcent                       nsmh         valid date
    0001112465     7.8     26.06.2007  ( update into above table in nsmh)
    0001112466     7.9     26.06.2007  ( update into above table in nsmh) 
    000111801                     7.6      26.06.2007 ( update into above table in nsmh
    1985                      11              26.06.2007   new row it should insert in table
    thanks,
    Sivagopal R

    Hi,
    First upload the file into an internal table. If you are using a file that is on application server. Use open dataset and close dataset.
    Then :
    Loop at it.
    *insert or modify as per your requirement.
    Endloop.
    Regards,
    Srilatha.

  • CRM  IC Winclient - How to add new fields in the BP Search of TRX CIC0

    Hello Experts,
    I want to know how to add new fields in the BP Search of TRX CIC0. In the HTML that we're using here I need to add the URL of the BP.
    Can you help me?
    Thanks in advance.
    Caíque Escaler

    Hi
    make append to tables in se11 - CCMBP1FIELDS, CCMBP2FIELDS
    in spro in Define customer-specific search control -> mark fields with X.
    and enhance html template CRM_CIC_SEARCH_DISPLAY. -> tcode smw0, look for package CRM_CIC_COMPONENTS for html CRM_CIC_SEARCH_DISPLAY. export it from SAP, edit, and import.
    you will need to enhance function module used for searching - you will find him in spro in Search Strategies.
    Regards
    Radek

  • How to add new fields to the system form (Ex.expenses to a/r invoice form)

    hi
    can any one tell me how to add new fields to the system form (Ex.expenses to a/r invoice form)
    i want to add expenses field to system a/r invoice form and connect data base also.
    i used the code of samples\11.system form manipulation(vb.net) but i'm not able to get it....so can any one help with code or concepts.
    reply soon plz..
    thankQ

    If I understood you correctly, you are just trying to add new fields to the invoice form and then use them in your form. you should first go and add the field to your tables, which you would do by going to Tool --> User Defined Fields --> Manage User Fields. There are different documents or categories given. For ex. for invoices, Sales Orders you would add your field under the Marketing Documents. If you want the field to be just one per invoice, add it to the Title, otherwise if you want a field per invoice or Sales Order line, add it to the Rows section. Once you have done that then you can just create a edit box or drop down to represent the field and set the datasource for that to your field. If you want example code to do that, let me know.

  • How to add new fields to the DME file in F110

    Hi,
    We have a requirement add new fields to the file that is used in  F110.
    .I did go in to DMEE transaction but I hae no idea how to add new fileds to the existing file.
    Can anybody please help me in resolving the issue.
    Thanks
    Venkat
    Edited by: Venkat R on Jun 8, 2009 8:45 AM

    Hi,
    There is no function module for that, We have created our own function module and attached to that field.
    Refer the below code. This will fetch the document number.
    DATA: lwa_item   TYPE dmee_paym_if_type,
            l_fpayp   TYPE fpayp,
            l_fpayhx TYPE fpayhx,
            first_flag TYPE c,
            lv_lifnr   TYPE lifnr,
            voucher_id TYPE string,
            voucher TYPE string,
            invoice_id TYPE belnr_d,
            voucher_len1 TYPE i,
            voucher_len TYPE i.
      TYPES:
      BEGIN OF lt_regup,
            xblnr TYPE xblnr1,
            belnr TYPE belnr_d,
      END OF lt_regup.
      DATA: lt_regup TYPE STANDARD TABLE OF regup,
            lv_regup TYPE regup.
    Hope this helps.
    Raja.A
    Edited by: Raja.A on Feb 16, 2011 7:17 PM

  • How to add new fields in the EBP front end..

    Hi All,
    Can any one let me know the process of how to add new fileds in the shopping cart creation screens by using the "Tag Browser" option in the Object navigator.
    Best Regards,
    Mahesh. J

    Hi
    <b>Please go through the following links for more details and examples -></b>
    http://help.sap.com/saphelp_47x200/helpdata/en/a2/8c6eeb2d8911d596a000a0c94260a5/frameset.htm
    http://help.sap.com/saphelp_47x200/helpdata/en/d3/5ecbe22a8a11d5991f00508b6b8b11/frameset.htm
    This will definitely help.
    <u>For adding customer fields to the Shopping cart, you need to refer SAP OSS Bote 672960 and 485891.</u>
    Do let me know, incase you need any other details.
    Regards
    - Atul

  • HT1296 how to add new photos without deleting the existing photos in ipad

    Hi,
    Can anyone tell me how to add new photos/PDF books from my PC to iPad without deleting the exsting data in iPad?

    Hello AJ2349
    If it is prompting you that it will replace the data on your iPhone, then that is typically the result of syncing with a different computer. The only way you can bypass that is to replace the media on your device and then sync. Now it will only replace items that would be considered purchased items like music, movies, TV shows and Apps and would not delete any pictures from your iPhone. Alternatively you can setup a Shared Photo Stream and then add the Photos there without syncing your iPhone with your computer. Check out the articles below for more information.
    iOS: Issues syncing content with multiple computers using iTunes
    http://support.apple.com/kb/ts1474
    Managing content manually on iPhone, iPad, and iPod
    http://support.apple.com/kb/ht1535
    iCloud: Shared Photo Streams FAQ
    http://support.apple.com/kb/HT5903
    Regards,
    -Norm G.

  • How to add reminders on the new ios6? I don't have the plus (+)on the upper right as seen on ios5 to add reminder.

    How to add reminders on the new ios6? I don't have the plus (+) on the upper right as seen on ios5 to add reminder.

    Also, tap the lines at the top left and create a new list, that should give you the + back.

  • How to Add New Object?

    HI,
    Any body can say how to add new object. For Example: The Document need to link with Invoice Transaction (T.Code: VF01, Table: VBRK/VBRP).
    Points will be rewarded, if information is useful.
    Tks
    Mani.

    Hi
    You can create New objects using the T.code: SE80.
    You can make an object link to SAP objects that are not shown in the possible entries list. To do this, proceed as follows:
    1. In the standard system, there are already two special screens for the module pools SAPLCV130 and SAPLCV140 for the linked SAP object.
    You must create two new screens with the same number for the module pools SAPLCV130 and SAPLCV140. The processing logic must follow that of screen 1204 in program SAPLVC130.
    2. Create function module OBJECT_CHECK_XXXX (XXXX = object name) If the object can be classified, this function module already exists .
    Otherwise copy the function module for linking equipment DOCUMENT_CHECK_EQUI and change it as required for the new object.
    Regards
    S.Sivakumar
    Reward points if useful----

  • How to add new xml item(BAPI requset)?

    Hello
    i want to create bom to ERP from mii
    how to add new xml item(BAPI requset)?
    i use bapi CAD_CREATE_BOM_WITH_SUB_ITEMS
    this bapi's format is
    <table>
    <item>
        <col1>1111</col1>
        <col2>bbbb</col2>
    </item>
    </table>
    i want to add <item>
    like this
    <table>
    <item>
        <col1>1111</col1>
        <col2>bbbb</col2>
    </item>
    <item>
        <col1>22222</col1>
        <col2>bbbb</col2>
    </item>
    </table>
    how to set trx?
    i tryed
    SAP_JCo_Interface_0.Request{/CAD_CREATE_BOM_WITH_SUB_ITEMS/TABLES/BOM_ITEM/item[2]/SORTF}
    when error occured
    use MII12.0
    Edited by: Atsushi Iwasaki on May 18, 2010 6:22 AM

    Hi,
    You can try this alternative
    Step 1) Create XML Document with required structure which you want to pass it to BAPI request.
    Step 2) Populate the XML Row with required contents and map it to above created XML document
    Step 3) Map above created XML Document to BAPI request (use assign XML option dfrom link editor rather tha assign value)
    This will help to map dynamic contents to your BAPI request.
    Regards,
    Shalaka

  • How to add new field into dynamic internal table

    Hello Expert.
    how to add new field into dynamic internal table.
    PARAMETERS: P_TABLE(30).    "table name
    DATA: I_TAB TYPE REF TO DATA.
    FIELD-SYMBOLS: <TAB> TYPE standard TABLE.
    *Create dynamic FS
    create DATA I_TAB TYPE TABLE OF (p_table).
      ASSIGN I_TAB->* TO <TAB>.
    SELECT * FROM (p_table) INTO TABLE <TAB>.
       here i want to add one more field into <TAB> at LAST position and my 
       Field name  =  field_stype     and
       Field type    =  'LVC_T_STYL'
    could you please helpme out .

    Hi,
    Please find the code below.You can add the field acc to your requirement.
    Creating Dynamic internal table
    TYPE-POOLS: slis.
    FIELD-SYMBOLS: <t_dyntable> TYPE STANDARD TABLE,  u201C Dynamic internal table name
                   <fs_dyntable>,                     u201C Field symbol to create work area
                   <fs_fldval> type any.              u201C Field symbol to assign values 
    PARAMETERS: p_cols(5) TYPE c.                     u201C Input number of columns
    DATA:   t_newtable TYPE REF TO data,
            t_newline  TYPE REF TO data,
            t_fldcat   TYPE slis_t_fldcat_alv,
            t_fldcat   TYPE lvc_t_fcat,
            wa_it_fldcat TYPE lvc_s_fcat,
            wa_colno(2) TYPE n,
            wa_flname(5) TYPE c. 
    Create fields .
      DO p_cols TIMES.
        CLEAR wa_it_fldcat.
        move sy-index to wa_colno.
        concatenate 'COL'
                    wa_colno
               into wa_flname.
        wa_it_fldcat-fieldname = wa_flname.
        wa_it_fldcat-datatype = 'CHAR'.
        wa_it_fldcat-intlen = 10.
        APPEND wa_it_fldcat TO t_fldcat.
      ENDDO. 
    Create dynamic internal table and assign to FS
      CALL METHOD cl_alv_table_create=>create_dynamic_table
        EXPORTING
          it_fieldcatalog = t_fldcat
        IMPORTING
          ep_table        = t_newtable. 
      ASSIGN t_newtable->* TO <t_dyntable>. 
    Create dynamic work area and assign to FS
      CREATE DATA t_newline LIKE LINE OF <t_dyntable>.
      ASSIGN t_newline->* TO <fs_dyntable>.
    Populating Dynamic internal table 
      DATA: fieldname(20) TYPE c.
      DATA: fieldvalue(10) TYPE c.
      DATA: index(3) TYPE c. 
      DO p_cols TIMES. 
        index = sy-index.
        MOVE sy-index TO wa_colno.
        CONCATENATE 'COL'
                    wa_colno
               INTO wa_flname. 
    Set up fieldvalue
        CONCATENATE 'VALUE' index INTO
                    fieldvalue.
        CONDENSE    fieldvalue NO-GAPS. 
        ASSIGN COMPONENT  wa_flname
            OF STRUCTURE <fs_dyntable> TO <fs_fldval>.
        <fs_fldval> =  fieldvalue. 
      ENDDO. 
    Append to the dynamic internal table
      APPEND <fs_dyntable> TO <t_dyntable>.
    Displaying dynamic internal table using Grid. 
    DATA: wa_cat LIKE LINE OF fs_fldcat. 
      DO p_cols TIMES.
        CLEAR wa_cat.
        MOVE sy-index TO wa_colno.
        CONCATENATE 'COL'
                    wa_colno
               INTO wa_flname. 
        wa_cat-fieldname = wa_flname.
        wa_cat-seltext_s = wa_flname.
        wa_cat-outputlen = '10'.
        APPEND wa_cat TO fs_fldcat.
      ENDDO. 
    Call ABAP List Viewer (ALV)
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          it_fieldcat = fs_fldcat
        TABLES
          t_outtab    = <t_dyntable>.

  • How to add new fields in Reduced message ( in BD53 )

    Hi Experts,
    How to add new fields in Reduced message ( in BD53 ), when the required field iis available in Table or Structure and need to be added in BD53 so that we can ALE.
    Thanks,
    Ninad

    Hello,
    I think of something like:
    First, you create extension, with transaction WE30.
    Then, reduce your idoc, your extension should also be proposed.
    Do not forget to add this extension in outbound we82, and/or we57 in inbound, and WE20, and find BTE or exit to populate extension.
    regards.
    F.S.

  • PLz Help me its urgent, how to add new field in mm01 basic data screen

    Hi everyone,
         plz tell me how to add new field in mm01 basic data screen,i added that field in basic data screen but when i create a material the data for that field will not save in database table.
    Thanks,
    murali.

    Hi Murali,
    when created added a field on the screen by using user exit then after that you have add the field in main table where you will be getting these table in the userexit only, please make sure about this. And i am sure defenitly it will get updated in to the table.
    reward if useful.
    thanks
    abdulsamee.

  • How to add new line in message on my S890

    My stock keyboard in Lenovo S890 doesn't have enter key, is this normal ? How to add new line ?
    However this happened only in messages, while using whatsapp the enter key present.

    Hi,
    the fact that your question is posted in Order Management section, does the move order automatically generated by OM?
    nevertheless, i don't think you should (or allowed, in this case) to add a new line in transact move order. Transact move order only queries (not create records) the move order lines eligible to allocate and transact.
    So, I don't see why you need to add a new line in transact move order.
    You can, however, add a new line in the allocation of the lines, where for instance, you need to have half of the line allocated to one locator, and the other half to another locator
    Thanks

  • How to add New field in SMART forms.

    How to add new field in the SMART FORMS. Please know me the step.
    Please help me soon.
    Moderator message: Welcome to SCN!
    Moderator message: please search for available information/documentation, do not use a priority higher than normal (no "soon", "ASAP", "earliest" etc.).
    [Rules of engagement|http://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement]
    [Asking Good Questions in the Forums to get Good Answers|/people/rob.burbank/blog/2010/05/12/asking-good-questions-in-the-forums-to-get-good-answers]
    Edited by: Thomas Zloch on Jun 17, 2011 12:31 PM

    How to add new field in the SMART FORMS. Please know me the step.
    Please help me soon.
    Moderator message: Welcome to SCN!
    Moderator message: please search for available information/documentation, do not use a priority higher than normal (no "soon", "ASAP", "earliest" etc.).
    [Rules of engagement|http://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement]
    [Asking Good Questions in the Forums to get Good Answers|/people/rob.burbank/blog/2010/05/12/asking-good-questions-in-the-forums-to-get-good-answers]
    Edited by: Thomas Zloch on Jun 17, 2011 12:31 PM

Maybe you are looking for

  • Hard drive will not partition

    Any steps or changes I need to do in order to partition my hard drive? An error message keeps popping up saying "Couldn't modify partition map because file system verification failed."

  • Acrobat Pro 9 shrinks Word docs when printing

    I have converted a Word 2003 doc using AA Pro 9 by printing to the PDF printer. The PDF pages have larger margins than the Word pages, when printed. I did not have this prob with prior versions. Any hints to correct this would be appreciated. Thanks

  • IWeb application quits unexpectedly

    I have a created page in my iWeb Project that consistently causes the message: "The application iWeb quit unexpectedly. The problem may have been caused by the SFWordProcessing plus-in. Mac OS X and other applications are not affected." The message a

  • Reports paper layout and web layout

    hi. i created a paper layout in reports but when i go to the web layout it is displayed entirely differently. how to get the same layout as that of paper layout in web layout...? the report is having four groupings.. any idea ? thanks in adv. Kris

  • XI 3.0 Trusted Authentication

    When setting up for Trusted Authentication, the TrustedPrincipal.conf file needs to be added to the BO install.  The documentation (Admin Guide) says that it needs to go to <drive>:\Program Files\Files\Business Objects\ BusinessObjects Enterprise 12.