Пример #1
0
        public void initWithImageNamed(string imageName)
        {
            gameObject.name = imageName;
            CCSpriteFrame frame = CCSpriteFrameCache.sharedSpriteFrameCache.spriteFrameByName(imageName);

            if (frame == null)
            {
                CCDebug.Info("cocos2d:CCSprite: try to load '{0}' as a file.", imageName);
                string    path    = FileUtils.GetFilePathWithoutExtends(imageName);
                Texture2D texture = Resources.Load <Texture2D> (path);
                NSUtils.Assert(texture != null, "cocos2d:CCSprite: '{0}' not found.", imageName);
                frame = new CCSpriteFrame(texture, new Rect(Vector2.zero, new Vector2(texture.width, texture.height)));
                frame.frameFileName = path;
                frame.frameFileName = path;
            }
            initWithSpriteFrame(frame);
        }
Пример #2
0
        protected CCDirector()
        {
            CCDebug.Log("cocos2d: cocos2d-iphone v2.1");
            // scenes
            _runningScene = null;
            _nextScene    = null;

//			_notificationNode = nil;

            _oldAnimationInterval = _animationInterval = 1.0f / kDefaultFPS;
            _scenesStack          = new Stack <CCScene> (10);

            // Set default projection (3D)
//			_projection = kCCDirectorProjectionDefault;

            // projection delegate if "Custom" projection is used
//			_delegate = nil;

            // FPS
            _displayStats = false;

            _displayError = false;

//			_totalFrames = _frames = 0;

            // paused ?
            _isPaused = false;

            // running thread
//			_runningThread = null;

            // scheduler
            _scheduler = new CCScheduler();

            // action manager
            _actionManager = new CCActionManager();
            _scheduler.scheduleUpdate(_actionManager, CCScheduler.kCCPrioritySystem, false);

            _winSizeInPixels = Vector2.zero;


            //CCDirectorIOS
//			_ccContentScaleFactor = 1;
//			_isContentScaleSupported = false;
            _touchDispatcher = new CCTouchDispatcher();
        }
Пример #3
0
        //
        // Draw the Scene
        //
        public void drawScene()
        {
            if (_displayError && _lastError != null)
            {
                return;
            }
            try{
                /* calculate "global" dt */
                calculateDeltaTime();

                /* tick before glClear: issue #533 */
                if (!_isPaused)
                {
                    _scheduler.update(_dt);
                }

                /* to avoid flickr, nextScene MUST be here: after tick and before draw.
                 * XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */
                if (_nextScene != null)
                {
                    setNextScene();
                }


                //			DateTime t3 = DateTime.Now;
                _globolRendererSortingOrder = _startGlbolRendererSortingOrder;
                if (_runningScene != null)
                {
                    _runningScene.visit();
                }
            }catch (Exception e) {
                CCDebug.Log(e.ToString());
                if (_displayError)
                {
                    _lastError = e;
                    throw e;
                }
                else
                {
                    Application.Quit();
                }
            }
            showState();

//			_totalFrames++;
        }
Пример #4
0
        public void scheduleBlockForKey(string key, System.Object owner, float interval, uint repeat, float delay, bool paused, TICK_IMP block)
        {
            NSUtils.Assert(block != null, "Argument block must be non-nil");
            NSUtils.Assert(owner != null, "Argument owner must be non-nil");

            tHashTimerEntry element = hashForTimers.HASH_FIND_INT(owner.GetHashCode());

            if (element == null)
            {
                element        = new tHashTimerEntry();
                element.target = owner;
                hashForTimers.HASH_ADD_INT(owner.GetHashCode(), element);

                // Is this the 1st element ? Then set the pause level to all the selectors of this target
                element.paused = paused;
            }
            else
            {
                NSUtils.Assert(element.paused == paused, "CCScheduler. Trying to schedule a block with a pause value different than the target");
            }


            if (element.timers == null)
            {
                element.timers = new List <CCTimer> (10);
            }
            else
            {
                var enumerator = element.timers.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    CCTimer timer = enumerator.Current;
                    if (timer is CCTimerBlock && key == ((CCTimerBlock)timer).key)
                    {
                        CCDebug.Log("CCScheduler#scheduleBlock. Block already scheduled. Updating interval from: {0:0.0000} to {1:0.0000}", timer.interval, interval);
                        timer.interval = interval;
                        return;
                    }
                }
            }

            CCTimerBlock timerBlock = new CCTimerBlock(owner, interval, key, block, repeat, delay);

            element.timers.Add(timerBlock);
        }
Пример #5
0
        /** The scheduled method will be called every 'interval' seconds.
         * If paused is YES, then it won't be called until it is resumed.
         * If 'interval' is 0, it will be called every frame, but if so, it recommended to use 'scheduleUpdateForTarget:' instead.
         * If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
         * repeat lets the action be repeated repeat + 1 times, use kCCRepeatForever to let the action run continuously
         * delay is the amount of time the action will wait before it'll start
         *
         * @since v0.99.3, repeat and delay added in v1.1
         */
        public void schedule(TICK_IMP selector, System.Object target, float interval, uint repeat, bool paused, float delay = 0)
        {
            NSUtils.Assert(selector != null, "Argument selector must be non-nil");
            NSUtils.Assert(target != null, "Argument target must be non-nil");

            tHashTimerEntry element = hashForTimers.HASH_FIND_INT(target.GetHashCode());

            if (element == null)
            {
                element        = new tHashTimerEntry();
                element.target = target;
                hashForTimers.HASH_ADD_INT(target.GetHashCode(), element);

                // Is this the 1st element ? Then set the pause level to all the selectors of this target
                element.paused = paused;
            }
            else
            {
                NSUtils.Assert(element.paused == paused, "CCScheduler. Trying to schedule a selector with a pause value different than the target");
            }


            if (element.timers == null)
            {
                element.timers = new List <CCTimer> (10);
            }
            else
            {
                var enumerator = element.timers.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    CCTimer timer = enumerator.Current;
                    if (timer is CCTimerTargetSelector && selector == ((CCTimerTargetSelector)timer).selector)
                    {
                        CCDebug.Log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: {0:0.0000} to {1:0.0000}", timer.interval, interval);
                        timer.interval = interval;
                        return;
                    }
                }
            }
            CCTimerTargetSelector timerSelector = new CCTimerTargetSelector(target, selector, interval, repeat, delay);

            element.timers.Add(timerSelector);
        }
Пример #6
0
        public void moveToPage(int page)
        {
            if (page < 0 || page >= layers_.Count)
            {
                CCDebug.Error("CCScrollLayer#moveToPage: {0} - wrong page number, out of bounds. ", page);
                return;
            }
            if (this.delegate_ != null)
            {
                this.delegate_.scrollLayerScrollingStarted(this, page);
            }
            isMoving_ = true;
            CCActionFiniteTime changePage = new CCMoveTo(scrollTime_, this.positionForPageWithNumber(page));

            changePage = CCSequence.Actions(changePage, new CCCallFunc(this, moveToPageEnded));
            this.runAction(changePage);
            prevScreen_    = currentScreen_;
            currentScreen_ = page;
        }
        public int playEffect(string filePath)
        {
            if (filePath == null)
            {
                CCDebug.Warning("cocos2d:SimpleAudioEngine: Audio file path should not be null.");
                return(-1);
            }
            AudioClip audio = getAudioClip(filePath);

            if (audio == null)
            {
                CCDebug.Warning("cocos2d:SimpleAudioEngine: Audio {0} not found.", filePath);
                return(-1);
            }
            else
            {
                return(playEffect(audio));
            }
        }
        /** Adds an animation from an NSDictionary
         * Make sure that the frames were previously loaded in the CCSpriteFrameCache.
         * @since v1.1
         */
        public void addAnimationsWithDictionary(NSDictionary dictionary)
        {
            NSDictionary animations = dictionary.objectForKey <NSDictionary>("animations");

            if (animations == null)
            {
                CCDebug.Log("cocos2d: CCAnimationCache: No animations were found in provided dictionary.");
                return;
            }

            int          version    = 1;
            NSDictionary properties = dictionary.objectForKey <NSDictionary>("properties");

            if (properties != null)
            {
                version = properties.objectForKey <int>("format");
            }

            NSArray spritesheets = properties.objectForKey <NSArray>("spritesheets");

            var enumerator = spritesheets.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string name = (string)enumerator.Current;
                CCSpriteFrameCache.sharedSpriteFrameCache.addSpriteFramesWithFile(name);
            }
            switch (version)
            {
            case 1:
                parseVersion1(animations);
                break;

            case 2:
                parseVersion2(animations);
                break;

            default:
                NSUtils.Assert(false, "Invalid animation format");
                break;
            }
        }
Пример #9
0
        /** Returns an Sprite Frame that was previously added.
         * If the name is not found it will return nil.
         * You should retain the returned copy if you are going to use it.
         */
        public CCSpriteFrame spriteFrameByName(string name)
        {
            CCSpriteFrame frame = _spriteFrames [name];

            if (frame == null)
            {
                // try alias dictionary
                string key = _spriteFramesAliases[name];
                if (key != null)
                {
                    frame = _spriteFrames [key];
                }

                if (frame == null)
                {
                    CCDebug.Info("cocos2d: CCSpriteFrameCache: Frame '{0}' not found", name);
                }
            }

            return(frame);
        }
Пример #10
0
        void startAnimation()
        {
            _nextDeltaTimeZero = true;

            if (_isAnimating)
            {
                return;
            }


            // approximate frame rate
            // assumes device refreshes at 60 fps
            int frameInterval = Mathf.FloorToInt(_animationInterval * 60.0f);


            CCDebug.Log("cocos2d: animation started with frame interval: {0:0.00}", 60.0f / frameInterval);

            _displayLink.registWithTarget(this, mainLoop, OnGUI);

            _isAnimating = true;
        }
Пример #11
0
        // ------------------------------------------------------------------------------
        //  Adds multiple Sprite Frames from a plist file.
        // ------------------------------------------------------------------------------

        /** Adds multiple Sprite Frames from a plist file.
         * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png .
         * If you want to use another texture, you should use the addSpriteFramesWithFile:texture method.
         */
        public void addSpriteFramesWithFile(string path)
        {
            path = FileUtils.GetFilePathWithoutExtends(path);
            if (_loadedFilenames.Contains(path))
            {
                CCDebug.Warning("cocos2d: CCSpriteFrameCache: file already loaded: {0}", path);
            }
            else
            {
                _loadedFilenames.Add(path);
                NSDictionary dict    = NSDictionary.DictionaryWithContentsOfFileFromResources(string.Concat(path, ".txt"));
                Texture2D    texture = Resources.Load <Texture2D> (path);
                if (texture != null)
                {
                    addSpriteFrames(dict, texture, path);
                }
                else
                {
                    CCDebug.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture: {0}", path);
                }
            }
        }
Пример #12
0
        /** Preloads a music file so it will be ready to play as background music */
        public void preloadBackgroundMusic(string filePath)
        {
            if (_preLoadedAudios == null)
            {
                _preLoadedAudios = new Dictionary <string, AudioClip> ();
            }
            string ext = Path.GetExtension(filePath);

            if (ext != null && ext.Length > 0)
            {
                filePath = filePath.Replace(ext, "");
            }
            AudioClip audio = Resources.Load <AudioClip> (filePath);

            if (audio == null)
            {
                CCDebug.Warning("cocos2d:SimpleAudioEngine: Audio {0} not found.", filePath);
            }
            else
            {
                _preLoadedAudios [filePath] = audio;
            }
        }
Пример #13
0
        // ------------------------------------------------------------------------------
        //  public runtime metod
        // ------------------------------------------------------------------------------
        public CCFactoryGear takeGear(string category)
        {
            Storage storage = getStorage(category, false);

            if (storage != null)
            {
                while (storage.gears.Count > 0)
                {
                    CCFactoryGear gear = storage.gears[0];
                    storage.gears.RemoveAt(0);
                    gear.gameObject.hideFlags = HideFlags.None;
                    gear.gameObject.SetActive(true);
                    if (gear.gameObject.transform.childCount != 0)
                    {
                        CCDebug.Warning("CCFactory try to take a not empty gear: {0}-{1}.", gear.gameObject, gear.gameObject.transform.GetChild(0));
                        DestroyObject(gear.gameObject);
                    }
                    else
                    {
                        return(gear);
                    }
                }
                //no gear caches
                {
                    Type[] componentTypes = new Type[storage.componentTypeNames.Length];
                    for (int i = 0; i < componentTypes.Length; i++)
                    {
                        componentTypes[i] = Type.GetType(storage.componentTypeNames[i]);
                    }
                    CCFactoryGear gear = buildGear(componentTypes);
                    gear.gameObject.hideFlags = HideFlags.None;
                    gear.gameObject.SetActive(true);
                    return(gear);
                }
            }
            return(null);
        }
Пример #14
0
        static NSDictionary DictionaryWithContentsOfString(string text, FileUtils.ZipDelegate zip = null)
        {
            if (text == null || text.Length == 0)
            {
                return(null);
            }
            try{
                text = System.Text.RegularExpressions.Regex.Replace(text, "<.*\\.dtd\">", string.Empty);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ProhibitDtd    = false;
                settings.ValidationType = ValidationType.None;
                XmlDocument xmlDoc = new XmlDocument();
                using (StringReader sr = new StringReader(text))
                    using (XmlReader reader = XmlReader.Create(sr, settings))
                    {
                        xmlDoc.Load(reader);
                    }

//				XmlDocument xmlDoc = new XmlDocument();
//				xmlDoc.LoadXml (text);

                XmlNode rootNode = xmlDoc.DocumentElement.ChildNodes[0];
                if (rootNode.Name != "dict")
                {
                    return(null);
                }
                NSDictionary dict = NSCollectionUtils.ParseDictionary(rootNode);
                if (dict != null)
                {
                    dict.zip = zip;
                }
                return(dict);
            }catch (Exception e) {
                CCDebug.Warning("NSDicitonary:DictionaryWithContentsOfString:Error:{0}", e);
                return(null);
            }
        }
Пример #15
0
        public bool recycleGear(string category, CCFactoryGear gear, bool constraint = false)
        {
            if (gear.gameObject.transform.childCount != 0)
            {
                CCDebug.Warning("CCFactory try to recyle a not empty gear: {0}-{1}.", gear.gameObject, gear.gameObject.transform.GetChild(0));
                DestroyObject(gear.gameObject);
                return(false);
            }


            Storage storage = getStorage(category, true);

            if (storage.componentTypeNames == null)
            {
                string[] componentTypeNames = new string[gear.components.Length];
                for (int i = 0; i < componentTypeNames.Length; i++)
                {
                    componentTypeNames [i] = gear.components [i].GetType().FullName;
                }
                storage.componentTypeNames = componentTypeNames;
            }
            else if (constraint)
            {
                if (storage.componentTypeNames.Length != gear.components.Length)
                {
                    return(false);
                }
                else
                {
                    HashSet <string> typeSet = new HashSet <string>(storage.componentTypeNames);

                    int count = gear.components.Length;
                    for (int i = 0; i < count; i++)
                    {
                        Component com   = gear.components[i];
                        string    tName = com.GetType().FullName;
                        if (!typeSet.Remove(tName))
                        {
                            return(false);
                        }
                    }
                }
            }

            gear.gameObject.layer = LayerMask.NameToLayer("Default");
            gear.gameObject.transform.SetParent(this.transform);
            gear.gameObject.transform.localEulerAngles = Vector3.zero;
            gear.gameObject.transform.localScale       = new Vector3(1, 1, 1);
            gear.gameObject.transform.localPosition    = Vector3.zero;
            gear.gameObject.name      = string.Format("{0}-{1}", category, storage.gears.Count);
            gear.gameObject.hideFlags = HideFlags.HideInHierarchy;
            gear.gameObject.SetActive(false);
            storage.gears.Add(gear);

            if (gear.gameObject.transform.parent == null)
            {
                NSUtils.Assert(gear.gameObject.transform.parent != null, "Recyle# set parent fail!");
            }

            return(true);
        }
Пример #16
0
        public static CCTMXMap Parse(string file, NSDictionary tilesetCaches = null)
        {
            string      text   = LoadText(file);
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(text);
            XmlNodeList nodeList = xmlDoc.DocumentElement.ChildNodes;

            // get mapWidth, mapHeight, tileWidth, tileHeight
            XmlNode mapNode = xmlDoc.DocumentElement;

            float version = float.Parse(mapNode.Attributes["version"].InnerText);

            if (!FloatUtils.EQ(version, 1.0f))
            {
                CCDebug.Warning("cocos2d:CCTMXMap: Found {0} tmx file, but only 1.0 version was tested.", version);
            }

            string dir = file.Replace(Path.GetFileName(file), "");

            CCTMXMap map = new CCTMXMap();

            map.fileName   = file;
            map.cols       = int.Parse(mapNode.Attributes["width"].InnerText);
            map.rows       = int.Parse(mapNode.Attributes["height"].InnerText);
            map.tileWidth  = int.Parse(mapNode.Attributes["tilewidth"].InnerText);
            map.tileHeight = int.Parse(mapNode.Attributes["tileheight"].InnerText);

            Dictionary <int, string> gidToFiles = new Dictionary <int, string> (256);
            Dictionary <int, Dictionary <string, string> > gidToTileProperties = new Dictionary <int, Dictionary <string, string> > (256);
            List <CCTMXLayer> layers = new List <CCTMXLayer> (8);


            var enumerator = nodeList.GetEnumerator();

            while (enumerator.MoveNext())
            {
                XmlNode nodeData = (XmlNode)enumerator.Current;
                if (nodeData.Name == "tileset")
                {
                    ParseTileset(nodeData, gidToFiles, gidToTileProperties, dir, tilesetCaches);
                }
                else if (nodeData.Name == "layer")
                {
                    CCTMXLayer layer = ParseLayer(nodeData, map.cols, map.rows, gidToFiles, gidToTileProperties);
                    layers.Add(layer);
                }
                else if (nodeData.Name == "objectgroup")
                {
                    CCTMXLayer layer = ParseObjectGroup(nodeData, map.cols, map.rows, map.tileWidth, map.tileHeight, gidToFiles, gidToTileProperties);
                    layers.Add(layer);
                }
                else if (nodeData.Name == "properties")
                {
                    if (map.properties == null)
                    {
                        map.properties = new Dictionary <string, string>();
                    }
                    ParseProperties(nodeData, map.properties);
                }
            }
            map.gidToFiles          = gidToFiles;
            map.gidToTileProperties = gidToTileProperties;
            map.layers = layers.ToArray();
            return(map);
        }
Пример #17
0
 public virtual void update(float dt)
 {
     CCDebug.Log("[Action update]. override me");
 }
Пример #18
0
 public virtual void step(float dt)
 {
     CCDebug.Log("[Action step]. override me");
 }
        static void CheckSemiTransparentSprite(NSDictionary dictionary, Texture2D texture)
        {
            NSDictionary metadataDict = dictionary.objectForKey <NSDictionary>("metadata");
            NSDictionary framesDict   = dictionary.objectForKey <NSDictionary>("frames");

            // get the format
            int format = 0;

            if (metadataDict != null)
            {
                format = metadataDict.objectForKey <int> ("format");
            }

            // get texture size
            Vector2 textureSize = new Vector2(texture.width, texture.height);

            // check the format
            NSUtils.Assert(format >= 0 && format <= 3, @"cocos2d: WARNING: format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:texture:");

            // SpriteFrame info
            Rect rect           = new Rect();
            bool textureRotated = false;

            // add real frames
            var enumerator = framesDict.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyValuePair <object, object> frameDictKeyValue = enumerator.Current;
                NSDictionary frameDict = (NSDictionary)frameDictKeyValue.Value;
                if (format == 0)
                {
                    float x  = frameDict.objectForKey <float>("x");
                    float y  = frameDict.objectForKey <float>("y");
                    float w  = frameDict.objectForKey <float>("width");
                    float h  = frameDict.objectForKey <float>("height");
                    int   ow = frameDict.objectForKey <int>("originalWidth");
                    int   oh = frameDict.objectForKey <int>("originalHeight");
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCDebug.Warning("cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
                    }

                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);

                    // set frame info
                    rect           = new Rect(x, y, w, h);
                    textureRotated = false;
                }
                else if (format == 1 || format == 2)
                {
                    Rect frame   = ccUtils.RectFromString(frameDict.objectForKey <string>("frame"));
                    bool rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        rotated = frameDict.objectForKey <bool>("rotated");
                    }

                    // set frame info
                    rect           = frame;
                    textureRotated = rotated;
                }
                else if (format == 3)
                {
                    // get values
                    Vector2 spriteSize      = ccUtils.PointFromString(frameDict.objectForKey <string>("spriteSize"));
                    Rect    textureRect     = ccUtils.RectFromString(frameDict.objectForKey <string>("textureRect"));
                    bool    textureRotated_ = frameDict.objectForKey <bool>("textureRotated");


                    // set frame info
                    rect           = new Rect(textureRect.position.x, textureRect.position.y, spriteSize.x, spriteSize.y);
                    textureRotated = textureRotated_;
                }
                if (textureRotated)
                {
                    rect.size = new Vector2(rect.size.y, rect.size.x);
                }
                rect.y = textureSize.y - rect.y - rect.height;

                // add sprite frame
                int  rectX  = Mathf.RoundToInt(rect.xMin);
                int  rectY  = Mathf.RoundToInt(rect.yMin);
                int  rectW  = Mathf.RoundToInt(rect.width);
                int  rectH  = Mathf.RoundToInt(rect.height);
                bool isSemi = false;
                for (int x = 0; x < rectW; x++)
                {
                    for (int y = 0; y < rectH; y++)
                    {
                        Color color = texture.GetPixel(rectX + x, rectY + y);
                        if (FloatUtils.Big(color.a, 0) && FloatUtils.Small(color.a, 1))
                        {
                            isSemi = true;
                            break;
                        }
                    }
                    if (isSemi)
                    {
                        break;
                    }
                }
                frameDict.Add("semi", isSemi);
            }
        }
        void parseVersion2(NSDictionary animations)
        {
            CCSpriteFrameCache frameCache = CCSpriteFrameCache.sharedSpriteFrameCache;

            var enumerator = animations.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyValuePair <object, object> kv = enumerator.Current;
                string       name          = (string)kv.Key;
                NSDictionary animationDict = (NSDictionary)kv.Value;

                int    loops    = 0;
                object loopsObj = loops;
                if (!animationDict.TryGetValue("loops", out loopsObj))
                {
                    loops = 1;
                }
                else
                {
                    loops = (int)loopsObj;
                }
                bool    restoreOriginalFrame = (bool)animationDict["restoreOriginalFrame"];
                NSArray frameArray           = (NSArray)animationDict["frames"];


                if (frameArray == null)
                {
                    CCDebug.Log(@"cocos2d: CCAnimationCache: Animation '%@' found in dictionary without any frames - cannot add to animation cache.", name);
                    continue;
                }

                // Array of AnimationFrames
                List <CCAnimationFrame> array = new List <CCAnimationFrame>(frameArray.Count);
                var frameArrayEnumerator      = frameArray.GetEnumerator();
                while (frameArrayEnumerator.MoveNext())
                {
                    NSDictionary  entry           = (NSDictionary)frameArrayEnumerator.Current;
                    string        spriteFrameName = (string)entry["spriteframe"];
                    CCSpriteFrame spriteFrame     = frameCache.spriteFrameByName(spriteFrameName);

                    if (spriteFrame == null)
                    {
                        CCDebug.Log("cocos2d: CCAnimationCache: Animation '{0}' refers to frame '{1}' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName);

                        continue;
                    }

                    float        delayUnits = float.Parse(entry["delayUnits"].ToString());
                    NSDictionary userInfo   = entry.objectForKey <NSDictionary>("notification");

                    CCAnimationFrame animFrame = new CCAnimationFrame(spriteFrame, delayUnits, userInfo);

                    array.Add(animFrame);
                }

                float       delayPerUnit = (float)animationDict["delayPerUnit"];
                CCAnimation animation    = new CCAnimation(array, delayPerUnit, (uint)loops);

                animation.restoreOriginalFrame = restoreOriginalFrame;

                CCAnimationCache.sharedAnimationCache.addAnimation(animation, name);
            }
        }
Пример #21
0
        void addSpriteFrames(NSDictionary dictionary, Texture2D texture, string textureFileName)
        {
            NSDictionary metadataDict = dictionary.objectForKey <NSDictionary>("metadata");
            NSDictionary framesDict   = dictionary.objectForKey <NSDictionary>("frames");

            // get the format
            int format = 0;

            if (metadataDict != null)
            {
                format = metadataDict.objectForKey <int> ("format");
            }

            // get texture size
            Vector2 textureSize = new Vector2(texture.width, texture.height);

            // check the format
            NSUtils.Assert(format >= 0 && format <= 3, @"cocos2d: WARNING: format is not supported for CCSpriteFrameCache addSpriteFramesWithDictionary:texture:");

            // SpriteFrame info
            Rect    rect           = new Rect();
            bool    textureRotated = false;
            Vector2 spriteOffset   = Vector2.zero;
            Vector2 originalSize   = Vector2.zero;
            bool    semi           = false;

            var enumerator = framesDict.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyValuePair <object, object> frameDictKeyValue = enumerator.Current;
                string       frameDictKey = (string)frameDictKeyValue.Key;
                NSDictionary frameDict    = (NSDictionary)frameDictKeyValue.Value;
                if (format == 0)
                {
                    float x  = frameDict.objectForKey <float>("x");
                    float y  = frameDict.objectForKey <float>("y");
                    float w  = frameDict.objectForKey <float>("width");
                    float h  = frameDict.objectForKey <float>("height");
                    float ox = frameDict.objectForKey <float>("offsetX");
                    float oy = frameDict.objectForKey <float>("offsetY");
                    int   ow = frameDict.objectForKey <int>("originalWidth");
                    int   oh = frameDict.objectForKey <int>("originalHeight");
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCDebug.Warning("cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
                    }

                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);

                    // set frame info
                    rect           = new Rect(x, y, w, h);
                    textureRotated = false;
                    spriteOffset   = new Vector2(ox, oy);
                    originalSize   = new Vector2(ow, oh);
                    semi           = frameDict.objectForKey <bool>("semi");
                }
                else if (format == 1 || format == 2)
                {
                    Rect frame   = ccUtils.RectFromString(frameDict.objectForKey <string>("frame"));
                    bool rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        rotated = frameDict.objectForKey <bool>("rotated");
                    }

                    Vector2 offset     = ccUtils.PointFromString(frameDict.objectForKey <string>("offset"));
                    Vector2 sourceSize = ccUtils.PointFromString(frameDict.objectForKey <string>("sourceSize"));

                    // set frame info
                    rect           = frame;
                    textureRotated = rotated;
                    spriteOffset   = offset;
                    originalSize   = sourceSize;
                    semi           = frameDict.objectForKey <bool>("semi");
                }
                else if (format == 3)
                {
                    // get values
                    Vector2 spriteSize       = ccUtils.PointFromString(frameDict.objectForKey <string>("spriteSize"));
                    Vector2 spriteOffset_    = ccUtils.PointFromString(frameDict.objectForKey <string>("spriteOffset"));
                    Vector2 spriteSourceSize = ccUtils.PointFromString(frameDict.objectForKey <string>("spriteSourceSize"));
                    Rect    textureRect      = ccUtils.RectFromString(frameDict.objectForKey <string>("textureRect"));
                    bool    textureRotated_  = frameDict.objectForKey <bool>("textureRotated");

                    // get aliases
                    NSArray aliases           = frameDict.objectForKey <NSArray>("aliases");
                    var     aliasesEnumerator = aliases.GetEnumerator();
                    while (aliasesEnumerator.MoveNext())
                    {
                        string alias = (string)aliasesEnumerator.Current;
                        if (_spriteFramesAliases.ContainsKey(alias))
                        {
                            CCDebug.Warning("cocos2d: WARNING: an alias with name {0} already exists", alias);
                        }

                        _spriteFramesAliases[alias] = frameDictKey;
                    }

                    // set frame info
                    rect           = new Rect(textureRect.position.x, textureRect.position.y, spriteSize.x, spriteSize.y);
                    textureRotated = textureRotated_;
                    spriteOffset   = spriteOffset_;
                    originalSize   = spriteSourceSize;
                    semi           = frameDict.objectForKey <bool>("semi");
                }
                if (textureRotated)
                {
                    rect.size = new Vector2(rect.size.y, rect.size.x);
                }
                rect.y = textureSize.y - rect.y - rect.height;

                // add sprite frame
                CCSpriteFrame spriteFrame = new CCSpriteFrame(texture, rect, textureRotated, spriteOffset, originalSize, semi);
                spriteFrame.frameFileName    = frameDictKey;
                spriteFrame.textureFilename  = textureFileName;
                _spriteFrames [frameDictKey] = spriteFrame;
            }
        }