Beispiel #1
0
 public void updateSize(CCPoint touchLocation)
 {
     CCSize s = CCDirector.SharedDirector.WinSize;
     CCSize newSize = new CCSize(Math.Abs(touchLocation.X - s.Width / 2) * 2, Math.Abs(touchLocation.Y - s.Height / 2) * 2);
     CCLayerColor l = (CCLayerColor)GetChildByTag(kTagLayer);
     l.ContentSize = newSize;
 }
 public static CCPoint Transform(CCPoint point, CCAffineTransform t)
 {
     return new CCPoint(
         t.a * point.X + t.c * point.Y + t.tx,
         t.b * point.X + t.d * point.Y + t.ty
         );
 }
        public static void DrawLine(CCPoint origin, CCPoint destination, CCColor4B color)
        {
            var c = new Color(color.R, color.G, color.B, color.A);

            m_Batch.AddVertex(new Vector2(origin.X, origin.Y), c, PrimitiveType.LineList);
            m_Batch.AddVertex(new Vector2(destination.X, destination.Y), c, PrimitiveType.LineList);
        }
Beispiel #4
0
        public override void Update(float time)
        {
            if (m_pTarget != null)
            {
                float xa = 0;
                float xb = m_sConfig.ControlPoint1.X;
                float xc = m_sConfig.ControlPoint2.X;
                float xd = m_sConfig.EndPosition.X;

                float ya = 0;
                float yb = m_sConfig.ControlPoint1.Y;
                float yc = m_sConfig.ControlPoint2.Y;
                float yd = m_sConfig.EndPosition.Y;

                float x = CCSplineMath.CubicBezier(xa, xb, xc, xd, time);
                float y = CCSplineMath.CubicBezier(ya, yb, yc, yd, time);

                CCPoint currentPos = m_pTarget.Position;
                CCPoint diff = currentPos - m_previousPosition;
                m_startPosition = m_startPosition + diff;
        
                CCPoint newPos = m_startPosition + new CCPoint(x, y);
                m_pTarget.Position = newPos;

                m_previousPosition = newPos;
            }
        }
Beispiel #5
0
		public GameMenu ()
		{
			var screenSize = CCDirector.SharedDirector.WinSize;
			
			voiceButtonName = "VoiceFX";
			voiceButtonNameDim = "VoiceFX";
			
			soundButtonName = "SoundFX";
			soundButtonNameDim = "SoundFX";
			
			ambientButtonName = "AmbientFX";
			ambientButtonNameDim = "AmbientFX";
			

			SoundFXMenuLocation = new CCPoint( 110, 55 );
			VoiceFXMenuLocation = new CCPoint( 230, 55 );
			AmbientFXMenuLocation = new CCPoint(355, 55 );
			

			TouchEnabled = true;
			

			IsSoundFXMenuItemActive = !GameData.SharedData.AreSoundFXMuted;

			IsVoiceFXMenuActive = !GameData.SharedData.AreVoiceFXMuted;

			IsAmbientFXMenuActive = !GameData.SharedData.AreAmbientFXMuted;

		}			
Beispiel #6
0
		bool enemyCantBeDamagedForShortInterval; // after damage occurs the enemy gets a moment of un-damage-abilty, which should play better ( I think)
		

		public Enemy (b2World world,
		              CCPoint location,
		              string spriteFileName,
		              bool isTheRotationFixed,
		              bool getsDamageFromGround,
		              bool doesGetDamageFromDamageEnabledStackObjects,
		              int breaksFromHowMuchContact,
		              bool hasDifferentSpritesForDamage,
		              int numberOfFramesToAnimateOnBreak,
		              float density,
		              CreationMethod createHow,
		              int points,
		              BreakEffect simpleScoreVisualFXType )
		{
			InitWithWorld( world,
			               location,
			               spriteFileName,
			               isTheRotationFixed,
			               getsDamageFromGround,
			               doesGetDamageFromDamageEnabledStackObjects,
			               breaksFromHowMuchContact,
			               hasDifferentSpritesForDamage,
			               numberOfFramesToAnimateOnBreak,
			               density,
			               createHow,
			               points,
			               simpleScoreVisualFXType );
		}
        public ParallaxScrollTest()
        {
            CCSize screen = CCDirector.SharedDirector.WinSize;
            parallax = new CCParallaxScrollNode();
            CCSprite land1 = new CCSprite("Images/land_green");
            CCSprite land2 = new CCSprite("Images/land_green");
            parallax.AddInfiniteScrollXWithZ(0, new CCPoint(0.5f, 0.2f), CCPoint.Zero, new CCSprite[] { land1, land2 });

            CCSprite land3 = new CCSprite("Images/land_grey");
            CCSprite land4 = new CCSprite("Images/land_grey");
            parallax.AddInfiniteScrollXWithZ(-2, new CCPoint(0.05f, 0.2f), new CCPoint(0f, 60f), new CCSprite[] { land3, land4 });

            CCSprite clouds1 = new CCSprite("Images/clouds");
            CCSprite clouds2 = new CCSprite("Images/clouds");
            parallax.AddInfiniteScrollXWithZ(1, new CCPoint(0.1f, 0.1f), new CCPoint(0f, screen.Height - clouds1.ContentSize.Height), new CCSprite[] { clouds1, clouds2 });

            for (int i = 0; i < 10; i++)
            {
                CCSprite mountain = new CCSprite("Images/mountain_grey");
                CCPoint pos = new CCPoint(CCMacros.CCRandomBetween0And1() * land1.ContentSize.Width * 2f, (0.1f + 0.24f * CCMacros.CCRandomBetween0And1()) * screen.Height);

                float speedMountainX = 0.15f + CCMacros.CCRandomBetween0And1() * 0.1f;
                parallax.AddChild(mountain, -1, new CCPoint(speedMountainX, .015f), pos, new CCPoint(land1.ContentSize.Width * 2f, 0));

                mountain.Scale = 0.6f + CCMacros.CCRandomBetween0And1() * 0.4f;
            }

            CCSprite sky = new CCSprite("Images/sky_evening");
            sky.AnchorPoint = CCPoint.AnchorLowerLeft;
            AddChild(parallax);
            AddChild(sky, -1);
        }
Beispiel #8
0
        public void addNewSpriteWithCoords(CCPoint p)
        {
            int idx = (int)(CCMacros.CCRandomBetween0And1() * 1400.0f / 100.0f);
            int x = (idx % 5) * 85;
            int y = (idx / 5) * 121;

            CCSprite sprite = new CCSprite("Images/grossini_dance_atlas", new CCRect(x, y, 85, 121));
            AddChild(sprite);

            sprite.Position = p;

            CCActionInterval action;
            float random = CCMacros.CCRandomBetween0And1();

            if (random < 0.20)
                action = new CCScaleBy(3, 2);
            else if (random < 0.40)
                action = new CCRotateBy (3, 360);
            else if (random < 0.60)
                action = new CCBlink (1, 3);
            else if (random < 0.8)
                action = new CCTintBy (2, 0, -255, -255);
            else
                action = new CCFadeOut  (2);
            object obj = action.Reverse();
            CCActionInterval action_back = (CCActionInterval)action.Reverse();
            CCActionInterval seq = (CCActionInterval)(new CCSequence(action, action_back));

            sprite.RunAction(new CCRepeatForever (seq));
        }
 public static void DrawPoints(CCPoint[] points, int numberOfPoints, float size, CCColor4B color)
 {
     for (int i = 0; i < numberOfPoints; i++)
     {
         DrawPoint(points[i], size, color);
     }
 }
Beispiel #10
0
        public override void Update(float time)
        {
            int i, j;
            CCPoint c = m_positionInPixels;

            for (i = 0; i < (m_sGridSize.X + 1); ++i)
            {
                for (j = 0; j < (m_sGridSize.Y + 1); ++j)
                {
                    CCVertex3F v = OriginalVertex(new CCGridSize(i, j));

                    var avg = new CCPoint(i - (m_sGridSize.X / 2.0f), j - (m_sGridSize.Y / 2.0f));
                    var r = (float) Math.Sqrt((avg.X * avg.X + avg.Y * avg.Y));

                    float amp = 0.1f * m_fAmplitude * m_fAmplitudeRate;
                    float a = r * (float) Math.Cos((float) Math.PI / 2.0f + time * (float) Math.PI * m_nTwirls * 2) *
                              amp;

                    float dx = (float) Math.Sin(a) * (v.Y - c.Y) + (float) Math.Cos(a) * (v.X - c.X);
                    float dy = (float) Math.Cos(a) * (v.Y - c.Y) - (float) Math.Sin(a) * (v.X - c.X);

                    v.X = c.X + dx;
                    v.Y = c.Y + dy;

                    SetVertex(new CCGridSize(i, j), ref v);
                }
            }
        }
Beispiel #11
0
 public void SetTouchInfo(int id, float x, float y)
 {
     m_nId = id;
     m_prevPoint = m_point;
     m_point.X = x;
     m_point.Y = y;
 }
Beispiel #12
0
        public StackObject(b2World world, 
		                    CCPoint location,
		                    string spriteFileName,
		                    bool breaksOnGround,
		                    bool breaksFromNinja,
		                    bool hasAnimatedBreakFrames,
		                    bool damagesEnemy,
		                    float density,
		                    CreationMethod createHow,
		                    int angleChange,
		                    bool makeImmovable,
		                    int points,
		                    BreakEffect simpleScoreVisualFXType)
        {
            InitWithWorld(world,
                          location,
                          spriteFileName,
                          breaksOnGround,
                          breaksFromNinja,
                          hasAnimatedBreakFrames,
                          damagesEnemy,
                          density,
                          createHow,
                          angleChange,
                          makeImmovable,
                          points,
                          simpleScoreVisualFXType);
        }
Beispiel #13
0
        public void addNewSpriteWithCoords(CCPoint p)
        {
            CCSpriteBatchNode BatchNode = (CCSpriteBatchNode)GetChildByTag((int)kTags.kTagSpriteBatchNode);

            int idx = (int)(CCRandom.NextDouble() * 1400 / 100);
            int x = (idx % 5) * 85;
            int y = (idx / 5) * 121;


            CCSprite sprite = new CCSprite(BatchNode.Texture, new CCRect(x, y, 85, 121));
            BatchNode.AddChild(sprite);

            sprite.Position = (new CCPoint(p.X, p.Y));

            CCActionInterval action = null;
            float random = (float)CCRandom.NextDouble();

            if (random < 0.20)
                action = new CCScaleBy(3, 2);
            else if (random < 0.40)
                action = new CCRotateBy (3, 360);
            else if (random < 0.60)
                action = new CCBlink (1, 3);
            else if (random < 0.8)
                action = new CCTintBy (2, 0, -255, -255);
            else
                action = new CCFadeOut  (2);

            CCActionInterval action_back = (CCActionInterval)action.Reverse();
            CCActionInterval seq = (CCActionInterval)(new CCSequence(action, action_back));

            sprite.RunAction(new CCRepeatForever (seq));
        }
Beispiel #14
0
 /// <summary>
 /// Initializes a CCMenuItem with a target/selector
 /// </summary>
 /// <param name="selector"></param>
 /// <returns></returns>
 public bool InitWithTarget(Action<object> selector)
 {
     AnchorPoint = new CCPoint(0.5f, 0.5f);
     m_pfnSelector = selector;
     m_bIsEnabled = true;
     m_bIsSelected = false;
     return true;
 }
Beispiel #15
0
		private void InitWithWorld( b2World world, CCPoint location, string spriteFileName)
		{
			this.theWorld = world;
			this.initialLocation = location;
			this.spriteImageName = spriteFileName;
			
			CreateGround();
		}
Beispiel #16
0
        public void resetAndScoreBallForPlayer(int player)
        {
            m_ballStartingVelocity = new CCPoint(m_ballStartingVelocity.X * -1.1f, m_ballStartingVelocity.Y * -1.1f);
            m_ball.Velocity = m_ballStartingVelocity;
            m_ball.Position = new CCPoint(160.0f, 240.0f);

            // TODO -- scoring
        }
Beispiel #17
0
 /// <summary>
 /// Initializes a CCMenuItem with a target/selector
 /// </summary>
 /// <param name="selector"></param>
 /// <returns></returns>
 public bool InitWithTarget(SEL_MenuHandler selector)
 {
     AnchorPoint = new CCPoint(0.5f, 0.5f);
     m_pfnSelector = selector;
     m_bIsEnabled = true;
     m_bIsSelected = false;
     return true;
 }
Beispiel #18
0
 public CCLightningTrack(CCPoint start, CCPoint end)
 {
     _Start = start;
     _End = end;
     _Track = CreateBolt(start, end);
     CCPoint dir = end - start;
     _Length = dir.Normalize();
     _uDir = dir;
 }
        protected internal override void StartWithTarget(CCNode target)
        {
            base.StartWithTarget(target);

            m_fDeltaT = 1f / m_pPoints.Count;

            m_previousPosition = target.Position;
            m_accumulatedDiff = CCPoint.Zero;
        }
Beispiel #20
0
 /// <summary>
 /// Initializes a new <see cref="GestureSample"/>.
 /// </summary>
 /// <param name="gestureType"><see cref="GestureType"/></param>
 /// <param name="timestamp"></param>
 /// <param name="position"></param>
 /// <param name="position2"></param>
 /// <param name="delta"></param>
 /// <param name="delta2"></param>
 public CCGesture(GestureType gestureType, TimeSpan timestamp, CCPoint position, CCPoint position2, CCPoint delta, CCPoint delta2)
 {
     this._gestureType = gestureType;
     this._timestamp = timestamp;
     this._position = position;
     this._position2 = position2;
     this._delta = delta;
     this._delta2 = delta2;
 }
        public virtual bool CollidesWith(CCMaskedSprite target, out CCPoint pt)
        {
            pt = CCPoint.Zero;
            if (!BoundingBox.IntersectsRect(target.BoundingBox))
            {
                return (false);
            }
            // Based upon http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Putting_CD_into_practice.php
            CCAffineTransform m1 = NodeToWorldTransform();
            CCAffineTransform m2 = target.NodeToWorldTransform();
            Matrix mat1 = m1.XnaMatrix;
            Matrix mat2 = m2.XnaMatrix;
            Matrix mat1to2 = mat1 * Matrix.Invert(mat2);
            int width2 = target.Texture.XNATexture.Width;
            int height2 = target.Texture.XNATexture.Height;
            int width1 = Texture.XNATexture.Width;
            int height1 = Texture.XNATexture.Height;
            byte[] maskA = CollisionMask;
            byte[] maskB = target.CollisionMask;
            for (int x1 = 0; x1 < width1; x1++)
            {
                for (int y1 = 0; y1 < height1; y1++)
                {
                    Vector2 pos1 = new Vector2(x1, y1);
                    Vector2 pos2 = Vector2.Transform(pos1, mat1to2);

                    int x2 = (int)pos2.X;
                    int y2 = (int)pos2.Y;
                    if ((x2 >= 0) && (x2 < width2))
                    {
                        if ((y2 >= 0) && (y2 < height2))
                        {
                            int iA = x1 + y1 * width1;
                            int iB = x2 + y2 * width2;
                            if (iA >= maskA.Length || iB >= maskB.Length)
                            {
                                continue;
                            }
                            byte ca = maskA[iA];
                            byte cb = maskB[iB];

                            if (maskA[iA] > 0)
                            {
                                if (maskB[iB] > 0)
                                {
                                    Vector2 screenPos = Vector2.Transform(pos1, mat1);
                                    pt = new CCPoint(screenPos);
                                    return (true);
                                }
                            }
                        }
                    }
                }
            }
            return (false);
        }
Beispiel #22
0
 public IntroLayer()
 {
     m_mouse = new Mouse();
     KeyboardEnabled = true;
     TouchEnabled = true;
     AccelerometerEnabled = true;
     AnchorPoint = new CCPoint(0, 0);
     m_mouse.SetJson(GetPath("walker_magic.json"));
     ScheduleUpdate();
 }
        public override float TestFunc(CCGridSize pos, float time)
        {
            var n = new CCPoint((m_sGridSize.X * (1.0f - time)), (m_sGridSize.Y * (1.0f - time)));
            if (pos.Y == 0)
            {
                return 1.0f;
            }

            return (float) Math.Pow(n.Y / pos.Y, 6);
        }
Beispiel #24
0
 private CCPoint AbsolutePosition()
 {
     CCPoint ret = m_obPosition;
     CCNode cn = this;
     while (cn.Parent != null)
     {
         cn = cn.Parent;
         ret = new CCPoint(ret.X + cn.Position.X, ret.Y + cn.Position.Y);
     }
     return ret;
 }
 public CCParallaxScrollOffset(CCNode node, CCPoint r, CCPoint p, CCPoint s, CCPoint v)
 {
     Child = node;
     Ratio = r;
     Offset = s;
     RelativeVelocity = v;
     Child.Position = p;
     OriginalPosition = p;
     //currPosition = p;
     Child.AnchorPoint = CCPoint.AnchorLowerLeft;
 }
Beispiel #26
0
		private void InitWithWorld (b2World world, CCPoint location, string baseFileName)
		{
			
			theWorld = world;
			initialLocation = location;
			baseImageName = baseFileName;
			
			
			//later we use initialLocation.x 
			
			CreateNinja();
		}
Beispiel #27
0
 public CCLayer(CCClipMode clipMode)
 {
     m_childClippingMode = clipMode;
     AnchorPoint = new CCPoint(0.5f, 0.5f);
     m_bIgnoreAnchorPointForPosition = true;
     CCDirector director = CCDirector.SharedDirector;
     if (director != null)
     {
         ContentSize = director.WinSize;
     }
     Init();
 }
Beispiel #28
0
 public void SetTouchInfo(int id, float x, float y)
 {
     m_nId = id;
     m_prevPoint = m_point;
     m_point.X = x;
     m_point.Y = y;
     if (!m_startPointCaptured)
     {
         m_startPoint = m_point;
         m_startPointCaptured = true;
     }
 }
Beispiel #29
0
		void InitWithWorld(b2World world,
		                    CCPoint location,
		                    string spriteFileName,
		                    bool isTheRotationFixed,
		                    bool getsDamageFromGround,
		                    bool doesGetDamageFromDamageEnabledStackObjects,
		                    int breaksFromHowMuchContact,
		                    bool hasDifferentSpritesForDamage,
		                    int numberOfFramesToAnimateOnBreak,
		                    float density,
		                    CreationMethod createHow,
		                    int points,
		                    BreakEffect simpleScoreVisualFXType )
		{
			this.theWorld = world;
			this.initialLocation = location;
			this.baseImageName = spriteFileName;
			this.spriteImageName =  String.Format("{0}.png", baseImageName);
			
			this.DamagesFromGroundContact = getsDamageFromGround; // does the ground break / damage the enemy
			
			this.damageLevel = 0; //starts at 0, if breaksAfterHowMuchContact also equals 0 then the enemy will break on first/next contact
			this.breaksAfterHowMuchContact = breaksFromHowMuchContact; //contact must be made this many times before breaking, or if set to 0, the enemy will break on first/next contact 
			this.differentSpritesForDamage = hasDifferentSpritesForDamage; //will progress through damage frames if this is YES, for example,  enemy_damage1.png, enemy_damage2.png
			
			this.currentFrame = 0;
			this.framesToAnimateOnBreak = numberOfFramesToAnimateOnBreak;  //will animate through breaks frames if this is more than 0, for example,  enemy_break0001.png, enemy_break0002.png
			
			
			this.theDensity = density;
			this.shapeCreationMethod = createHow;
			
			this.isRotationFixed = isTheRotationFixed;
			
			this.PointValue = points ;
			this.SimpleScoreVisualFX = simpleScoreVisualFXType;
			
			this.DamagesFromDamageEnabledStackObjects = doesGetDamageFromDamageEnabledStackObjects; 
			
			
			if ( damageLevel == breaksAfterHowMuchContact) {  
				BreaksOnNextDamage = true;
			} else {
				BreaksOnNextDamage = false; //duh
				
			}
			
			
			CreateEnemy();
			

		}
Beispiel #30
0
		public static CCSprite AddSpriteToTargetWithPosAndAnchor(string spriteName, CCNode target, CCPoint pos, CCPoint anchor)
		{
			var sprite = new CCSprite(spriteName);
    
			if (sprite == null)
				return null;

			sprite.Position = pos;
			sprite.AnchorPoint = anchor;
			target.AddChild(sprite);

			return sprite;
		}
Beispiel #31
0
 public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset)
 {
     InitWithString(str, fntFile, width, alignment, imageOffset);
 }
Beispiel #32
0
        public void CreateFontChars()
        {
            int nextFontPositionX = 0;
            int nextFontPositionY = 0;
            //unsigned short prev = -1;
            int kerningAmount = 0;

            CCSize tmpSize = CCSize.Zero;

            int longestLine = 0;
            int totalHeight = 0;

            int quantityOfLines = 1;

            int stringLen = m_sString.Length;

            if (stringLen == 0)
            {
                return;
            }

            for (int i = 0; i < stringLen - 1; ++i)
            {
                if (m_sString[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            totalHeight       = m_pConfiguration.m_nCommonHeight * quantityOfLines;
            nextFontPositionY = 0 - (m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);

            for (int i = 0; i < stringLen; i++)
            {
                char c = m_sString[i];

                if (c == '\n')
                {
                    nextFontPositionX  = 0;
                    nextFontPositionY -= m_pConfiguration.m_nCommonHeight;
                    continue;
                }

                // unichar is a short, and an int is needed on HASH_FIND_INT
                CCBMFontConfiguration.ccBMFontDef fontDef = m_pConfiguration.m_pFontDefDictionary[c];

                CCRect rect = fontDef.rect;
                rect = CCMacros.CCRectanglePixelsToPoints(rect);

                rect.Origin.X += m_tImageOffset.X;
                rect.Origin.Y += m_tImageOffset.Y;

                CCSprite fontChar;

                fontChar = (CCSprite)(GetChildByTag(i));
                if (fontChar == null)
                {
                    fontChar = new CCSprite(m_pobTextureAtlas.Texture, rect);
                    AddChild(fontChar, 0, i);
                }
                else
                {
                    // reusing fonts
                    fontChar.SetTextureRect(rect, false, rect.Size);

                    // restore to default in case they were modified
                    fontChar.Visible = true;
                    fontChar.Opacity = 255;
                }

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
                var fontPos = new CCPoint((float)nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
                                          (float)nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
                fontChar.Position = CCMacros.CCPointPixelsToPoints(fontPos);

                // update kerning
                nextFontPositionX += fontDef.xAdvance + kerningAmount;
                //prev = c;

                // Apply label properties
                fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;
                // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
                fontChar.Color = m_tColor;

                // only apply opacity if it is different than 255 )
                // to prevent modifying the color too (issue #610)
                if (m_cOpacity != 255)
                {
                    fontChar.Opacity = m_cOpacity;
                }

                if (longestLine < nextFontPositionX)
                {
                    longestLine = nextFontPositionX;
                }
            }

            tmpSize.Width  = longestLine;
            tmpSize.Height = totalHeight;

            ContentSize = CCMacros.CCSizePixelsToPoints(tmpSize);
        }
Beispiel #33
0
        private CCActionInterval GetAction(CCBKeyframe pKeyframe0, CCBKeyframe pKeyframe1, string pPropName, CCNode node)
        {
            float duration = pKeyframe1.Time - (pKeyframe0 != null ? pKeyframe0.Time : 0);

            switch (pPropName)
            {
            case "rotation":
            {
                var value = (CCBValue)pKeyframe1.Value;
                return(new CCBRotateTo(duration, value.GetFloatValue()));
            }

            case "opacity":
            {
                var value = (CCBValue)pKeyframe1.Value;
                return(new CCFadeTo(duration, value.GetByteValue()));
            }

            case "color":
            {
                var       color = (ccColor3BWapper)pKeyframe1.Value;
                CCColor3B c     = color.getColor();

                return(new CCTintTo(duration, c.R, c.G, c.B));
            }

            case "visible":
            {
                var value = (CCBValue)pKeyframe1.Value;
                if (value.GetBoolValue())
                {
                    return(new CCSequence(new CCDelayTime(duration), new CCShow()));
                }
                return(new CCSequence(new CCDelayTime(duration), new CCHide()));
            }

            case "displayFrame":
                return(new CCSequence(new CCDelayTime(duration), new CCBSetSpriteFrame((CCSpriteFrame)pKeyframe1.Value)));

            case "position":
            {
                // Get position type
                var array = (List <CCBValue>)GetBaseValue(node, pPropName);
                var type  = (CCBPositionType)array[2].GetIntValue();

                // Get relative position
                var   value = (List <CCBValue>)pKeyframe1.Value;
                float x     = value[0].GetFloatValue();
                float y     = value[1].GetFloatValue();

                CCSize containerSize = GetContainerSize(node.Parent);

                CCPoint absPos = CCBHelper.GetAbsolutePosition(new CCPoint(x, y), type, containerSize, pPropName);

                return(new CCMoveTo(duration, absPos));
            }

            case "scale":
            {
                // Get position type
                var array = (List <CCBValue>)GetBaseValue(node, pPropName);
                var type  = (CCBScaleType)array[2].GetIntValue();

                // Get relative scale
                var   value = (List <CCBValue>)pKeyframe1.Value;
                float x     = value[0].GetFloatValue();
                float y     = value[1].GetFloatValue();

                if (type == CCBScaleType.MultiplyResolution)
                {
                    float resolutionScale = CCBReader.ResolutionScale;
                    x *= resolutionScale;
                    y *= resolutionScale;
                }

                return(new CCScaleTo(duration, x, y));
            }

            default:
                CCLog.Log("CCBReader: Failed to create animation for property: {0}", pPropName);
                break;
            }

            return(null);
        }
Beispiel #34
0
 public void DrawCircle(CCPoint center, float radius, CCColor4B color)
 {
     DrawCircle(center, radius, CCMacros.CCDegreesToRadians(360f), 360, color);
 }
Beispiel #35
0
        /**
         * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
         *
         * @param offset new offset
         * @param If YES, the view scrolls to the new offset
         */

        public void SetContentOffset(CCPoint offset)
        {
            SetContentOffset(offset, false);
        }
Beispiel #36
0
 public CCParallaxNode()
 {
     m_pParallaxArray = new List <CCPointObject>(5);
     m_tLastPosition  = new CCPoint(-100, -100);
 }
Beispiel #37
0
        private void ProcessGamePad(GamePadState gps, PlayerIndex player)
        {
            GamePadState lastState = new GamePadState();

            if (m_PriorGamePadState.ContainsKey(player))
            {
                lastState = m_PriorGamePadState[player];
                // Notify listeners when the gamepad is connected.
                if ((lastState.IsConnected != gps.IsConnected) && GamePadConnectionUpdate != null)
                {
                    GamePadConnectionUpdate(player, false);
                }
                // TODO: Check button pressed/released status for button tap events.
            }
            if (gps.IsConnected)
            {
                GamePadCapabilities caps = GamePad.GetCapabilities(player);
                if (GamePadButtonUpdate != null)
                {
                    CCGamePadButtonStatus back          = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus start         = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus system        = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus a             = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus b             = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus x             = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus y             = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus leftShoulder  = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus rightShoulder = CCGamePadButtonStatus.NotApplicable;
                    if (caps.HasBackButton)
                    {
                        back = (gps.Buttons.Back == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasStartButton)
                    {
                        start = (gps.Buttons.Start == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasBigButton)
                    {
                        system = (gps.Buttons.BigButton == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasAButton)
                    {
                        a = (gps.Buttons.A == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasBButton)
                    {
                        b = (gps.Buttons.B == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasXButton)
                    {
                        x = (gps.Buttons.X == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasYButton)
                    {
                        y = (gps.Buttons.Y == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasLeftShoulderButton)
                    {
                        leftShoulder = (gps.Buttons.LeftShoulder == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasRightShoulderButton)
                    {
                        rightShoulder = (gps.Buttons.RightShoulder == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    GamePadButtonUpdate(back, start, system, a, b, x, y, leftShoulder, rightShoulder, player);
                }
                // Process the game sticks
                if (GamePadStickUpdate != null && (caps.HasLeftXThumbStick || caps.HasLeftYThumbStick || caps.HasRightXThumbStick || caps.HasRightYThumbStick || caps.HasLeftStickButton || caps.HasRightStickButton))
                {
                    CCPoint vecLeft;
                    if (caps.HasLeftXThumbStick || caps.HasLeftYThumbStick)
                    {
                        vecLeft = new CCPoint(gps.ThumbSticks.Left);
                        vecLeft.Normalize();
                    }
                    else
                    {
                        vecLeft = CCPoint.Zero;
                    }
                    CCPoint vecRight;
                    if (caps.HasRightXThumbStick || caps.HasRightYThumbStick)
                    {
                        vecRight = new CCPoint(gps.ThumbSticks.Right);
                        vecRight.Normalize();
                    }
                    else
                    {
                        vecRight = CCPoint.Zero;
                    }
                    CCGameStickStatus left = new CCGameStickStatus();
                    left.Direction = vecLeft;
                    left.Magnitude = ((caps.HasLeftXThumbStick || caps.HasLeftYThumbStick) ? gps.ThumbSticks.Left.Length() : 0f);
                    left.IsDown    = ((caps.HasLeftStickButton) ? gps.IsButtonDown(Buttons.LeftStick) : false);
                    CCGameStickStatus right = new CCGameStickStatus();
                    right.Direction = vecRight;
                    right.Magnitude = ((caps.HasRightXThumbStick || caps.HasRightYThumbStick) ? gps.ThumbSticks.Right.Length() : 0f);
                    right.IsDown    = ((caps.HasLeftStickButton) ? gps.IsButtonDown(Buttons.RightStick) : false);
                    GamePadStickUpdate(left, right, player);
                }
                // Process the game triggers
                if (GamePadTriggerUpdate != null && (caps.HasLeftTrigger || caps.HasRightTrigger))
                {
                    GamePadTriggerUpdate(caps.HasLeftTrigger ? gps.Triggers.Left : 0f, caps.HasRightTrigger ? gps.Triggers.Right : 0f, player);
                }
                // Process the D-Pad
                if (GamePadDPadUpdate != null)
                {
                    CCGamePadButtonStatus left  = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus right = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus up    = CCGamePadButtonStatus.NotApplicable;
                    CCGamePadButtonStatus down  = CCGamePadButtonStatus.NotApplicable;
                    if (caps.HasDPadDownButton)
                    {
                        down = (gps.DPad.Down == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasDPadUpButton)
                    {
                        up = (gps.DPad.Up == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasDPadLeftButton)
                    {
                        left = (gps.DPad.Left == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    if (caps.HasDPadRightButton)
                    {
                        right = (gps.DPad.Right == ButtonState.Pressed ? CCGamePadButtonStatus.Pressed : CCGamePadButtonStatus.Released);
                    }
                    GamePadDPadUpdate(left, up, right, down, player);
                }
            }
            m_PriorGamePadState[player] = gps;
        }
Beispiel #38
0
 protected internal override void StartWithTarget(CCNode target)
 {
     base.StartWithTarget(target);
     m_previousPosition = m_startPosition = target.Position;
 }
Beispiel #39
0
 public bool ContainsPoint(CCPoint point)
 {
     return(point.X >= MinX && point.X <= MaxX && point.Y >= MinY && point.Y <= MaxY);
 }
Beispiel #40
0
 public CCPoint(CCPoint pt)
 {
     X = pt.X;
     Y = pt.Y;
 }
Beispiel #41
0
        /** Calculates cross product of two points.
         *  @return CGFloat
         *  @since v0.7.2
         */

        public static float CrossProduct(CCPoint v1, CCPoint v2)
        {
            return(v1.X * v2.Y - v1.Y * v2.X);
        }
Beispiel #42
0
 public static float DotProduct(CCPoint v1, CCPoint v2)
 {
     return(v1.X * v2.X + v1.Y * v2.Y);
 }
Beispiel #43
0
 public static float Dot(CCPoint p1, CCPoint p2)
 {
     return(p1.X * p2.X + p1.Y * p2.Y);
 }
Beispiel #44
0
 public CCPoint ConvertToNodeSpace(CCPoint worldPoint)
 {
     return(CCAffineTransform.CCPointApplyAffineTransform(worldPoint, WorldToNodeTransform()));
 }
Beispiel #45
0
        public void AddSpriteFramesWithDictionary(PlistDictionary pobDictionary, CCTexture2D pobTexture)
        {
            /*
             * Supported Zwoptex Formats:
             *
             * ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
             * ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
             * ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
             * ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
             */

            PlistDictionary metadataDict = null;

            if (pobDictionary.ContainsKey("metadata"))
            {
                metadataDict = pobDictionary["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;

            if (pobDictionary.ContainsKey("frames"))
            {
                framesDict = pobDictionary["frames"].AsDictionary;
            }

            int format = 0;

            // get the format
            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict   = pair.Value.AsDictionary;
                CCSpriteFrame   spriteFrame = null;

                if (format == 0)
                {
                    float x = 0f, y = 0f, w = 0f, h = 0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);
                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    new CCRect(x, y, w, h),
                                                    false,
                                                    new CCPoint(ox, oy),
                                                    new CCSize(ow, oh)
                                                    );
                }
                else if (format == 1 || format == 2)
                {
                    CCRect frame   = CCRect.Parse(frameDict["frame"].AsString);
                    bool   rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    CCPoint offset     = CCPoint.Parse(frameDict["offset"].AsString);
                    CCSize  sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    frame,
                                                    rotated,
                                                    offset,
                                                    sourceSize
                                                    );
                }
                else if (format == 3)
                {
                    // get values
                    CCSize  spriteSize       = CCSize.Parse(frameDict["spriteSize"].AsString);
                    CCPoint spriteOffset     = CCPoint.Parse(frameDict["spriteOffset"].AsString);
                    CCSize  spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
                    CCRect  textureRect      = CCRect.Parse(frameDict["textureRect"].AsString);
                    bool    textureRotated   = false;
                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    PlistArray aliases  = frameDict["aliases"].AsArray;
                    string     frameKey = pair.Key;

                    foreach (PlistObjectBase item2 in aliases)
                    {
                        string oneAlias = item2.AsString;
                        if (m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            if (m_pSpriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }
                        if (!m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            m_pSpriteFramesAliases.Add(oneAlias, frameKey);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
                                                    textureRotated,
                                                    spriteOffset,
                                                    spriteSourceSize);
                }

                // add sprite frame
                string key = pair.Key;
                if (!_AllowFrameOverwrite && m_pSpriteFrames.ContainsKey(key))
                {
                    CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
                }
                else if (_AllowFrameOverwrite || !m_pSpriteFrames.ContainsKey(key))
                {
                    m_pSpriteFrames[key] = spriteFrame;
                }
            }
        }
Beispiel #46
0
 public CCPoint ConvertToWorldSpace(CCPoint nodePoint)
 {
     return(CCAffineTransform.CCPointApplyAffineTransform(nodePoint, NodeToWorldTransform()));
 }
Beispiel #47
0
        public void DrawPolygon(CCPoint[] verts, int count, CCColor4F fillColor, float borderWidth,
                                CCColor4F borderColor)
        {
            var extrude = new ExtrudeVerts[count];

            for (int i = 0; i < count; i++)
            {
                var v0 = verts[(i - 1 + count) % count];
                var v1 = verts[i];
                var v2 = verts[(i + 1) % count];

                var n1 = CCPoint.Normalize(CCPoint.Perp(v1 - v0));
                var n2 = CCPoint.Normalize(CCPoint.Perp(v2 - v1));

                var offset = (n1 + n2) * (1.0f / (CCPoint.Dot(n1, n2) + 1.0f));
                extrude[i] = new ExtrudeVerts()
                {
                    offset = offset, n = n2
                };
            }

            bool outline = (fillColor.A > 0.0f && borderWidth > 0.0f);

            float inset = (!outline ? 0.5f : 0.0f);

            for (int i = 0; i < count - 2; i++)
            {
                var v0 = verts[0] - (extrude[0].offset * inset);
                var v1 = verts[i + 1] - (extrude[i + 1].offset * inset);
                var v2 = verts[i + 2] - (extrude[i + 2].offset * inset);

                m_pVertices.Add(new VertexPositionColor(v0, fillColor)); //__t(v2fzero)
                m_pVertices.Add(new VertexPositionColor(v1, fillColor)); //__t(v2fzero)
                m_pVertices.Add(new VertexPositionColor(v2, fillColor)); //__t(v2fzero)
            }

            for (int i = 0; i < count; i++)
            {
                int j  = (i + 1) % count;
                var v0 = verts[i];
                var v1 = verts[j];

                var n0 = extrude[i].n;

                var offset0 = extrude[i].offset;
                var offset1 = extrude[j].offset;

                if (outline)
                {
                    var inner0 = (v0 - (offset0 * borderWidth));
                    var inner1 = (v1 - (offset1 * borderWidth));
                    var outer0 = (v0 + (offset0 * borderWidth));
                    var outer1 = (v1 + (offset1 * borderWidth));

                    m_pVertices.Add(new VertexPositionColor(inner0, borderColor)); //__t(v2fneg(n0))
                    m_pVertices.Add(new VertexPositionColor(inner1, borderColor)); //__t(v2fneg(n0))
                    m_pVertices.Add(new VertexPositionColor(outer1, borderColor)); //__t(n0)

                    m_pVertices.Add(new VertexPositionColor(inner0, borderColor)); //__t(v2fneg(n0))
                    m_pVertices.Add(new VertexPositionColor(outer0, borderColor)); //__t(n0)
                    m_pVertices.Add(new VertexPositionColor(outer1, borderColor)); //__t(n0)
                }
                else
                {
                    var inner0 = (v0 - (offset0 * 0.5f));
                    var inner1 = (v1 - (offset1 * 0.5f));
                    var outer0 = (v0 + (offset0 * 0.5f));
                    var outer1 = (v1 + (offset1 * 0.5f));

                    m_pVertices.Add(new VertexPositionColor(inner0, fillColor)); //__t(v2fzero)
                    m_pVertices.Add(new VertexPositionColor(inner1, fillColor)); //__t(v2fzero)
                    m_pVertices.Add(new VertexPositionColor(outer1, fillColor)); //__t(n0)

                    m_pVertices.Add(new VertexPositionColor(inner0, fillColor)); //__t(v2fzero)
                    m_pVertices.Add(new VertexPositionColor(outer0, fillColor)); //__t(n0)
                    m_pVertices.Add(new VertexPositionColor(outer1, fillColor)); //__t(n0)
                }
            }

            m_bDirty = true;
        }
Beispiel #48
0
        public CCPoint ConvertToNodeSpaceAr(CCPoint worldPoint)
        {
            CCPoint nodePoint = ConvertToNodeSpace(worldPoint);

            return(nodePoint - m_tAnchorPointInPoints);
        }
Beispiel #49
0
 public bool Equals(CCPoint p)
 {
     return(X == p.X && Y == p.Y);
 }
Beispiel #50
0
        public CCPoint ConvertToWorldSpaceAr(CCPoint nodePoint)
        {
            CCPoint pt = nodePoint + m_tAnchorPointInPoints;

            return(ConvertToWorldSpace(pt));
        }
Beispiel #51
0
        protected virtual bool InitWithString(string theString, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset)
        {
            Debug.Assert(m_pConfiguration == null, "re-init is no longer supported");
            Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null), "Invalid params for CCLabelBMFont");

            CCTexture2D texture;

            if (!String.IsNullOrEmpty(fntFile))
            {
                CCBMFontConfiguration newConf = FNTConfigLoadFile(fntFile);
                Debug.Assert(newConf != null, "CCLabelBMFont: Impossible to create font. Please check file");

                m_pConfiguration = newConf;

                m_sFntFile = fntFile;

                try
                {
                    texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
                }
                catch (Exception)
                {
                    // Try the 'images' ref location just in case.
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images", m_pConfiguration.AtlasName));
                    }
                    catch (Exception)
                    {
                        // Lastly, try <font_path>/images/<font_name>
                        string dir     = System.IO.Path.GetDirectoryName(m_pConfiguration.AtlasName);
                        string fname   = System.IO.Path.GetFileName(m_pConfiguration.AtlasName);
                        string newName = System.IO.Path.Combine(System.IO.Path.Combine(dir, "images"), fname);
                        texture = CCTextureCache.SharedTextureCache.AddImage(newName);
                    }
                }
            }
            else
            {
                texture = new CCTexture2D();
            }

            if (String.IsNullOrEmpty(theString))
            {
                theString = String.Empty;
            }

            if (base.InitWithTexture(texture, theString.Length))
            {
                m_pAlignment          = alignment;
                m_tImageOffset        = imageOffset;
                m_fWidth              = width;
                m_cOpacity            = 255;
                m_tColor              = CCTypes.CCWhite;
                m_tContentSize        = CCSize.Zero;
                m_bIsOpacityModifyRGB = m_pobTextureAtlas.Texture.HasPremultipliedAlpha;
                Label       = (theString);
                AnchorPoint = new CCPoint(0.5f, 0.5f);
                return(true);
            }
            return(false);
        }
Beispiel #52
0
        public CCPoint ConvertToWindowSpace(CCPoint nodePoint)
        {
            CCPoint worldPoint = ConvertToWorldSpace(nodePoint);

            return(CCDirector.SharedDirector.ConvertToUi(worldPoint));
        }
Beispiel #53
0
        public override void CalculateVertexPoints()
        {
            float width  = m_pTexture.PixelsWide;
            float height = m_pTexture.PixelsHigh;
            float imageH = m_pTexture.ContentSizeInPixels.Height;

            int numOfPoints = (m_sGridSize.X + 1) * (m_sGridSize.Y + 1);

            m_pVertices         = new CCV3F_T2F[numOfPoints];
            m_pOriginalVertices = new CCVertex3F[numOfPoints];
            //m_pTexCoordinates = new CCPoint[numOfPoints];
            m_pIndices = new ushort[m_sGridSize.X * m_sGridSize.Y * 6];

            CCV3F_T2F[] vertArray = m_pVertices;
            //var texArray = m_pTexCoordinates;
            ushort[] idxArray = m_pIndices;

            var l1   = new int[4];
            var l2   = new CCVertex3F[4];
            var tex1 = new int[4];
            var tex2 = new CCPoint[4];

            //int idx = -1;
            for (int x = 0; x < m_sGridSize.X; ++x)
            {
                for (int y = 0; y < m_sGridSize.Y; ++y)
                {
                    float x1 = x * m_obStep.X;
                    float x2 = x1 + m_obStep.X;
                    float y1 = y * m_obStep.Y;
                    float y2 = y1 + m_obStep.Y;

                    var a = (short)(x * (m_sGridSize.Y + 1) + y);
                    var b = (short)((x + 1) * (m_sGridSize.Y + 1) + y);
                    var c = (short)((x + 1) * (m_sGridSize.Y + 1) + (y + 1));
                    var d = (short)(x * (m_sGridSize.Y + 1) + (y + 1));

                    int idx = ((y * m_sGridSize.X) + x) * 6;

                    idxArray[idx + 0] = (ushort)a;
                    idxArray[idx + 1] = (ushort)b;
                    idxArray[idx + 2] = (ushort)d;
                    idxArray[idx + 3] = (ushort)b;
                    idxArray[idx + 4] = (ushort)c;
                    idxArray[idx + 5] = (ushort)d;

                    //var tempidx = new short[6] {a, d, b, b, d, c};
                    //Array.Copy(tempidx, 0, idxArray, 6 * idx, tempidx.Length);

                    l1[0] = a;
                    l1[1] = b;
                    l1[2] = c;
                    l1[3] = d;

                    //var e = new Vector3(x1, y1, 0);
                    //var f = new Vector3(x2, y1, 0);
                    //var g = new Vector3(x2, y2, 0);
                    //var h = new Vector3(x1, y2, 0);

                    l2[0] = new CCVertex3F(x1, y1, 0);
                    l2[1] = new CCVertex3F(x2, y1, 0);
                    l2[2] = new CCVertex3F(x2, y2, 0);
                    l2[3] = new CCVertex3F(x1, y2, 0);

                    tex1[0] = a;
                    tex1[1] = b;
                    tex1[2] = c;
                    tex1[3] = d;

                    tex2[0] = new CCPoint(x1, y1);
                    tex2[1] = new CCPoint(x2, y1);
                    tex2[2] = new CCPoint(x2, y2);
                    tex2[3] = new CCPoint(x1, y2);

                    for (int i = 0; i < 4; ++i)
                    {
                        vertArray[l1[i]].vertices = l2[i];

                        vertArray[tex1[i]].texCoords.U = tex2[i].X / width;

                        if (m_bIsTextureFlipped)
                        {
                            vertArray[tex1[i]].texCoords.V = tex2[i].Y / height;
                        }
                        else
                        {
                            vertArray[tex1[i]].texCoords.V = (imageH - tex2[i].Y) / height;
                        }
                    }
                }
            }

            int n = (m_sGridSize.X + 1) * (m_sGridSize.Y + 1);

            for (int i = 0; i < n; i++)
            {
                m_pOriginalVertices[i] = m_pVertices[i].vertices;
            }

            m_bDirty = true;
        }
Beispiel #54
0
        /** Linear Interpolation between two points a and b
         *  @returns
         *    alpha == 0 ? a
         *    alpha == 1 ? b
         *    otherwise a value between a..b
         *  @since v0.99.1
         */

        public static CCPoint Lerp(CCPoint a, CCPoint b, float alpha)
        {
            return(a * (1f - alpha) + b * alpha);
        }
Beispiel #55
0
        /** Converts a vector to radians.
         *  @return CGFloat
         *  @since v0.7.2
         */

        public static float ToAngle(CCPoint v)
        {
            return((float)Math.Atan2(v.Y, v.X));
        }
Beispiel #56
0
        public virtual void ScrollViewDidScroll(CCScrollView view)
        {
            var uCountOfItems = _dataSource.NumberOfCellsInTableView(this);

            if (uCountOfItems == 0)
            {
                return;
            }

            if (_tableViewDelegate != null)
            {
                _tableViewDelegate.ScrollViewDidScroll(this);
            }

            int     startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
            CCPoint offset = GetContentOffset() * -1;

            maxIdx = Math.Max(uCountOfItems - 1, 0);

            if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
            {
                offset.Y = offset.Y + _viewSize.Height / Container.ScaleY;
            }
            startIdx = _indexFromOffset(offset);
            if (startIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
            {
                startIdx = uCountOfItems - 1;
            }

            if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
            {
                offset.Y -= _viewSize.Height / Container.ScaleY;
            }
            else
            {
                offset.Y += _viewSize.Height / Container.ScaleY;
            }
            offset.X += _viewSize.Width / Container.ScaleX;

            endIdx = _indexFromOffset(offset);
            if (endIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
            {
                endIdx = uCountOfItems - 1;
            }

#if DEBUG_ // For Testing.
            int i = 0;
            foreach (object pObj in _cellsUsed)
            {
                var pCell = (CCTableViewCell)pObj;
                CCLog.Log("cells Used index {0}, value = {1}", i, pCell.getIdx());
                i++;
            }
            CCLog.Log("---------------------------------------");
            i = 0;
            foreach (object pObj in _cellsFreed)
            {
                var pCell = (CCTableViewCell)pObj;
                CCLog.Log("cells freed index {0}, value = {1}", i, pCell.getIdx());
                i++;
            }
            CCLog.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif

            if (_cellsUsed.Count > 0)
            {
                var cell = (CCTableViewCell)_cellsUsed[0];

                idx = cell.Index;
                while (idx < startIdx)
                {
                    _moveCellOutOfSight(cell);
                    if (_cellsUsed.Count > 0)
                    {
                        cell = (CCTableViewCell)_cellsUsed[0];
                        idx  = cell.Index;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (_cellsUsed.Count > 0)
            {
                var cell = (CCTableViewCell)_cellsUsed[_cellsUsed.Count - 1];
                idx = cell.Index;

                while (idx <= maxIdx && idx > endIdx)
                {
                    _moveCellOutOfSight(cell);
                    if (_cellsUsed.Count > 0)
                    {
                        cell = (CCTableViewCell)_cellsUsed[_cellsUsed.Count - 1];
                        idx  = cell.Index;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            for (int i = startIdx; i <= endIdx; i++)
            {
                if (_indices.Contains(i))
                {
                    continue;
                }
                UpdateCellAtIndex(i);
            }
        }
Beispiel #57
0
        public override void TouchMoved(CCTouch touch)
        {
            if (!Visible)
            {
                return;
            }

            if (m_pTouches.Contains(touch))
            {
                if (m_pTouches.Count == 1 && m_bDragging)
                {                                   // scrolling
                    CCPoint moveDistance, newPoint; //, maxInset, minInset;
                    CCRect  frame;
                    float   newX, newY;

                    frame = GetViewRect();

                    newPoint     = ConvertTouchToNodeSpace(m_pTouches[0]);
                    moveDistance = newPoint - m_tTouchPoint;

                    float dis = 0.0f;
                    if (m_eDirection == CCScrollViewDirection.Vertical)
                    {
                        dis = moveDistance.Y;
                    }
                    else if (m_eDirection == CCScrollViewDirection.Horizontal)
                    {
                        dis = moveDistance.X;
                    }
                    else
                    {
                        dis = (float)Math.Sqrt(moveDistance.X * moveDistance.X + moveDistance.Y * moveDistance.Y);
                    }

                    if (!m_bTouchMoved && Math.Abs(ConvertDistanceFromPointToInch(dis)) < MOVE_INCH)
                    {
                        //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
                        return;
                    }

                    if (!m_bTouchMoved)
                    {
                        moveDistance = CCPoint.Zero;
                    }

                    m_tTouchPoint = newPoint;
                    m_bTouchMoved = true;

                    if (frame.ContainsPoint(ConvertToWorldSpace(newPoint)))
                    {
                        switch (m_eDirection)
                        {
                        case CCScrollViewDirection.Vertical:
                            moveDistance = new CCPoint(0.0f, moveDistance.Y);
                            break;

                        case CCScrollViewDirection.Horizontal:
                            moveDistance = new CCPoint(moveDistance.X, 0.0f);
                            break;

                        default:
                            break;
                        }

                        //maxInset = m_fMaxInset;
                        //minInset = m_fMinInset;

                        newX = m_pContainer.Position.X + moveDistance.X;
                        newY = m_pContainer.Position.Y + moveDistance.Y;

                        m_tScrollDistance = moveDistance;
                        SetContentOffset(new CCPoint(newX, newY));
                    }
                }
                else if (m_pTouches.Count == 2 && !m_bDragging)
                {
                    float len = CCPoint.Distance(m_pContainer.ConvertTouchToNodeSpace(m_pTouches[0]),
                                                 m_pContainer.ConvertTouchToNodeSpace(m_pTouches[1]));
                    ZoomScale = ZoomScale * len / m_fTouchLength;
                }
            }
        }
Beispiel #58
0
 public static float Distance(CCPoint v1, CCPoint v2)
 {
     return((v1 - v2).Length);
 }
Beispiel #59
0
 public static bool Equal(ref CCPoint point1, ref CCPoint point2)
 {
     return((point1.X == point2.X) && (point1.Y == point2.Y));
 }
Beispiel #60
0
 public float DistanceSQ(ref CCPoint v2)
 {
     return(Sub(ref v2).LengthSQ);
 }