Exemple #1
0
        private static List <CCVector2> StarPoints(CCVector2 center, int pointCount, float outerRadius, float innerRadius, float rotation, bool close)
        {
            List <CCVector2> points = new List <CCVector2>();

            int limit = (close) ? pointCount * 2 + 1 : pointCount * 2;

            float rot = (float)((Math.PI * 2) / (pointCount * 2));

            for (int i = 0; i < limit; i++)
            {
                float si = (float)Math.Sin(-i * rot + Math.PI + rotation);
                float ci = (float)Math.Cos(-i * rot + Math.PI + rotation);

                if (i % 2 == 0)
                {
                    points.Add(center + new CCVector2(si, ci) * outerRadius);
                }
                else
                {
                    points.Add(center + new CCVector2(si, ci) * innerRadius);
                }
            }

            return(points);
        }
Exemple #2
0
        public GraphicsPathTest()
        {
            _thickPen = new Pen(Microsoft.Xna.Framework.Color.Green, 15);

            List <CCVector2> path1 = new List <CCVector2>()
            {
                new CCVector2(50, 50), new CCVector2(100, 50), new CCVector2(100, 100), new CCVector2(50, 100),
            };

            _gpathf = new GraphicsPath(_thickPen, path1, PathType.Closed);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
            {
                path1[i] = new CCVector2(path1[i].X + 100, path1[i].Y);
            }

            _gpathr = new GraphicsPath(_thickPen, path1, PathType.Closed);

            for (int i = 0; i < path1.Count; i++)
            {
                path1[i] = new CCVector2(path1[i].X, path1[i].Y + 100);
            }

            _gpath2r = new GraphicsPath(_thickPen, path1);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
            {
                path1[i] = new CCVector2(path1[i].X - 100, path1[i].Y);
            }

            _gpath2f = new GraphicsPath(_thickPen, path1);
        }
        public override void DrawCircle(cpVect center, float radius, cpColor color)
        {
            if (!primitiveBatch.IsReady())
            {
                throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
            }
            const float increment = cp.M_PI * 2.0f / CircleSegments;
            float       theta     = 0.0f;

            var col          = color;
            var colorOutline = col.ToCCColor4B();

            CCVector2 centr  = center.ToCCVector2();
            CCVector2 thetaV = CCVector2.Zero;


            for (int i = 0, count = CircleSegments; i < count; i++)
            {
                thetaV.X = cp.cpfcos(theta);
                thetaV.Y = cp.cpfsin(theta);
                CCVector2 v1 = centr + Convert.ToSingle(radius) * thetaV;

                thetaV.X = cp.cpfcos(theta + increment);
                thetaV.Y = cp.cpfsin(theta + increment);
                CCVector2 v2 = centr +
                               Convert.ToSingle(radius) *
                               thetaV;

                primitiveBatch.AddVertex(ref v1, colorOutline, PrimitiveType.LineList);
                primitiveBatch.AddVertex(ref v2, colorOutline, PrimitiveType.LineList);

                theta += increment;
            }
        }
Exemple #4
0
        private static float ApproxDistance(CCVector2 p0, CCVector2 p1)
        {
            float dx = Math.Abs(p1.X - p0.X);
            float dy = Math.Abs(p1.Y - p0.Y);

            return(ApproxDistance(dx, dy));
        }
        public override void Draw(DrawBatch drawBatch)
        {
            float space = 30;
            float macroSpace = 50;
            float length = 200;

            CCVector2 o1 = new CCVector2(macroSpace, macroSpace);
            CCVector2 o2 = new CCVector2(macroSpace * 2 + length, macroSpace);
            CCVector2 o3 = new CCVector2(macroSpace * 2 + length, macroSpace * 2 + length);
            CCVector2 o4 = new CCVector2(macroSpace, macroSpace * 2 + length);

            drawBatch.DrawPath(new GraphicsPath(_flatPen, new List<CCVector2> { o1 + new CCVector2(0, space * 0), o1 + new CCVector2(length, space * 0) }));
            drawBatch.DrawPath(new GraphicsPath(_squarePen, new List<CCVector2> { o1 + new CCVector2(0, space * 1), o1 + new CCVector2(length, space * 1) }));
            drawBatch.DrawPath(new GraphicsPath(_trianglePen, new List<CCVector2> { o1 + new CCVector2(0, space * 2), o1 + new CCVector2(length, space * 2) }));
            drawBatch.DrawPath(new GraphicsPath(_invTrianglePen, new List<CCVector2> { o1 + new CCVector2(0, space * 3), o1 + new CCVector2(length, space * 3) }));
            drawBatch.DrawPath(new GraphicsPath(_arrowPen, new List<CCVector2> { o1 + new CCVector2(0, space * 4), o1 + new CCVector2(length, space * 4) }));

            drawBatch.DrawPath(new GraphicsPath(_flatPen, new List<CCVector2> { o2 + new CCVector2(space * 0, 0), o2 + new CCVector2(space * 0, length) }));
            drawBatch.DrawPath(new GraphicsPath(_squarePen, new List<CCVector2> { o2 + new CCVector2(space * 1, 0), o2 + new CCVector2(space * 1, length) }));
            drawBatch.DrawPath(new GraphicsPath(_trianglePen, new List<CCVector2> { o2 + new CCVector2(space * 2, 0), o2 + new CCVector2(space * 2, length) }));
            drawBatch.DrawPath(new GraphicsPath(_invTrianglePen, new List<CCVector2> { o2 + new CCVector2(space * 3, 0), o2 + new CCVector2(space * 3, length) }));
            drawBatch.DrawPath(new GraphicsPath(_arrowPen, new List<CCVector2> { o2 + new CCVector2(space * 4, 0), o2 + new CCVector2(space * 4, length) }));

            drawBatch.DrawPath(new GraphicsPath(_flatPen, new List<CCVector2> { o3 + new CCVector2(length, space * 0), o3 + new CCVector2(0, space * 0) }));
            drawBatch.DrawPath(new GraphicsPath(_squarePen, new List<CCVector2> { o3 + new CCVector2(length, space * 1), o3 + new CCVector2(0, space * 1) }));
            drawBatch.DrawPath(new GraphicsPath(_trianglePen, new List<CCVector2> { o3 + new CCVector2(length, space * 2), o3 + new CCVector2(0, space * 2) }));
            drawBatch.DrawPath(new GraphicsPath(_invTrianglePen, new List<CCVector2> { o3 + new CCVector2(length, space * 3), o3 + new CCVector2(0, space * 3) }));
            drawBatch.DrawPath(new GraphicsPath(_arrowPen, new List<CCVector2> { o3 + new CCVector2(length, space * 4), o3 + new CCVector2(0, space * 4) }));

            drawBatch.DrawPath(new GraphicsPath(_flatPen, new List<CCVector2> { o4 + new CCVector2(space * 0, length), o4 + new CCVector2(space * 0, 0) }));
            drawBatch.DrawPath(new GraphicsPath(_squarePen, new List<CCVector2> { o4 + new CCVector2(space * 1, length), o4 + new CCVector2(space * 1, 0) }));
            drawBatch.DrawPath(new GraphicsPath(_trianglePen, new List<CCVector2> { o4 + new CCVector2(space * 2, length), o4 + new CCVector2(space * 2, 0) }));
            drawBatch.DrawPath(new GraphicsPath(_invTrianglePen, new List<CCVector2> { o4 + new CCVector2(space * 3, length), o4 + new CCVector2(space * 3, 0) }));
            drawBatch.DrawPath(new GraphicsPath(_arrowPen, new List<CCVector2> { o4 + new CCVector2(space * 4, length), o4 + new CCVector2(space * 4, 0) }));
        }
Exemple #6
0
        public override void DrawSolidPolygon(Vector2[] vertices, int count, float red, float green, float blue)
        {
            var verts = new CCVector2[vertices.Length];

            vertices.CopyTo(verts, 0);
            DrawSolidPolygon(verts, count, new Color(red, green, blue), true);
        }
Exemple #7
0
        public override void DrawSolidCircle(b2Vec2 center, float radius, b2Vec2 axis, b2Color color)
        {
            if (!primitiveBatch.IsReady())
            {
                throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
            }
            const double increment = Math.PI * 2.0 / CircleSegments;
            double       theta     = 0.0;

            var colorFill = color.ToCCColor4B() * 0.5f;
            var centr     = center.ToCCVector2();

            CCVector2 v0 = center.ToCCVector2() + radius * new CCVector2((float)Math.Cos(theta), (float)Math.Sin(theta));

            theta += increment;

            for (int i = 1; i < CircleSegments - 1; i++)
            {
                var v1 = centr + radius * new CCVector2((float)Math.Cos(theta), (float)Math.Sin(theta));
                var v2 = centr +
                         radius * new CCVector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment));

                primitiveBatch.AddVertex(ref v0, colorFill, PrimitiveType.TriangleList);
                primitiveBatch.AddVertex(ref v1, colorFill, PrimitiveType.TriangleList);
                primitiveBatch.AddVertex(ref v2, colorFill, PrimitiveType.TriangleList);

                theta += increment;
            }
            DrawCircle(center, radius, color);

            DrawSegment(center, center + axis * radius, color);
        }
        public GraphicsPathTest()
        {
            _thickPen = new Pen(Microsoft.Xna.Framework.Color.Green, 15);

            List<CCVector2> path1 = new List<CCVector2>() {
                new CCVector2(50, 50), new CCVector2(100, 50), new CCVector2(100, 100), new CCVector2(50, 100),
            };

            _gpathf = new GraphicsPath(_thickPen, path1, PathType.Closed);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X + 100, path1[i].Y);

            _gpathr = new GraphicsPath(_thickPen, path1, PathType.Closed);

            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X, path1[i].Y + 100);

            _gpath2r = new GraphicsPath(_thickPen, path1);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X - 100, path1[i].Y);

            _gpath2f = new GraphicsPath(_thickPen, path1);
        }
Exemple #9
0
        private void BuildCubicBezierGeometryBuffer(CCVector2 v0, CCVector2 v1, CCVector2 v2, CCVector2 v3, int subdivisions)
        {
            CheckBufferFreeSpace(subdivisions + 1);
            int baseIndex = _geometryIndex;

            float step = 1f / (subdivisions - 1);
            float t    = 0;

            for (int i = 0; i < subdivisions; i++, t += step)
            {
                if (1 - t < 5e-6)
                {
                    t = 1;
                }

                float p0 = Bernstein(3, 0, t);
                float p1 = Bernstein(3, 1, t);
                float p2 = Bernstein(3, 2, t);
                float p3 = Bernstein(3, 3, t);

                float vx = p0 * v0.X + p1 * v1.X + p2 * v2.X + p3 * v3.X;
                float vy = p0 * v0.Y + p1 * v1.Y + p2 * v2.Y + p3 * v3.Y;

                _geometryBuffer[_geometryIndex++] = new CCVector2(vx, vy);
            }

            if (_calculateLengths)
            {
                CalculateLengthsInRange(baseIndex, _geometryIndex - baseIndex);
            }
        }
        public override void DrawSolidPolygon(cpVect[] vertices, int vertexCount, cpColor color)
        {
            if (!primitiveBatch.IsReady())
            {
                throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
            }

            if (vertexCount == 2)
            {
                DrawPolygon(vertices, vertexCount, color);
                return;
            }

            CCColor4B colorFill = color.ToCCColor4B() * 0.5f;

            for (int i = 1; i < vertexCount - 1; i++)
            {
                CCVector2 vertice0 = vertices[0].ToCCVector2();
                primitiveBatch.AddVertex(ref vertice0, colorFill, PrimitiveType.TriangleList);
                primitiveBatch.AddVertex(vertices[i].ToCCVector2(), colorFill, PrimitiveType.TriangleList);
                primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2(), colorFill, PrimitiveType.TriangleList);
            }

            DrawPolygon(vertices, vertexCount, color);
        }
        public static CCFontAtlas GetFontAtlasSpriteFont (string fontFileName, float fontSize, CCVector2 imageOffset = default(CCVector2))
        {
            string atlasName = GenerateFontName(fontFileName, (int)fontSize, GlyphCollection.Custom,false);
            var atlasAlreadyExists = atlasMap.ContainsKey(atlasName);

            if (!atlasAlreadyExists)
            {
                var font = new CCFontSpriteFont(fontFileName, fontSize, imageOffset);
                if (font != null)
                {
                    var tempAtlas = font.CreateFontAtlas();
                    if (tempAtlas != null)
                    {
                        atlasMap[atlasName] = tempAtlas;
                        return atlasMap[atlasName];
                    }
                }
            }
            else
            {
                return atlasMap[atlasName];
            }


            return null;
        }
Exemple #12
0
        /// <summary>
        /// Appends a fully-defined arc to the end of the path, connected by an additional line segment if the arc does not
        /// begin at the path's current endpoint.
        /// </summary>
        /// <param name="p0">The starting point of the arc.</param>
        /// <param name="p1">The ending point of the arc.</param>
        /// <param name="height">The furthest point on the arc from the line connecting <paramref name="p0"/> and <paramref name="p1"/>.</param>
        public void AddArc(CCVector2 p0, CCVector2 p1, float height)
        {
            float width  = (p1 - p0).Length();
            float radius = (height / 2) + (width * width) / (height * 8);

            AddArc(p0, p1, height, DefaultSubdivisions(radius));
        }
Exemple #13
0
        private void BuildCircleGeometryBuffer(CCVector2 center, float radius, int subdivisions, bool connect)
        {
            List <CCVector2> unitCircle = CalculateCircleSubdivisions(subdivisions);

            CheckBufferFreeSpace(subdivisions + 1);
            int baseIndex = _geometryIndex;

            for (int i = 0; i < subdivisions; i++)
            {
                _geometryBuffer[_geometryIndex++] = new CCVector2(center.X + radius * unitCircle[i].X, center.Y + radius * unitCircle[i].Y);
            }

            if (connect)
            {
                _geometryBuffer[_geometryIndex++] = new CCVector2(center.X + radius * unitCircle[0].X, center.Y + radius * unitCircle[0].Y);
            }

            if (_calculateLengths)
            {
                float arcLength     = 2 * (float)Math.PI * radius;
                float segmentLength = arcLength / subdivisions;

                for (int i = baseIndex; i < _geometryIndex; i++)
                {
                    _lengthBuffer[baseIndex + i] = _lengthBuffer[baseIndex + i - 1] + segmentLength;
                }
            }
        }
Exemple #14
0
        public override void DrawCircle(b2Vec2 center, float radius, b2Color color)
        {
            if (!primitiveBatch.IsReady())
            {
                throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
            }
            const double increment = Math.PI * 2.0 / CircleSegments;
            double       theta     = 0.0;

            var       col   = color.ToCCColor4B();
            CCVector2 centr = center.ToCCVector2();

            for (int i = 0, count = CircleSegments; i < count; i++)
            {
                CCVector2 v1 = centr + radius * new CCVector2((float)Math.Cos(theta), (float)Math.Sin(theta));
                CCVector2 v2 = centr +
                               radius *
                               new CCVector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment));

                primitiveBatch.AddVertex(ref v1, col, PrimitiveType.LineList);
                primitiveBatch.AddVertex(ref v2, col, PrimitiveType.LineList);

                theta += increment;
            }
        }
Exemple #15
0
        //---------------------------------------------------------------------------------------------------------
        // GetRandomPosition - Old method - don't use
        //---------------------------------------------------------------------------------------------------------
        // Parameters: CCsprite - size of the sprite to position
        //
        // Returns: CCPoint - random point within the display field
        //---------------------------------------------------------------------------------------------------------
//		CCPoint GetRandomPosition (CCSize spriteSize)
//		{
//			double rndX = CCRandom.NextDouble ();
//			double rndY = CCRandom.NextDouble ();
//			double randomX = (rndX > 0)
//				? rndX * VisibleBoundsWorldspace.Size.Width - spriteSize.Width / 2
//				: spriteSize.Width / 2;
//			if (randomX < (spriteSize.Width / 2))
//				randomX += spriteSize.Width;
//
//			double randomY = (rndY > 0)
//				? rndY * VisibleBoundsWorldspace.Size.Height - spriteSize.Height / 2
//				: spriteSize.Height / 2;
//			if (randomY < (spriteSize.Height / 2))
//				randomY += spriteSize.Height;
//			return new CCPoint ((float)randomX, (float)randomY);
//		}

        //---------------------------------------------------------------------------------------------------------
        // GetSeparatingVector - Not being used
        //---------------------------------------------------------------------------------------------------------
        // Parameters:	first - CCRect of the first object being compared
        //				second - CCRect of the second object being compared
        //
        // Returns:		CCVector2 - vector to direction to move second object so it won't collide with first
        //---------------------------------------------------------------------------------------------------------
        // Used to compare overlaping rectangles of two objects to determine if they collide or not.  If they do
        // return a vector to move the object so it won't overlap
        //---------------------------------------------------------------------------------------------------------
        static CCVector2 GetSeparatingVector(CCRect first, CCRect second)
        {
            CCVector2 separation = CCVector2.Zero;

            if (first.IntersectsRect(second))
            {
                var  intersecionRect      = first.Intersection(second);
                bool separateHorizontally = intersecionRect.Size.Width < intersecionRect.Size.Height;

                if (separateHorizontally)
                {
                    separation.X = intersecionRect.Size.Width;
                    if (first.Center.X < second.Center.X)
                    {
                        separation.X *= -1;
                    }
                    separation.Y = 0;
                }
                else
                {
                    separation.X = 0;
                    separation.Y = intersecionRect.Size.Height;
                    if (first.Center.Y < second.Center.Y)
                    {
                        separation.Y *= -1;
                    }
                }
            }
            return(separation);
        }
Exemple #16
0
        public void DrawArrow(Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator,
                              Color color)
        {
            // Draw connection segment between start- and end-point
            DrawSegment(start, end, color);

            // Precalculate halfwidth
            float halfWidth = width / 2;

            // Create directional reference
            Vector2 rotation = (start - end);

            rotation.Normalize();

            // Calculate angle of directional vector
            float angle = (float)Math.Atan2(rotation.X, -rotation.Y);
            // Create matrix for rotation
            Matrix rotMatrix = Matrix.CreateRotationZ(angle);
            // Create translation matrix for end-point
            Matrix endMatrix = Matrix.CreateTranslation(end.X, end.Y, 0);

            // Setup arrow end shape
            CCVector2[] verts = new CCVector2[3];
            verts[0] = new CCVector2(0, 0);
            verts[1] = new CCVector2(-halfWidth, -length);
            verts[2] = new CCVector2(halfWidth, -length);

            // Rotate end shape
            var rotAffineTransform = MatrixToCCAffineTransform(rotMatrix);

            CCVector2.Transform(verts, ref rotAffineTransform, verts);
            // Translate end shape
            var endAffineTransform = MatrixToCCAffineTransform(endMatrix);

            CCVector2.Transform(verts, ref endAffineTransform, verts);

            // Draw arrow end shape
            DrawSolidPolygon(verts, 3, color, false);

            if (drawStartIndicator)
            {
                // Create translation matrix for start
                Matrix startMatrix = Matrix.CreateTranslation(start.X, start.Y, 0);
                // Setup arrow start shape
                CCVector2[] baseVerts = new CCVector2[4];
                baseVerts[0] = new CCVector2(-halfWidth, length / 4);
                baseVerts[1] = new CCVector2(halfWidth, length / 4);
                baseVerts[2] = new CCVector2(halfWidth, 0);
                baseVerts[3] = new CCVector2(-halfWidth, 0);

                // Rotate start shape
                CCVector2.Transform(baseVerts, ref rotAffineTransform, baseVerts);
                // Translate start shape
                var startAffineTransform = MatrixToCCAffineTransform(startMatrix);
                CCVector2.Transform(baseVerts, ref startAffineTransform, baseVerts);
                // Draw start shape
                DrawSolidPolygon(baseVerts, 4, color, false);
            }
        }
 protected LineCapInfo (float width, CCVector2[] xyBuffer, CCVector2[] uvBuffer, short[] indexBuffer, short[] outlineBuffer)
 {
     _width = width;
     _xyBuffer = xyBuffer;
     _uvBuffer = uvBuffer;
     _indexBuffer = indexBuffer;
     _outlineBuffer = outlineBuffer;
 }
Exemple #18
0
        private int AddEndPoint(int pointIndex, CCVector2 a, CCVector2 b, PenWorkspace ws, Buffer <CCVector2> positionBuffer)
        {
            _pen.ComputeEndPoint(a, b, ws);

            int xyCount = AddStartOrEndPoint(pointIndex, ws, positionBuffer, true);

            return(xyCount);
        }
 public StrongEnemyFire()
 {
     for (int i = 0; i < vecs.Length; i++)
     {
         double radian = -(60 + ((120 - 60) / (vecs.Length - 1) * i)) * (Math.PI / 180);
         vecs[i] = new CCVector2((float)Math.Cos(radian), (float)Math.Sin(radian));
     }
 }
Exemple #20
0
 protected static List <CCVector2> ShiftPath(List <CCVector2> path, float x, float y)
 {
     for (int i = 0; i < path.Count; i++)
     {
         path[i] = new CCVector2(path[i].X + x, path[i].Y + y);
     }
     return(path);
 }
Exemple #21
0
 public NormalEnemyFire()
 {
     for (int i = 0; i < 3; i++)
     {
         double radian = -(60 + ((120 - 60) / (3 - 1) * i)) * (Math.PI / 180);
         vecs[i] = new CCVector2((float)Math.Cos(radian), (float)Math.Sin(radian));
     }
 }
Exemple #22
0
        private static int DefaultBezierSubdivisions(CCVector2 p0, CCVector2 p1, CCVector2 p2)
        {
            CCVector2 p01 = CCVector2.Lerp(p0, p1, .5f);
            CCVector2 p12 = CCVector2.Lerp(p1, p2, .5f);

            float dist = ApproxDistance(p0, p01) + ApproxDistance(p01, p12) + ApproxDistance(p12, p2);

            return((int)(dist * 0.10f));
        }
Exemple #23
0
        internal void ComputeEndPoint(CCVector2 a, CCVector2 b, PenWorkspace ws)
        {
            EndCapInfo.Calculate(b, a - b, ws, Alignment, false);

            for (int i = 0; i < ws.UVBuffer.Index; i++)
            {
                ws.UVBuffer[i] = new CCVector2(1 - ws.UVBuffer[i].X, ws.PathLength);
            }
        }
Exemple #24
0
        /// <summary>
        /// Appends a cubic Bezier curve to the end of the path, connected by an additional line segment if the curve does not
        /// begin at the path's current endpoint.
        /// </summary>
        /// <param name="p0">The starting point of the curve.</param>
        /// <param name="p1">The first control point.</param>
        /// <param name="p2">The second control point.</param>
        /// <param name="p3">The ending point of the curve.</param>
        /// <param name="subdivisions">The number of subdivisions in the curve.</param>
        public void AddBezier(CCVector2 p0, CCVector2 p1, CCVector2 p2, CCVector2 p3, int subdivisions)
        {
            if (LastPointClose(p0))
            {
                _geometryIndex--;
            }

            BuildCubicBezierGeometryBuffer(p0, p1, p2, p3, subdivisions);
        }
        public void Calculate (CCVector2 p, CCVector2 edgeAB, PenWorkspace ws, PenAlignment alignment, bool start)
        {
            edgeAB.Normalize();

            // [  eAB.X  -eAB.Y ]
            // [  eAB.Y   eAB.X ]

            float tC = edgeAB.X * _width;
            float tS = edgeAB.Y * _width;

            float tX = p.X;
            float tY = p.Y;

            switch (alignment) {
                case PenAlignment.Center:
                    break;

                case PenAlignment.Inset:
                    if (start) {
                        tX = p.X + (-.5f * tS);
                        tY = p.Y - (-.5f * tC);
                    }
                    else {
                        tX = p.X - (-.5f * tS);
                        tY = p.Y + (-.5f * tC);
                    }
                    break;

                case PenAlignment.Outset:
                    if (start) {
                        tX = p.X + (.5f * tS);
                        tY = p.Y - (.5f * tC);
                    }
                    else {
                        tX = p.X - (.5f * tS);
                        tY = p.Y + (.5f * tC);
                    }
                    break;
            }

            for (int i = 0; i < _xyBuffer.Length; i++)
                ws.XYBuffer[i] = new CCVector2(_xyBuffer[i].X * tC - _xyBuffer[i].Y * tS + tX, _xyBuffer[i].X * tS + _xyBuffer[i].Y * tC + tY);

            for (int i = 0; i < _uvBuffer.Length; i++)
                ws.UVBuffer[i] = _uvBuffer[i];

            for (int i = 0; i < _indexBuffer.Length; i++)
                ws.IndexBuffer[i] = _indexBuffer[i];

            for (int i = 0; i < _outlineBuffer.Length; i++)
                ws.OutlineIndexBuffer[i] = _outlineBuffer[i];

            ws.XYBuffer.Index = _xyBuffer.Length;
            ws.UVBuffer.Index = _uvBuffer.Length;
            ws.IndexBuffer.Index = _indexBuffer.Length;
            ws.OutlineIndexBuffer.Index = _outlineBuffer.Length;
        }
Exemple #26
0
        /// <summary>
        /// Computes a triangle list that fully covers the area enclosed by the given set of points.
        /// </summary>
        /// <param name="points">A list of points that defines an enclosing path.</param>
        /// <param name="offset">The offset of the first point in the list.</param>
        /// <param name="count">The number of points in the path.</param>
        public void Triangulate(IList <CCVector2> points, int offset, int count)
        {
            Initialize(count);

            int index        = 0;
            int computeIndex = 0;

            while (count >= 3)
            {
                bool isEar = true;

                CCVector2 a = points[offset + _triPrev[index]];
                CCVector2 b = points[offset + index];
                CCVector2 c = points[offset + _triNext[index]];
                if (TriangleIsCCW(a, b, c))
                {
                    int k = _triNext[_triNext[index]];
                    do
                    {
                        if (PointInTriangleInclusive(points[offset + k], a, b, c))
                        {
                            isEar = false;
                            break;
                        }
                        k = _triNext[k];
                    } while (k != _triPrev[index]);
                }
                else
                {
                    isEar = false;
                }

                if (isEar)
                {
                    if (_indexComputeBuffer.Length < computeIndex + 3)
                    {
                        Array.Resize(ref _indexComputeBuffer, _indexComputeBuffer.Length * 2);
                    }

                    _indexComputeBuffer[computeIndex++] = offset + _triPrev[index];
                    _indexComputeBuffer[computeIndex++] = offset + index;
                    _indexComputeBuffer[computeIndex++] = offset + _triNext[index];

                    _triNext[_triPrev[index]] = _triNext[index];
                    _triPrev[_triNext[index]] = _triPrev[index];
                    count--;
                    index = _triPrev[index];
                }
                else
                {
                    index = _triNext[index];
                }
            }

            _indexCount = computeIndex;
        }
        public virtual bool CollidesWith(CCMaskedSprite target, out CCPoint pt)
        {
            pt = CCPoint.Zero;
            CCAffineTransform affine1 = AffineWorldTransform;
            CCAffineTransform affine2 = target.AffineWorldTransform;
            CCRect myBBInWorld = BoundingBoxTransformedToWorld;
            CCRect targetBBInWorld = target.BoundingBoxTransformedToWorld;

            if (!myBBInWorld.IntersectsRect(targetBBInWorld))
            {
                return (false);
            }
            // Based upon http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Putting_CD_into_practice.php
            var affine1to2 = affine1 * CCAffineTransform.Invert (affine2);

            int width2 = (int)target.ContentSize.Width;
            int height2 = (int)target.ContentSize.Height;
            int width1 = (int)ContentSize.Width;
            int height1 = (int)ContentSize.Height;
            byte[] maskA = CollisionMask;
            byte[] maskB = target.CollisionMask;
            if (maskA == null || maskB == null)
            {
                return (false);
            }
            for (int x1 = 0; x1 < width1; x1++)
            {
                for (int y1 = 0; y1 < height1; y1++)
                {
                    var pos1 = new CCVector2(x1, y1);
                    var pos2 = CCVector2.Transform (pos1, affine1to2);

                    int x2 = (int)pos2.X;
                    int y2 = (int)pos2.Y;
                    if ((x2 >= 0) && (x2 < width2))
                    {
                        if ((y2 >= 0) && (y2 < height2))
                        {
                            int iA = x1 + (height1-y1) * width1;
                            int iB = x2 + (height2-y2) * width2;
                            if (iA >= maskA.Length || iB >= maskB.Length)
                                continue;
                            if (maskA[iA] > 0){
                                if (maskB[iB] > 0){
                                    CCVector2 screenPos = CCVector2.Transform(pos1, affine1);
                                    pt = new CCPoint(screenPos);
                                    return (true);
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
Exemple #28
0
        public JoinSample(CCVector2 pointA, CCVector2 pointB, CCVector2 pointC, float lengthA, float lengthB, float lengthC)
        {
            PointA = pointA;
            PointB = pointB;
            PointC = pointC;

            LengthA = lengthA;
            LengthB = lengthB;
            LengthC = lengthC;
        }
Exemple #29
0
        public void Advance(CCVector2 nextPoint, float nextLength)
        {
            PointA = PointB;
            PointB = PointC;
            PointC = nextPoint;

            LengthA = LengthB;
            LengthB = LengthC;
            LengthC = nextLength;
        }
Exemple #30
0
        public JoinSample(CCVector2 pointA, CCVector2 pointB, CCVector2 pointC)
        {
            PointA = pointA;
            PointB = pointB;
            PointC = pointC;

            LengthA = 0;
            LengthB = 0;
            LengthC = 0;
        }
Exemple #31
0
        public void DrawAABB(ref AABB aabb, Color color)
        {
            CCVector2[] verts = new CCVector2[4];
            verts[0] = new CCVector2(aabb.LowerBound.X, aabb.LowerBound.Y);
            verts[1] = new CCVector2(aabb.UpperBound.X, aabb.LowerBound.Y);
            verts[2] = new CCVector2(aabb.UpperBound.X, aabb.UpperBound.Y);
            verts[3] = new CCVector2(aabb.LowerBound.X, aabb.UpperBound.Y);

            DrawPolygon(verts, 4, color);
        }
        public void Advance (CCVector2 nextPoint, float nextLength)
        {
            PointA = PointB;
            PointB = PointC;
            PointC = nextPoint;

            LengthA = LengthB;
            LengthB = LengthC;
            LengthC = nextLength;
        }
Exemple #33
0
        /// <summary>
        /// Creates an open or closed <see cref="GraphicsPath"/> from a transformed copy of the path with a given <see cref="Pen"/>.
        /// </summary>
        /// <param name="pen">The pen to stroke the path with.</param>
        /// <param name="transform">The transform matrix to apply to all of the points in the path.</param>
        /// <param name="pathType">Whether the path is open or closed.</param>
        /// <returns>A computed <see cref="GraphicsPath"/>.</returns>
        public GraphicsPath Stroke(Pen pen, CCAffineTransform transform, PathType pathType)
        {
            CCVector2[] buffer = new CCVector2[_geometryIndex];
            for (int i = 0; i < _geometryIndex; i++)
            {
                buffer[i] = CCVector2.Transform(_geometryBuffer[i], transform);
            }

            return(new GraphicsPath(pen, buffer, _lengthBuffer, pathType, 0, _geometryIndex));
        }
        public JoinSample (CCVector2 pointA, CCVector2 pointB, CCVector2 pointC, float lengthA, float lengthB, float lengthC)
        {
            PointA = pointA;
            PointB = pointB;
            PointC = pointC;

            LengthA = lengthA;
            LengthB = lengthB;
            LengthC = lengthC;
        }
        public JoinSample (CCVector2 pointA, CCVector2 pointB, CCVector2 pointC)
        {
            PointA = pointA;
            PointB = pointB;
            PointC = pointC;

            LengthA = 0;
            LengthB = 0;
            LengthC = 0;
        }
Exemple #36
0
        private int AddStartOrEndPoint(int pointIndex, PenWorkspace ws, Buffer <CCVector2> positionBuffer, bool ccw)
        {
            int xyCount = ws.XYBuffer.Index;

            if (positionBuffer != null)
            {
                for (int i = 0; i < ws.OutlineIndexBuffer.Index; i++)
                {
                    positionBuffer.SetNext(ws.XYBuffer[ws.OutlineIndexBuffer[i]]);
                }
            }

            if (_strokeType == StrokeType.Outline)
            {
                return(0);
            }

            int baseIndex = _vertexBufferIndex;

            _vertexBufferIndex += xyCount;

            for (int i = 0; i < xyCount; i++)
            {
                _positionData[baseIndex + i] = ws.XYBuffer[i];
            }

            for (int i = 0; i < ws.IndexBuffer.Index; i++)
            {
                _indexData[_indexBufferIndex++] = (short)(baseIndex + ws.IndexBuffer[i]);
            }

            if (_colorData != null)
            {
                for (int i = 0; i < xyCount; i++)
                {
                    _colorData[baseIndex + i] = _pen.ColorAt(ws.UVBuffer[i], ws.PathLengthScale);
                }
            }

            if (_textureData != null)
            {
                int texWidth  = _pen.Brush.Texture.XNATexture.Width;
                int texHeight = _pen.Brush.Texture.XNATexture.Height;

                for (int i = baseIndex; i < _vertexBufferIndex; i++)
                {
                    CCVector2 pos = _positionData[i];
                    _textureData[i] = new CCVector2(pos.X / texWidth, pos.Y / texHeight);
                }
            }

            _jointCCW[pointIndex] = ccw;

            return(xyCount);
        }
Exemple #37
0
        /// <summary>
        /// Appends a fully-defined arc to the end of the path, connected by an additional line segment if the arc does not
        /// begin at the path's current endpoint.
        /// </summary>
        /// <param name="center">The center coordinate of the the arc.</param>
        /// <param name="radius">The radius of the arc.</param>
        /// <param name="startAngle">The starting angle of the arc in radians, where 0 is 3 O'Clock.</param>
        /// <param name="arcAngle">The sweep of the arc in radians.  Positive values draw clockwise.</param>
        /// <param name="subdivisions">The number of subdivisions in a circle of the same arc radius.</param>
        public void AddArc(CCVector2 center, float radius, float startAngle, float arcAngle, int subdivisions)
        {
            var startPoint = new CCVector2(center.X + radius * (float)Math.Cos(startAngle), center.Y + radius * (float)Math.Sin(startAngle));

            if (LastPointEqual(startPoint))
            {
                _geometryIndex--;
            }

            BuildArcGeometryBuffer(center, radius, subdivisions, startAngle, arcAngle);
        }
Exemple #38
0
        /// <summary>
        /// Appends an arc between the current endpoint and a point defined by a center and arc angle.
        /// </summary>
        /// <param name="center">The center of a circle containing the path's current endpoint and destination point.</param>
        /// <param name="arcAngle">The sweep of the arc in radians.  Positive values draw clockwise.</param>
        /// <exception cref="InvalidOperationException">The path has no existing points.</exception>
        public void AddArcByAngle(CCVector2 center, float arcAngle)
        {
            if (_geometryIndex == 0)
            {
                throw new InvalidOperationException("Cannot add an arc from partial information to an empty path.");
            }

            float radius = Math.Abs((_geometryBuffer[_geometryIndex - 1] - center).Length());

            AddArcByAngle(center, arcAngle, DefaultSubdivisions(radius));
        }
Exemple #39
0
        private static float PointToAngle(CCVector2 center, CCVector2 point)
        {
            double angle = Math.Atan2(point.Y - center.Y, point.X - center.X);

            if (angle < 0)
            {
                angle += Math.PI * 2;
            }

            return((float)angle);
        }
        private static PathBuilder BuildLillyPad(CCVector2 center, int radius, float rotation)
        {
            float segment = (float)(Math.PI * 2 / 32);

            PathBuilder builder = new PathBuilder();

            builder.AddPoint(center);
            builder.AddLine(radius, segment * 25 + rotation);
            builder.AddArcByAngle(center, segment * 30, radius / 2);

            return builder;
        }
        public CCFontSpriteFont (string fntFilePath, float fontSize, CCVector2? imageOffset = null)
        { 
            fontName = fntFilePath;
            this.fontSize = fontSize;

            this.imageOffset = CCVector2.Zero;

            if (imageOffset.HasValue)
                this.imageOffset = imageOffset.Value;

            fontScale = 1.0f;
        }
Exemple #42
0
        public CCFontFNT(string fntFilePath, CCVector2? imageOffset = null)
        { 
            
            Configuration = CCBMFontConfiguration.FontConfigurationWithFile(fntFilePath);
            this.imageOffset = CCVector2.Zero;

            if (imageOffset.HasValue)
                this.imageOffset = imageOffset.Value;

            if (Configuration != null)
                IsFontConfigValid = true;
        }
            public void Initialize(CCRect bounds, float mag)
            {
                ColorPen = new Pen(new Microsoft.Xna.Framework.Color(rand.Next(255), rand.Next(255), rand.Next(255)));

                for (int i = 0; i < Points.Length; i++)
                {
                    Points[i] = new CCVector2(bounds.MinX + (float)rand.NextDouble() * bounds.Size.Width, bounds.MaxY + (float)rand.NextDouble() * bounds.Size.Height);
                    Velocities[i] = new CCVector2((float)(rand.NextDouble() - .5) * mag, (float)(rand.NextDouble() - .5) * mag);

                    for (int j = 0; j < History.Count; j++)
                        History[j][i] = Points[i];
                }
            }
        private GraphicsPath CreateFlowerGP(Pen pen, CCVector2 center, int petalCount, float petalLength, float petalWidth, float rotation)
        {
            List<CCVector2> points = StarPoints(center, petalCount / 2, petalLength, petalLength, rotation, false);

            PathBuilder builder = new PathBuilder();
            builder.AddPoint(center);

            foreach (CCVector2 point in points)
            {
                builder.AddArcByPoint(point, petalWidth / 2);
                builder.AddArcByPoint(center, petalWidth / 2);
            }

            return builder.Stroke(pen, PathType.Closed);
        }
        public static CCFontAtlas GetFontAtlasFNT(CCFontFNT font, CCVector2 imageOffset = default(CCVector2))
        {
            if (font != null)
            {
                var atlasName = font.Configuration.AtlasName;
                var tempAtlas = font.CreateFontAtlas();
                if (tempAtlas != null)
                {
                    atlasMap[atlasName] = tempAtlas;
                    return atlasMap[atlasName];
                }
            }


            return null;
        }
        protected static List<CCVector2> StarPoints(CCVector2 center, int pointCount, float outerRadius, float innerRadius, float rotation, bool close)
        {
            List<CCVector2> points = new List<CCVector2>();

            int limit = (close) ? pointCount * 2 + 1 : pointCount * 2;

            float rot = (float)((Math.PI * 2) / (pointCount * 2));
            for (int i = 0; i < limit; i++)
            {
                float si = (float)Math.Sin(-i * rot + Math.PI + rotation);
                float ci = (float)Math.Cos(-i * rot + Math.PI + rotation);

                if (i % 2 == 0)
                    points.Add(center + new CCVector2(si, ci) * outerRadius);
                else
                    points.Add(center + new CCVector2(si, ci) * innerRadius);
            }

            return points;
        }
        /// <summary>
        /// Constructor to create a Bitmap Font configuration object from a .FNT configuration file
        /// string to be parsed and a Stream object of the Atlas Texture to be used.
        /// </summary>
        /// <param name="configInfo">String representation read from a .FNT configuration</param>
        /// <param name="atlasTexture">CCTexture2D Atlas to be used.</param>
        /// <param name="imageOffset">Image Offset</param>
        public CCFontFNT(string configInfo, CCTexture2D atlasTexture, CCVector2? imageOffset = null)
        {

            try
            {
                Configuration = new CCBMFontConfiguration(configInfo, string.Empty);
            }
            catch (Exception exc)
            {
                throw new ContentLoadException("Bitmap Font Configuration is invalid: " + exc.Message);
            }

            this.imageOffset = CCVector2.Zero;

            if (imageOffset.HasValue)
                this.imageOffset = imageOffset.Value;

            AtlasTexture = atlasTexture;

            if (Configuration != null)
                IsFontConfigValid = true;
        }
        public override void Update(GameSettings settings, GameTime gameTime)
        {
            Manifold manifold = new Manifold();
            Collision.Collision.CollidePolygons(ref manifold, _polygonA, ref _transformA, _polygonB, ref _transformB);

            Vector2 normal;
            FixedArray2<Vector2> points;
            Collision.Collision.GetWorldManifold(ref manifold, ref _transformA, _polygonA.Radius,
                                                 ref _transformB, _polygonB.Radius, out normal, out points);

            DebugView.DrawString(50, TextLine, "Point count = {0:n0}", manifold.PointCount);
            TextLine += 15;
            DebugView.BeginCustomDraw();
            {
                Color color = new Color(0.9f, 0.9f, 0.9f);
                CCVector2[] v = new CCVector2[Settings.MaxPolygonVertices];
                for (int i = 0; i < _polygonA.Vertices.Count; ++i)
                {
                    v[i] = (CCVector2)MathUtils.Multiply(ref _transformA, _polygonA.Vertices[i]);
                }

				DebugView.DrawPolygon(v, _polygonA.Vertices.Count, color);

                for (int i = 0; i < _polygonB.Vertices.Count; ++i)
                {
                    v[i] = (CCVector2)MathUtils.Multiply(ref _transformB, _polygonB.Vertices[i]);
                }
				DebugView.DrawPolygon(v, _polygonB.Vertices.Count, color);
            }

            for (int i = 0; i < manifold.PointCount; ++i)
            {
                DebugView.DrawPoint(points[i], 0.1f, new Color(0.9f, 0.3f, 0.3f));
            }
            DebugView.EndCustomDraw();
        }
Exemple #49
0
        private void DrawFixture(Fixture fixture)
        {
            Color color = new Color(0.95f, 0.95f, 0.6f);
            Transform xf;
            fixture.Body.GetTransform(out xf);

            switch (fixture.Shape.ShapeType)
            {
                case ShapeType.Circle:
                    {
                        CircleShape circle = (CircleShape)fixture.Shape;

                        Vector2 center = MathUtils.Multiply(ref xf, circle.Position);
                        float radius = circle.Radius;

                        DebugDraw.DrawSolidCircle(center, radius, Vector2.Zero, color);
                    }
                    break;

                case ShapeType.Polygon:
                    {
                        PolygonShape poly = (PolygonShape)fixture.Shape;
                        int vertexCount = poly.Vertices.Count;
                        Debug.Assert(vertexCount <= Settings.MaxPolygonVertices);
                        CCVector2[] vertices = new CCVector2[Settings.MaxPolygonVertices];

                        for (int i = 0; i < vertexCount; ++i)
                        {
                            vertices[i] = (CCVector2)MathUtils.Multiply(ref xf, poly.Vertices[i]);
                        }

					DebugDraw.DrawSolidPolygon(vertices, vertexCount, color);
                    }
                    break;
            }
        }
 public void Advance (CCVector2 nextPoint)
 {
     PointA = PointB;
     PointB = PointC;
     PointC = nextPoint;
 }
 protected static List<CCVector2> ShiftPath(List<CCVector2> path, float x, float y)
 {
     for (int i = 0; i < path.Count; i++)
         path[i] = new CCVector2(path[i].X + x, path[i].Y + y);
     return path;
 }
Exemple #52
0
        public override void Update(GameSettings settings, GameTime gameTime)
        {
            base.Update(settings, gameTime);

            Sweep sweepA = new Sweep();
            sweepA.C0 = new Vector2(24.0f, -60.0f);
            sweepA.A0 = 2.95f;
            sweepA.C = sweepA.C0;
            sweepA.A = sweepA.A0;
            sweepA.LocalCenter = Vector2.Zero;

            Sweep sweepB = new Sweep();
            sweepB.C0 = new Vector2(53.474274f, -50.252514f);
            sweepB.A0 = 513.36676f; // - 162.0f * b2_pi;
            sweepB.C = new Vector2(54.595478f, -51.083473f);
            sweepB.A = 513.62781f; //  - 162.0f * b2_pi;
            sweepB.LocalCenter = Vector2.Zero;

            //sweepB.a0 -= 300.0f * b2_pi;
            //sweepB.a -= 300.0f * b2_pi;

            TOIInput input = new TOIInput();
            input.ProxyA.Set(_shapeA, 0);
            input.ProxyB.Set(_shapeB, 0);
            input.SweepA = sweepA;
            input.SweepB = sweepB;
            input.TMax = 1.0f;

            TOIOutput output;
            TimeOfImpact.CalculateTimeOfImpact(out output, input);

            DebugView.DrawString(50, TextLine, "TOI = {0:n}", output.T);
            TextLine += 15;

            DebugView.DrawString(50, TextLine, "Max TOI iters = {0:n}, Max root iters = {1:n}", TimeOfImpact.TOIMaxIters,
                                 TimeOfImpact.TOIMaxRootIters);
            TextLine += 15;

            CCVector2[] vertices = new CCVector2[Settings.MaxPolygonVertices];

            DebugView.BeginCustomDraw();
            Transform transformA;
            sweepA.GetTransform(out transformA, 0.0f);
            for (int i = 0; i < _shapeA.Vertices.Count; ++i)
            {
                vertices[i] = (CCVector2)MathUtils.Multiply(ref transformA, _shapeA.Vertices[i]);
            }
			DebugView.DrawPolygon(vertices, _shapeA.Vertices.Count, new Color(0.9f, 0.9f, 0.9f));

            Transform transformB;
            sweepB.GetTransform(out transformB, 0.0f);

            for (int i = 0; i < _shapeB.Vertices.Count; ++i)
            {
                vertices[i] = (CCVector2)MathUtils.Multiply(ref transformB, _shapeB.Vertices[i]);
            }
			DebugView.DrawPolygon(vertices, _shapeB.Vertices.Count, new Color(0.5f, 0.9f, 0.5f));

            sweepB.GetTransform(out transformB, output.T);
            for (int i = 0; i < _shapeB.Vertices.Count; ++i)
            {
                vertices[i] = (CCVector2)MathUtils.Multiply(ref transformB, _shapeB.Vertices[i]);
            }
			DebugView.DrawPolygon(vertices, _shapeB.Vertices.Count, new Color(0.5f, 0.7f, 0.9f));

            sweepB.GetTransform(out transformB, 1.0f);
            for (int i = 0; i < _shapeB.Vertices.Count; ++i)
            {
                vertices[i] = (CCVector2)MathUtils.Multiply(ref transformB, _shapeB.Vertices[i]);
            }
			DebugView.DrawPolygon(vertices, _shapeB.Vertices.Count, new Color(0.9f, 0.5f, 0.5f));
            DebugView.EndCustomDraw();
        }
 private float Cross2D (CCVector2 u, CCVector2 v)
 {
     return (u.Y * v.X) - (u.X * v.Y);
 }
        List<CCVector2> GetSeparatingVector(CCRect first, RectWithDirection second)
        {
            //返回一个向量,是player在碰撞之后反方向移动的向量

            List<CCVector2> separation = new List<CCVector2> {
                CCVector2.Zero,
                CCVector2.Zero,
                CCVector2.Zero,
                CCVector2.Zero
            };

            // Only calculate separation if the rectangles intersect
            if (Intersects(first, second))
            {
                // The intersectionRect returns the rectangle produced
                // by overlapping the two rectangles.
                // This is protected by partitioning and deep collision, so it
                // won't happen too often - it's okay to do a ToRect here
                //得到两个rect重叠部分的rect
                var intersectionRect = first.Intersection (second.ToRect());

                float minDistance = float.PositiveInfinity;

                float firstCenterX = first.Center.X;
                float firstCenterY = first.Center.Y;

                float secondCenterX = second.Left + second.Width / 2.0f;
                float secondCenterY = second.Bottom + second.Height / 2.0f;

                //second的方向和想要判断的方向(左)取交集,如果和想要判断的方向(左)一致,且第一个的中心点在第二个的中心点的(左边)
                //则当碰撞时,player可以向想要的方向移动
                bool canMoveLeft = (second.Directions & Directions.Left) == Directions.Left && firstCenterX < secondCenterX;
                bool canMoveRight = (second.Directions & Directions.Right) == Directions.Right && firstCenterX > secondCenterX;
                bool canMoveDown = (second.Directions & Directions.Down) == Directions.Down && firstCenterY < secondCenterY;
                bool canMoveUp = (second.Directions & Directions.Up) == Directions.Up && firstCenterY > secondCenterY;

                if (canMoveLeft)
                {
                    //左重叠
                    //得到重叠的rect的X方向边长
                    float candidate = first.UpperRight.X - second.Left;

                    if (candidate > 0)
                    {
                        minDistance = candidate;
                        //x方向移动回到地图实体瓦片的外面,y方向不动
                        separation [0] = new CCVector2 (-minDistance, 0);
                    }

                }

                if (canMoveRight)
                {
                    //右重叠
                    float candidate = (second.Left + second.Width) - first.LowerLeft.X;

                    if (candidate > 0)
                    {
                        minDistance = candidate;
                        //向右移动
                        separation [1] = new CCVector2 (minDistance, 0);
                    }

                }

                //其他方向同理
                if (canMoveUp)
                {
                    float candidate = (second.Bottom + second.Height) - first.Origin.Y;

                    if (candidate > 0)
                    {
                        minDistance = candidate;
                        separation [2] = new CCVector2 (0, minDistance);
                    }

                }

                if (canMoveDown)
                {
                    float candidate = first.UpperRight.Y - second.Bottom;

                    if (candidate > 0)
                    {
                        minDistance = candidate;
                        separation [3] = new CCVector2 (0, -minDistance);
                    }

                }

                if ((intersectionRect.UpperRight.X > (second.Left + first.Size.Width))
                   && (intersectionRect.LowerLeft.X < (second.Left + second.Width - first.Size.Width))) {
                    separation [0] = new CCVector2 (0, 0);
                    separation [1] = new CCVector2 (0, 0);
                }

            }

            //左后返回player移动的vector
            return separation;
        }
Exemple #55
0
        public override void Update(GameSettings settings, GameTime gameTime)
        {
            base.Update(settings, gameTime);

            DistanceInput input = new DistanceInput();
            input.ProxyA.Set(_polygonA, 0);
            input.ProxyB.Set(_polygonB, 0);
            input.TransformA = _transformA;
            input.TransformB = _transformB;
            input.UseRadii = true;
            SimplexCache cache;
            cache.Count = 0;
            DistanceOutput output;
            Distance.ComputeDistance(out output, out cache, input);

            DebugView.DrawString(50, TextLine, "Distance = {0:n7}", output.Distance);
            TextLine += 15;

            DebugView.DrawString(50, TextLine, "Iterations = {0:n0}", output.Iterations);
            TextLine += 15;

            DebugView.BeginCustomDraw();
            {
                Color color = new Color(0.9f, 0.9f, 0.9f);
                CCVector2[] v = new CCVector2[Settings.MaxPolygonVertices];
                for (int i = 0; i < _polygonA.Vertices.Count; ++i)
                {
                    v[i] = (CCVector2)MathUtils.Multiply(ref _transformA, _polygonA.Vertices[i]);
                }
				DebugView.DrawPolygon(v, _polygonA.Vertices.Count, color);

                for (int i = 0; i < _polygonB.Vertices.Count; ++i)
                {
                    v[i] = (CCVector2)MathUtils.Multiply(ref _transformB, _polygonB.Vertices[i]);
                }
				DebugView.DrawPolygon(v, _polygonB.Vertices.Count, color);
            }

            Vector2 x1 = output.PointA;
            Vector2 x2 = output.PointB;


            DebugView.DrawPoint(x1, 0.5f, new Color(1.0f, 0.0f, 0.0f));
            DebugView.DrawPoint(x2, 0.5f, new Color(1.0f, 0.0f, 0.0f));

            DebugView.DrawSegment(x1, x2, new Color(1.0f, 1.0f, 0.0f));
            DebugView.EndCustomDraw();
        }
 /// <summary>
 /// Adds a primitive ellipse path to the batch of figures to be rendered.
 /// </summary>
 /// <param name="pen">The pen supplying the color to render the path with.</param>
 /// <param name="center">The center of the ellipse.</param>
 /// <param name="xRadius">The radius of the ellipse along the x-axis.</param>
 /// <param name="yRadius">The radius of the ellipse along the y-acis.</param>
 /// <param name="angle">The angle to rotate the ellipse by in radians.  Positive values rotate clockwise.</param>
 /// <exception cref="InvalidOperationException"><c>DrawPrimitiveEllipse</c> was called, but <see cref="Begin()"/> has not yet been called.</exception>
 /// <remarks>The number of subdivisions in the ellipse is computed as max(xRadius, yRadius) / 1.5.</remarks>
 public void DrawPrimitiveEllipse (Pen pen, CCVector2 center, float xRadius, float yRadius, float angle)
 {
     DrawPrimitiveEllipse(pen, center, xRadius, yRadius, angle, DefaultSubdivisions(xRadius, yRadius));
 }
		public void AddVertex(ref CCVector2 vertex, CCColor4B color, PrimitiveType primitiveType)
        {
            if (!hasBegun)
            {
                throw new InvalidOperationException("Begin must be called before AddVertex can be called.");
            }

            if (primitiveType == PrimitiveType.LineStrip || primitiveType == PrimitiveType.TriangleStrip)
            {
                throw new NotSupportedException("The specified primitiveType is not supported by PrimitiveBatch.");
            }

            if (primitiveType == PrimitiveType.TriangleList)
            {
                if (triangleVertsCount >= triangleVertices.Length)
                {
                    FlushTriangles();
                }
                triangleVertices[triangleVertsCount].Vertices = new CCVertex3F(vertex.X, vertex.Y, -0.1f);
				triangleVertices[triangleVertsCount].Colors = color;
                triangleVertsCount++;
            }

            if (primitiveType == PrimitiveType.LineList)
            {
                if (lineVertsCount >= lineVertices.Length)
                {
                    FlushLines();
                }
                lineVertices[lineVertsCount].Vertices = new CCVertex3F(vertex.X, vertex.Y, 0.0f);
				lineVertices[lineVertsCount].Colors = color;
                lineVertsCount++;
            }
        }
		public void AddVertex(CCVector2 vertex, CCColor4B color, PrimitiveType primitiveType)
        {
			AddVertex(ref vertex, color, primitiveType);
        }
 private bool PointInTriangleInclusive (CCVector2 point, CCVector2 a, CCVector2 b, CCVector2 c)
 {
     if (Cross2D(point - a, b - a) <= 0f)
         return false;
     if (Cross2D(point - b, c - b) <= 0f)
         return false;
     if (Cross2D(point - c, a - c) <= 0f)
         return false;
     return true;
 }
 private bool TriangleIsCCW (CCVector2 a, CCVector2 b, CCVector2 c)
 {
     return Cross2D(b - a, c - b) < 0;
 }