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(); }
// // 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.Error(e.ToString()); if (_displayError) { _lastError = e; } else { Application.Quit(); } } showState(); // _totalFrames++; }
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); }
/** 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); }
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; }
/** 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; } }
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; }
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 { _currentSource = (_currentSource + 1) % AUDIO_SOURCES_NUM; playAudio(audio, _audioSources[_currentSource], false, _effectsVolume); return(_currentSource); } }
/** 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; if (!_spriteFrames.TryGetValue(name, out frame)) { // try alias dictionary string key; if (_spriteFramesAliases.TryGetValue(name, out key)) { _spriteFrames.TryGetValue(key, out frame); } if (frame == null) { CCDebug.Info("cocos2d: CCSpriteFrameCache: Frame '{0}' not found", name); } } return(frame); }
/** 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; } }
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); } }
void analyze(string image, string plist) { NSDictionary dictionary = NSDictionary.DictionaryWithContentsOfFileFromResources(plist); NSDictionary metadataDict = dictionary.objectForKey <NSDictionary>("metadata"); NSDictionary framesDict = dictionary.objectForKey <NSDictionary>("frames"); Vector2 atlasSize; int format = 0; // get the format if (metadataDict != null) { format = metadataDict.objectForKey <int> ("format"); atlasSize = ccUtils.PointFromString(metadataDict.objectForKey <string> ("size")); } else { NSDictionary texture = dictionary.objectForKey <NSDictionary>("texture"); float width = texture.objectForKey <float>("width"); float height = texture.objectForKey <float>("height"); atlasSize = new Vector2(width, height); } // SpriteFrame info Rect rect = new Rect(); bool isRotated = false; List <SpriteMetaData> metaData = new List <SpriteMetaData> (); // add real frames 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"); 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); isRotated = 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; isRotated = 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); isRotated = textureRotated; } if (isRotated) { rect.size = new Vector2(rect.size.y, rect.size.x); } // add sprite metadata { SpriteMetaData smd = new SpriteMetaData(); smd.name = frameDictKey; rect.y = atlasSize.y - rect.y - rect.height; smd.rect = rect; smd.alignment = (int)UnityEngine.SpriteAlignment.Center; smd.pivot = smd.rect.center; metaData.Add(smd); } } //update texutre importer TextureImporter importer = assetImporter as TextureImporter; if (importer.textureType != TextureImporterType.Advanced) { importer.textureType = TextureImporterType.Sprite; } importer.maxTextureSize = 4096; importer.spriteImportMode = SpriteImportMode.Multiple; importer.spritesheet = metaData.ToArray(); //update #tp.txt string textureBase = plist.Replace(Path.GetFileName(plist), ""); string txtPath = textureBase + Path.GetFileNameWithoutExtension(plist) + "-tp.txt"; // dictionary.writeToFile (assetPath); if (File.Exists(txtPath)) { File.Delete(txtPath); } File.Move(plist, txtPath); //update unity edior widnow AssetDatabase.ImportAsset(txtPath); AssetDatabase.Refresh(); //update asset info // CCTPData data = ScriptableObject.CreateInstance<CCTPData> (); // data.frames = spriteFrames; // data.aliases = spriteFramesAliases; // // string textureBase = plist.Replace(Path.GetFileName(plist), ""); // string assetPath = textureBase + Path.GetFileNameWithoutExtension(plist) + "#tp.asset"; //// string path = Path.ChangeExtension (plist, "tp") + ".asset"; // AssetDatabase.CreateAsset (data, assetPath); // AssetDatabase.SaveAssets (); }
public virtual void step(float dt) { CCDebug.Log("[Action step]. override me"); }
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); } }
public void Debug() { string s = flash.trace(); CCDebug.Log(s); }
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); }
public virtual void update(float dt) { CCDebug.Log("[Action update]. override me"); }
void addSpriteFrames(NSDictionary dictionary, Sprite[] sprites) { Dictionary <string, Sprite> spritesDict = new Dictionary <string, Sprite> (); for (int i = 0; i < sprites.Length; i++) { Sprite s = sprites[i]; spritesDict.Add(s.name, s); } NSDictionary metadataDict = dictionary.objectForKey <NSDictionary>("metadata"); NSDictionary framesDict = dictionary.objectForKey <NSDictionary>("frames"); int format = 0; // get the format if (metadataDict != null) { format = metadataDict.objectForKey <int> ("format"); } // SpriteFrame info // Rect rect = new Rect(); bool isRotated = false; Vector2 frameOffset = Vector2.zero; Vector2 originalSize = Vector2.zero; // add real frames var enumerator = framesDict.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair <object, object> frameDictKeyValue = enumerator.Current; string frameDictKey = (string)frameDictKeyValue.Key; NSDictionary frameDict = (NSDictionary)frameDictKeyValue.Value; CCSpriteFrame spriteFrame = null; 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); isRotated = false; frameOffset = new Vector2(ox, oy); originalSize = new Vector2(ow, oh); // if(isRotated) // rect.size = new Vector2(rect.size.y, rect.size.x); } 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; isRotated = rotated; frameOffset = offset; originalSize = sourceSize; } 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); isRotated = textureRotated; frameOffset = spriteOffset; originalSize = spriteSourceSize; } Sprite spt; if (!spritesDict.TryGetValue(frameDictKey, out spt)) { CCDebug.Warning("cocos2d: WARNING: a sprite frame with name {0} not found", frameDictKey); continue; } // add sprite frame spriteFrame = new CCSpriteFrame(spt, originalSize, frameOffset, isRotated); _spriteFrames.Add(frameDictKey, spriteFrame); } }