private int CalculateIndex(Geom geom1, Geom geom2) { int x; int y; if (geom1.CollisionId < geom2.CollisionId) { x = geom1.CollisionId; y = geom2.CollisionId; } else { x = geom2.CollisionId; y = geom1.CollisionId; } int result = x * _geomCount; if (x % 2 == 0) { result -= ((x + 1) * (x / 2)); } else { result -= (x + 1) * (x / 2) + (x + 1) / 2; } result += y - x - 1; return result; }
public override void LoadContent() { _lineBrush.Load(ScreenManager.GraphicsDevice); _rectangleTexture = DrawingHelper.CreateRectangleTexture(ScreenManager.GraphicsDevice, 32, 32, 2, 0, 0, Color.White, Color.Black); _rectangleBody = BodyFactory.Instance.CreateRectangleBody(32, 32, 1f); //template _rectangleGeom = GeomFactory.Instance.CreateRectangleGeom(_rectangleBody, 32, 32); //template _rectangleGeom.FrictionCoefficient = .4f; _rectangleGeom.RestitutionCoefficient = 0f; //create the _pyramid near the bottom of the screen. _pyramid = new Pyramid(_rectangleBody, _rectangleGeom, 32f / 3f, 32f / 3f, 32, 32, _pyramidBaseBodyCount, new Vector2(ScreenManager.ScreenCenter.X - _pyramidBaseBodyCount * .5f * (32 + 32 / 3), ScreenManager.ScreenHeight - 125)); _pyramid.Load(PhysicsSimulator); _floor = new Floor(ScreenManager.ScreenWidth, 100, new Vector2(ScreenManager.ScreenCenter.X, ScreenManager.ScreenHeight - 50)); _floor.Load(ScreenManager.GraphicsDevice, PhysicsSimulator); _agent = new Agent(ScreenManager.ScreenCenter - new Vector2(320, 300)); _agent.Load(ScreenManager.GraphicsDevice, PhysicsSimulator); base.LoadContent(); }
//use this constructor when you want to add a sprite from the content pipeline //sprites should have a pure magenta background for //transparency public sprite(theGame reference, String contentAssetName, float width, float height, float X, float Y) { asset = reference.Content.Load<Texture2D>(contentAssetName); spriteOrigin = new Vector2(asset.Width / 2f, asset.Height / 2f); this.X = X; this.Y = Y; this.width = width; this.height = height; rectangle = new Rectangle((int)this.X, (int)this.Y, (int)width, (int)height); this.identity = identity; this.reference = reference; rectBody = BodyFactory.Instance.CreateRectangleBody(reference.ps, width, height, 1);//PHYSICS rectBody.Position = new FarseerGames.FarseerPhysics.Mathematics.Vector2(this.X, this.Y);//PHYSICS rectGeom = GeomFactory.Instance.CreateRectangleGeom(reference.ps,rectBody, this.width, this.height);//PHYSICS rectGeom.SetBody(rectBody); rectGeom.CollisionEnabled = true; this.rectGeom.CollisionResponseEnabled = true; this.rectGeom.CollisionCategories = CollisionCategory.All; this.rectGeom.CollidesWith = CollisionCategory.All; rectBody.Enabled = true;//PHYSICS rectGeom.OnSeparation += OnSeperation; rectGeom.OnCollision += OnCollision; reference.ps.BroadPhaseCollider.OnBroadPhaseCollision += OnBroadPhaseCollision; reference.ps.Add(rectBody); reference.ps.Add(rectGeom); }
public override void Initialize() { ClearCanvas(); physicsSimulator = new PhysicsSimulator(new Vector2(0, 100)); physicsSimulator.BiasFactor = .4f; int borderWidth = (int) (ScreenManager.ScreenHeight*.05f); _border = new Border(ScreenManager.ScreenWidth + borderWidth*2, ScreenManager.ScreenHeight + borderWidth*2, borderWidth, ScreenManager.ScreenCenter); _border.Load(this, physicsSimulator); _rectangleBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, 32, 32, 1f); _rectangleGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rectangleBody, 32, 32); _rectangleGeom.FrictionCoefficient = .4f; _rectangleGeom.RestitutionCoefficient = 0f; //create the pyramid near the bottom of the screen. _pyramid = new Pyramid(_rectangleBody, _rectangleGeom, 32f/3f, 32f/3f, 32, 32, _pyramidBaseBodyCount, new Vector2(ScreenManager.ScreenCenter.X - _pyramidBaseBodyCount*.5f*(32 + 32/3), ScreenManager.ScreenHeight - 125)); _pyramid.Load(this, physicsSimulator); _floor = new Floor(ScreenManager.ScreenWidth, 100, new Vector2(ScreenManager.ScreenCenter.X, ScreenManager.ScreenHeight - 50)); _floor.Load(this, physicsSimulator); _agent = new Agent(ScreenManager.ScreenCenter - new Vector2(320, 300)); _agent.Load(this, physicsSimulator); controlledBody = _agent.Body; base.Initialize(); }
public Table(Vector2 position, float width, float height) { Random rand = new Random(); _topBody = BodyFactory.Instance.CreateRectangleBody(width, 10, 6); _rightLegBody = BodyFactory.Instance.CreateRectangleBody(10, height, 3); _leftLegBody = BodyFactory.Instance.CreateRectangleBody(10, height, 3); _topGeom = GeomFactory.Instance.CreateRectangleGeom(_topBody, width, 10); _rightLegGeom = GeomFactory.Instance.CreateRectangleGeom(_rightLegBody, 10, height); _leftLegGeom = GeomFactory.Instance.CreateRectangleGeom(_leftLegBody, 10, height); _topBody.Position = position; _leftLegBody.Position = new Vector2(position.X - (width / 2) + 10, position.Y + (height / 2) + 5); _rightLegBody.Position = new Vector2(position.X + (width / 2) - 10, position.Y + (height / 2) + 5); int group = rand.Next(1, 100); _rightLegGeom.CollisionGroup = group; _leftLegGeom.CollisionGroup = group; _topGeom.CollisionGroup = group; _rightLegGeom.RestitutionCoefficient = 0; _leftLegGeom.RestitutionCoefficient = 0; _topGeom.RestitutionCoefficient = 0; _height = height; }
public bool TestAndSet(Geom geom1, Geom geom2) { int index = CalculateIndex(geom1, geom2); bool result = _bitmap[index]; _bitmap[index] = true; return result; }
void ItemBase.InitSelf() { X = 200; Y = 100; body = BodyFactory.Instance.CreateRectangleBody(PhysicsSys.Instance.PhysicsSimulator,100.0f, 100.0f,100.0f); body.Position = new Vector2(X, Y); geom = GeomFactory.Instance.CreateRectangleGeom(PhysicsSys.Instance.PhysicsSimulator, body, 100, 100); }
public void load(ContentManager Content) { Vector2 origin; texture = Content.Load<Texture2D>(textureName); body = BodyFactory.Instance.CreateBody(1f, 1f); geom = GeomFactory.Instance.CreateRectangleGeom(body, texture.Width, texture.Height); geom.Tag = _id; }
/// <summary> /// Finds the contactpoints between the two geometries. /// </summary> /// <param name="geomA">The first geom.</param> /// <param name="geomB">The second geom.</param> /// <param name="contactList">The contact list.</param> public void Collide(Geom geomA, Geom geomB, ContactList contactList) { int vertexIndex = -1; //Lookup distancegrid A data from list DistanceGridData geomAGridData = _distanceGrids[geomA.id]; //Iterate the second geometry vertices for (int i = 0; i < geomB.worldVertices.Count; i++) { if (contactList.Count == PhysicsSimulator.MaxContactsToDetect) break; vertexIndex += 1; _vertRef = geomB.WorldVertices[i]; geomA.TransformToLocalCoordinates(ref _vertRef, out _localVertex); //The geometry intersects when distance <= 0 //Continue in the list if the current vector does not intersect if (!geomAGridData.Intersect(ref _localVertex, out _feature)) continue; //If the geometries collide, create a new contact and add it to the contact list. if (_feature.Distance < 0f) { geomA.TransformNormalToWorld(ref _feature.Normal, out _feature.Normal); Contact contact = new Contact(geomB.WorldVertices[i], _feature.Normal, _feature.Distance, new ContactId(1, vertexIndex, 2)); contactList.Add(contact); } } //Lookup distancegrid B data from list DistanceGridData geomBGridData = _distanceGrids[geomB.id]; //Iterate the first geometry vertices for (int i = 0; i < geomA.WorldVertices.Count; i++) { if (contactList.Count == PhysicsSimulator.MaxContactsToDetect) break; vertexIndex += 1; _vertRef = geomA.WorldVertices[i]; geomB.TransformToLocalCoordinates(ref _vertRef, out _localVertex); if (!geomBGridData.Intersect(ref _localVertex, out _feature)) continue; if (_feature.Distance < 0f) { geomB.TransformNormalToWorld(ref _feature.Normal, out _feature.Normal); _feature.Normal = -_feature.Normal; Contact contact = new Contact(geomA.WorldVertices[i], _feature.Normal, _feature.Distance, new ContactId(2, vertexIndex, 1)); contactList.Add(contact); } } }
public void EntryEventHandler(Geom geom, Vertices verts) { for (int i = 0; i < verts.Count; i++) { Vector2 vel, point = verts[i]; geom.Body.GetVelocityAtWorldPoint(ref point, out vel); WaveController.Disturb(verts[i].X, (vel.Y * geom.Body.Mass) / (100.0f * geom.Body.Mass)); } }
public Sprite() { position = new Vector2(0.0f, 0.0f); rotation = 0.0f; origin = new Vector2(0.0f, 0.0f); currentTexture = null; body = null; geom = null; }
public Planet(PhysicsSimulator sim, Texture2D tex, Vector2 pos, float size, float mass) { body = BodyFactory.Instance.CreateCircleBody(sim, size, mass); geometry = GeomFactory.Instance.CreateCircleGeom(body, size, 64); body.Position = pos; geometry.RestitutionCoefficient = 0.2f; geometry.FrictionCoefficient = 0.9f; texture = tex; }
/// <summary> /// 重载AnimItem的SetSize方法 /// 1. 调用基类方法修改scale /// 2. 创建或重建物理体 构造尺寸 /// 注意: 物理体Mass需要通过PhysicsItem.Mass单独设置 /// </summary> public override void SetSize(Vector2 size) { // 设置图形尺寸 base.SetSize(size); // 创建或重建物理体 // 默认取质量10 body = BodyFactory.Instance.CreateRectangleBody(PhysicsSys.Instance.PhysicsSimulator,Size.X, Size.Y,10); geom = GeomFactory.Instance.CreateRectangleGeom(PhysicsSys.Instance.PhysicsSimulator, body, Size.X, Size.Y); }
protected bool oncollision(Geom geom1, Geom geom2, ContactList contact) { Iid id1 = (Iid)geom1.Tag; Iid id2 = (Iid)geom2.Tag; if (id1.UnitID == UnitID.obstacle && id2.UnitID == UnitID.player) { master.players[id2.NodeID].body.ApplyForce(this.rotationV2 * 4333333); master.players[id2.NodeID].addPush(4000f); } return false; }
public Box(PhysicsSimulator pS, Texture2D tex, float x, float y, float width, float heigth, float mass) { boxTex = tex; wdth = width; hgth = heigth; boxBody = BodyFactory.Instance.CreateRectangleBody(pS, width, heigth, mass); boxBody.Position = new Vector2(x, y); boxGeom = GeomFactory.Instance.CreateRectangleGeom(pS, boxBody, 0.9f*width, 0.9f*heigth); boxGeom.FrictionCoefficient = 0.8f; boxOrigin = new Vector2(boxTex.Width / 2, boxTex.Height / 2); }
public Pyramid(Body referenceBody, Geom referenceGeom, float horizontalSpacing, float verticleSpacing, float blockWidth, float blockHeight, int bottomRowBlockCount, Vector2 bottomRightBlockPosition) { _referenceBody = referenceBody; _referenceGeom = referenceGeom; _horizontalSpacing = horizontalSpacing; _verticleSpacing = verticleSpacing; _blockWidth = blockWidth; _blockHeight = blockHeight; _bottomRowBlockCount = bottomRowBlockCount; _bottomRightBlockPosition = bottomRightBlockPosition; }
public void InitSelf() { X = 200; Y = 500; rotation=0; body = BodyFactory.Instance.CreateRectangleBody(PhysicsSys.Instance.PhysicsSimulator,100.0f, 100.0f,100.0f); body.Position = new Vector2(X, Y); body.Rotation = 0.1f; body.IsStatic = true;//静态 geom = GeomFactory.Instance.CreateRectangleGeom(PhysicsSys.Instance.PhysicsSimulator, body, 100, 100); }
/// <summary> /// Returns the contact list from two possibly intersecting Geom's. /// This is the stationary version of this function. It doesn't /// account for linear or angular motion. /// </summary> /// <param name="geomA">The first Geom.</param> /// <param name="geomB">The second Geom.</param> /// <param name="contactList">Set of Contacts between the two Geoms. /// NOTE- this will be empty if no contacts are present.</param> public void Collide(Geom geomA, Geom geomB, ContactList contactList) { PolygonCollisionResult result = PolygonCollision(geomA.WorldVertices, geomB.WorldVertices, geomB.body.LinearVelocity - geomA.body.LinearVelocity); float distance = result.MinimumTranslationVector.Length(); int contactsDetected = 0; Vector2 normal = Vector2.Normalize(-result.MinimumTranslationVector); if (result.Intersect) { for (int i = 0; i < geomA.WorldVertices.Count; i++) { if (contactsDetected <= PhysicsSimulator.MaxContactsToDetect) { if (InsidePolygon(geomB.WorldVertices, geomA.WorldVertices[i])) { if (!geomA.Body.IsStatic) { if (distance > 0.001f) { Contact c = new Contact(geomA.WorldVertices[i], normal, -distance, new ContactId(geomA.id, i, geomB.id)); contactList.Add(c); contactsDetected++; } } } } else break; } contactsDetected = 0; for (int i = 0; i < geomB.WorldVertices.Count; i++) { if (contactsDetected <= PhysicsSimulator.MaxContactsToDetect) { if (InsidePolygon(geomA.WorldVertices, geomB.WorldVertices[i])) { if (!geomB.Body.IsStatic) { if (distance > 0.001f) { Contact c = new Contact(geomB.WorldVertices[i], normal, -distance, new ContactId(geomB.id, i, geomA.id)); contactList.Add(c); contactsDetected++; } } } } else break; } } }
public Rectangle(PhysicsSimulator pS, Vector2 pos) { physicsS = pS; xSize = 50; ySize = 50; xSizePrev = xSize; ySizePrev = ySize; placing = true; rBody = BodyFactory.Instance.CreateRectangleBody(pS, 50, 50, 1); rBody.IgnoreGravity = true; rBody.Position = pos; rGeom = GeomFactory.Instance.CreateRectangleGeom(pS, rBody, 50, 50); }
public void Load(SimulatorView view, PhysicsSimulator physicsSimulator) { //use the body factory to create the physics body _platformBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); view.AddRectangleToCanvas(_platformBody, Colors.White, new Vector2(_width, _height)); _platformBody.IsStatic = true; _platformBody.Position = _position; _platformGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _platformBody, _width, _height); _platformGeom.CollisionGroup = 100; _platformGeom.CollisionGroup = _collisionGroup; _platformGeom.FrictionCoefficient = 1; }
public int Compare(Node x, Node y) { if (Math.Abs(x.Distance - y.Distance) < Geom.GetPrecision() && x == y) { return(0); } int res = x.Distance.CompareTo(y.Distance); if (res == 0) { return(x.CompareTo(y)); } return(res); }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _floorTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, _width, _height, 0, 1, 1, Color.White, Color.Black); _floorOrigin = new Vector2(_floorTexture.Width / 2f, _floorTexture.Height / 2f); //use the body factory to create the physics body _floorBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); _floorBody.IsStatic = true; _floorGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _floorBody, _width, _height); _floorGeom.RestitutionCoefficient = .4f; _floorGeom.FrictionCoefficient = .4f; _floorBody.Position = _position; }
public static void clonegeom(ref Geom newgeom, ref Geom oldgeom) { newgeom.Id = Geom.GetNextId(); newgeom.RestitutionCoefficient = oldgeom.RestitutionCoefficient; newgeom.FrictionCoefficient = oldgeom.FrictionCoefficient; newgeom.GridCellSize = oldgeom.GridCellSize; newgeom.CollisionGroup = oldgeom.CollisionGroup; newgeom.CollisionEnabled = oldgeom.CollisionEnabled; newgeom.CollisionResponseEnabled = oldgeom.CollisionResponseEnabled; newgeom.CollisionCategories = oldgeom.CollisionCategories; newgeom.CollidesWith = oldgeom.CollidesWith; newgeom.SetVertices(oldgeom.LocalVertices); DistanceGrid.Instance.CreateDistanceGrid(newgeom); }
/// <summary> /// Renders a simple representation of the element while it is selected in edit mode. /// </summary> /// <param name="g">The graphics context to render to.</param> public override void RenderSelected(Graphics g) { g.DrawEllipse(new Pen(Constants.SelectedColor, 2), Geom.CircleToRectangle(this.Location, this.Radius)); g.FillEllipse( new SolidBrush(Constants.SelectedColor), Geom.CircleToRectangle(this.Location, this.Radius / 5)); if (this.RelevantManipulation?.Type == ElementManipulationType.Scale) { g.DrawEllipse( new Pen(Constants.SelectedColorSpecial, 3), Geom.CircleToRectangle(this.Location, this.Radius)); } }
private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (_mousePickSpring != null) return; Vector2 point = new Vector2((float) (e.GetPosition(_canvas).X), (float) (e.GetPosition(_canvas).Y)); point = ConvertUnits.ToSimUnits(point); _pickedGeom = _physicsSimulator.Collide(point); if (_pickedGeom != null) { _mousePickSpring = SpringFactory.Instance.CreateFixedLinearSpring(_physicsSimulator, _pickedGeom.Body, _pickedGeom.Body.GetLocalPosition( point), point, 20, 10); _mousePickLine.Visibility = Visibility.Visible; } }
public Hero(PhysicsSimulator pS) { hBody = BodyFactory.Instance.CreateEllipseBody(pS, 32, 32, 2); //hBody = BodyFactory.Instance.CreateRectangleBody(pS, 64, 64, 1); hBody.Position = new Vector2(512, 381); //hBody.IsStatic = true; //hBody.IgnoreGravity = true; hGeom = GeomFactory.Instance.CreateEllipseGeom(pS, hBody, 32, 32, 12); hGeom.FrictionCoefficient = 1f; hGeom.CollisionGroup = 3; hGeom.OnSeparation += onSeperation; hGeom.OnCollision += onCollision; //hGeom = GeomFactory.Instance.CreateRectangleGeom(pS, hBody, 64, 64); }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _texture = DrawingSystem.DrawingHelper.CreateCircleTexture(graphicsDevice, _radius, Color.Yellow, Color.Black); _origin = new Vector2(_texture.Width / 2f, _texture.Height / 2f); _body = BodyFactory.Instance.CreateCircleBody(physicsSimulator, _radius, 1); //NOTICE how the grid cell size is 0.5f, this causes the physics engine to take a long time //to calculate the collision grid. This is only a demonstration! _geom = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, _body, _radius, 10, 0.5f); _geom.CollisionGroup = 1; _geom.CollidesWith = _collidesWith; _geom.CollisionCategories = _collisionCategory; }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _floorTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, _width, _height, 0, 1, 1, Color.White, Color.Black); _floorOrigin = new Vector2(_floorTexture.Width/2f, _floorTexture.Height/2f); //use the body factory to create the physics body _floorBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); _floorBody.IsStatic = true; _floorGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _floorBody, _width, _height); _floorGeom.RestitutionCoefficient = .4f; _floorGeom.FrictionCoefficient = .4f; _floorBody.Position = _position; }
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); Vector2 point = new Vector2((float)(e.GetPosition(this).X), (float)(e.GetPosition(this).Y)); pickedGeom = physicsSimulator.Collide(point); if (pickedGeom != null) { mousePickSpring = SpringFactory.Instance.CreateFixedLinearSpring(physicsSimulator, pickedGeom.Body, pickedGeom.Body.GetLocalPosition( point), point, 20, 10); mouseSpringVisual = AddFixedLinearSpringVisualToCanvas(mousePickSpring); } }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _platformTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, _width, _height, 2, 0, 0, _color, _borderColor); _platformOrigin = new Vector2(_platformTexture.Width/2f, _platformTexture.Height/2f); //use the body factory to create the physics body _platformBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); _platformBody.IsStatic = true; _platformBody.Position = _position; _platformGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _platformBody, _width, _height); _platformGeom.CollisionGroup = 100; _platformGeom.CollisionGroup = _collisionGroup; _platformGeom.FrictionCoefficient = 1; }
public void TestPointOnLine() { Vector point1 = new Vector(2, 1); Vector point2 = new Vector(-2, 0); Vector point3 = new Vector(5, 0); Vector point4 = new Vector(3, 0); Vector point5 = new Vector(4, 0); Line line = new Line(Vector.Zero, new Vector(4, 0)); Assert.False(Geom.PointOnLine(point1, line)); Assert.False(Geom.PointOnLine(point2, line)); Assert.False(Geom.PointOnLine(point3, line)); Assert.True(Geom.PointOnLine(point4, line)); Assert.True(Geom.PointOnLine(point5, line)); }
void Initialize() { this.Body = BodyFactory.Instance.CreateRectangleBody(this.simulator, this.Size.X, this.Size.Y, 1); this.Body.IsStatic = true; geometry = GeomFactory.Instance.CreateRectangleGeom(this.simulator, this.Body, this.Size.X, this.Size.Y); geometry.RestitutionCoefficient = .1f; geometry.FrictionCoefficient = 1f; geometry.CollisionGridCellSize = .05f; this.brush = new RectangleBrush(); this.brush.Extender.Body = this.Body; this.brush.Size = this.Size; this.brush.rectangle.Fill = new SolidColorBrush(Colors.Transparent); this.brush.rectangle.Stroke = new SolidColorBrush(Colors.Transparent); }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _platformTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, _width, _height, 2, 0, 0, _color, _borderColor); _platformOrigin = new Vector2(_platformTexture.Width / 2f, _platformTexture.Height / 2f); //use the body factory to create the physics body _platformBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); _platformBody.IsStatic = true; _platformBody.Position = _position; _platformGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _platformBody, _width, _height); _platformGeom.CollisionGroup = 100; _platformGeom.CollisionGroup = _collisionGroup; _platformGeom.FrictionCoefficient = 1; }
private void SetGeom(Geom geom, Vertices vertices) { if (_leftGeom == null) { _leftGeom = geom; _leftPolyBrush = new PolygonBrush(vertices, Color.White, Color.Black, 1.5f, 1); _leftPolyBrush.Load(ScreenManager.GraphicsDevice); } else if (_rightGeom == null) { _rightGeom = geom; _rightPolyBrush = new PolygonBrush(vertices, Color.White, Color.Black, 1.5f, 1); _rightPolyBrush.Load(ScreenManager.GraphicsDevice); } }
public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _platformBrush = new RectangleBrush(_width, _height, _color, _borderColor); _platformBrush.Load(graphicsDevice); //use the body factory to create the physics body _platformBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _width, _height, 1); _platformBody.IsStatic = true; _platformBody.Position = _position; _platformGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _platformBody, _width, _height); _platformGeom.CollisionGroup = 100; _platformGeom.CollisionGroup = _collisionGroup; _platformGeom.FrictionCoefficient = 1; }
public void Update(Vector2 pos) { if (xSizePrev != xSize | ySizePrev != ySize) { rBody.Dispose(); rBody = null; rBody = BodyFactory.Instance.CreateRectangleBody(physicsS, xSize, ySize, 1); rBody.IgnoreGravity = true; rGeom = GeomFactory.Instance.CreateRectangleGeom(physicsS, rBody, xSize, ySize); } if (placing) rBody.Position = pos; xSizePrev = xSize; ySizePrev = ySize; }
private Vector2 CalcOrigin(out int[] _firstTriIdxs) { var cent = D.BoundsRect.center; var pIdxArr = new int[D.Points.Length]; var pDistArr = new float[D.Points.Length]; for (var idx = 0; idx < pIdxArr.Length; ++idx) { var dx = Math.Abs(cent.x - D.Points[idx].x); var dy = Math.Abs(cent.y - D.Points[idx].y); pIdxArr[idx] = idx; pDistArr[idx] = dx + dy; } Array.Sort(pIdxArr, (_a, _b) => pDistArr[_a].CompareTo(pDistArr[_b])); _firstTriIdxs = new[] { pIdxArr[0], pIdxArr[1], pIdxArr[2] }; //Find 1st non-linear set of points (valid triangle) var findNonLineIdx = 3; while (Geom.AreColinear(D.Points[_firstTriIdxs[0]], D.Points[_firstTriIdxs[1]], D.Points[_firstTriIdxs[2]], D.MinFloatingPointErr)) { _firstTriIdxs[2] = pIdxArr[findNonLineIdx++]; } //Force Clockwise var v0 = D.Points[_firstTriIdxs[0]]; var v1 = D.Points[_firstTriIdxs[1]]; var v2 = D.Points[_firstTriIdxs[2]]; var vecL = v1 - v0; var vecR = v2 - v0; //Positive Cross Product greater than 180 var crossZ = vecL.x * vecR.y - vecL.y * vecR.x; if (crossZ > 0) { var tempIdx = _firstTriIdxs[1]; _firstTriIdxs[1] = _firstTriIdxs[2]; _firstTriIdxs[2] = tempIdx; } var triPts = new[] { D.Points[_firstTriIdxs[0]], D.Points[_firstTriIdxs[1]], D.Points[_firstTriIdxs[2]] }; var cc = Geom.CentroidOfPoly(triPts); return(cc); }
public static float CheckIntersections(Creature creature, short heading, Point3D moveVector, float distance) { if (distance <= 0f) { return(0f); } WorldPosition targetPosition = moveVector.Clone().Add(creature.Position).ToWorldPosition(); double minDistance = distance; List <Creature> around = Global.VisibleService.FindTargets(creature, creature.Position, distance + 40, TargetingAreaType.All); for (int x = 0; x < around.Count; x++) { if (around[x] == creature) { continue; } short diff = Geom.GetAngleDiff(heading, Geom.GetHeading(creature.Position, around[x].Position)); if (diff > 90) { continue; } double d = Geom.DistanceToLine(around[x].Position, creature.Position, targetPosition); if (d > 40) { continue; } d = creature.Position.DistanceTo(around[x].Position) - 40; if (d <= 0) { return(0f); } if (d < minDistance) { minDistance = d; } } return((float)(minDistance / distance)); }
/// <summary> /// Is the edge legal, or does it need to be flipped? /// </summary> bool LegalEdge(int k, int l, int i, int j) { Debug.Assert(k != highest && k >= 0); var lMagic = l < 0; var iMagic = i < 0; var jMagic = j < 0; Debug.Assert(!(iMagic && jMagic)); if (lMagic) { return(true); } else if (iMagic) { Debug.Assert(!jMagic); var p = verts[l]; var l0 = verts[k]; var l1 = verts[j]; return(Geom.ToTheLeft(p, l0, l1)); } else if (jMagic) { Debug.Assert(!iMagic); var p = verts[l]; var l0 = verts[k]; var l1 = verts[i]; return(!Geom.ToTheLeft(p, l0, l1)); } else { Debug.Assert(k >= 0 && l >= 0 && i >= 0 && j >= 0); var p = verts[l]; var c0 = verts[k]; var c1 = verts[i]; var c2 = verts[j]; Debug.Assert(Geom.ToTheLeft(c2, c0, c1)); Debug.Assert(Geom.ToTheLeft(c2, c1, p)); return(!Geom.InsideCircumcircle(p, c0, c1, c2)); } }
/// <summary> /// TessellateMonoRegion( face ) tessellates a monotone region /// (what else would it do??) The region must consist of a single /// loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this /// case means that any vertical line intersects the interior of the /// region in a single interval. /// /// Tessellation consists of adding interior edges (actually pairs of /// half-edges), to split the region into non-overlapping triangles. /// /// The basic idea is explained in Preparata and Shamos (which I don't /// have handy right now), although their implementation is more /// complicated than this one. The are two edge chains, an upper chain /// and a lower chain. We process all vertices from both chains in order, /// from right to left. /// /// The algorithm ensures that the following invariant holds after each /// vertex is processed: the untessellated region consists of two /// chains, where one chain (say the upper) is a single edge, and /// the other chain is concave. The left vertex of the single edge /// is always to the left of all vertices in the concave chain. /// /// Each step consists of adding the rightmost unprocessed vertex to one /// of the two chains, and forming a fan of triangles from the rightmost /// of two chain endpoints. Determining whether we can add each triangle /// to the fan is a simple orientation test. By making the fan as large /// as possible, we restore the invariant (check it yourself). /// </summary> private void TessellateMonoRegion(MeshUtils.Face face) { // All edges are oriented CCW around the boundary of the region. // First, find the half-edge whose origin vertex is rightmost. // Since the sweep goes from left to right, face->anEdge should // be close to the edge we want. var up = face._anEdge; Debug.Assert(up._Lnext != up && up._Lnext._Lnext != up); while (Geom.VertLeq(up._Dst, up._Org)) up = up._Lprev; while (Geom.VertLeq(up._Org, up._Dst)) up = up._Lnext; var lo = up._Lprev; while (up._Lnext != lo) { if (Geom.VertLeq(up._Dst, lo._Org)) { // up.Dst is on the left. It is safe to form triangles from lo.Org. // The EdgeGoesLeft test guarantees progress even when some triangles // are CW, given that the upper and lower chains are truly monotone. while (lo._Lnext != up && (Geom.EdgeGoesLeft(lo._Lnext) || Geom.EdgeSign(lo._Org, lo._Dst, lo._Lnext._Dst) <= 0.0f)) { lo = _mesh.Connect(lo._Lnext, lo)._Sym; } lo = lo._Lprev; } else { // lo.Org is on the left. We can make CCW triangles from up.Dst. while (lo._Lnext != up && (Geom.EdgeGoesRight(up._Lprev) || Geom.EdgeSign(up._Dst, up._Org, up._Lprev._Org) >= 0.0f)) { up = _mesh.Connect(up, up._Lprev)._Sym; } up = up._Lnext; } } // Now lo.Org == up.Dst == the leftmost vertex. The remaining region // can be tessellated in a fan from this leftmost vertex. Debug.Assert(lo._Lnext != up); while (lo._Lnext._Lnext != up) { lo = _mesh.Connect(lo._Lnext, lo)._Sym; } }
public FarseerPhysicsComponent(Body body, Geom geom) { _body = body; _geom = geom; _geom.Tag = this; _geom.FrictionCoefficient = 0.7f; _body.IgnoreGravity = true; _geom.OnCollision += new CollisionEventHandler((geom1, geom2, contactList) => { CollidedWithWorld(); return true; }); }
protected override void Update(int t) { P = _p + V * t; if (t % 3 == 0) { _.World.Spawn(new Blast ( P + P.Rotated90CW().Normalized *_.Random.Float(-6, 6), _.Random.Float(2, 9), 15)); } if (t > 30 && !Geom.CircleOverBox(new Circle(P, 2), World.Box)) { Despawn(); } }
public void jump() { if (Environment.TickCount - timeOfLastJump > 750 && !isDead) { timeOfLastJump = Environment.TickCount; Geom touching = isTouchingGeom(true); if (touching != null) { float jumpForce = Weight * (450 + 6 * getStat(StatType.Agility)); //Vector2 pos = body.Position; //Feature nearest = touching.GetNearestFeature(ref pos, 1); Vector2 featureNormal = new Vector2(0, 1);//nearest.Normal; body.ApplyForce(jumpForce * featureNormal); } } }
protected override void Update(int t) { if (t <= _t) { P = _p0 + Mathf.Sqrt(t) * _v1 * V; } else { P = _p0 + Mathf.Sqrt(_t) * _v1 * V + (t - _t) * _v2 * V; } if (t > 30 && !Geom.CircleOverBox(new Circle(P, R + 2), World.Box)) { Despawn(); } }
public Geom CreatePolygonGeom(Body body, Vertices vertices, Vector2 offset, float rotationOffset, float collisionGridCellSize) { //adjust the verts to be relative to 0,0 Vector2 centroid = vertices.GetCentroid(); vertices.Translate(-centroid); if (collisionGridCellSize <= 0) { collisionGridCellSize = CalculateGridCellSizeFromAABB(vertices); } Geom geometry = new Geom(body, vertices, offset, rotationOffset, collisionGridCellSize); return(geometry); }
public override bool Over(CircleHitbox other) { bool result = Geom.Overlap( new Circle(Center1, Radius), new Circle(Center2, Radius), other.Circle ); /* if (result) { * Console.WriteLine (new Circle (Center1, Radius)); * Console.WriteLine (new Circle (Center2, Radius)); * Console.WriteLine (other.Circle); * Console.WriteLine (); * }*/ return(result); }
public Robot(RobotPHX robotPHX, string name) { this.robotPHX = robotPHX; servoMotors[(int)ServoType.FINGER] = robotPHX.QueryDeviceServoMotor(name + "_doigt/a1/servo"); servoMotors[(int)ServoType.ARM] = robotPHX.QueryDeviceServoMotor(name + "_bras/a1/servo"); servoMotors[(int)ServoType.SHOULDER] = robotPHX.QueryDeviceServoMotor(name + "_epaule/a1/servo"); Debug.Assert(servoMotors[0] != null && servoMotors[1] != null && servoMotors[2] != null); core = robotPHX.QueryGeom("basPlatine"); Debug.Assert(core != null); gyro = robotPHX.QueryDeviceAccelGyro("basPlatine/gyro"); Debug.Assert(gyro != null); }
public bool isInRange(Being target) { Vector2 dimensions = new Vector2((currAnimation.aoe ? 2 : 1) * getRange(), controller.getFrameDimensions(getCurrentFrame()).Y + getStat(StatType.Range)); Vector2 positionOffset = currAnimation.aoe ? Vector2.Zero : new Vector2(getFacingMultiplier() * controller.getFrameDimensions(getCurrentFrame()).X / 2, 0); Geom collisionGeom = GeomFactory.Instance.CreateRectangleGeom(Game.instance.physicsSimulator, body, dimensions.X, dimensions.Y, positionOffset, 0); collisionGeom.CollisionCategories = geom.CollisionCategories; collisionGeom.CollidesWith = geom.CollidesWith; bool inRange = target.geom.Collide(collisionGeom); Game.instance.physicsSimulator.Remove(collisionGeom); return(inRange); }
public void UseSkill(Npc npc, Skill skill) { if (npc.Target == null) { return; } npc.Position.Heading = Geom.GetHeading(npc.Position, npc.Target.Position); ProcessSkill(npc, new UseSkillArgs { IsTargetAttack = false, SkillId = skill.Id + 0x40000000 + (npc.NpcTemplate.HuntingZoneId << 16), StartPosition = npc.Position.Clone(), }, skill); }
public void MergeConvexFaces(IPool pool, int maxVertsPerFace) { for (var f = _fHead._next; f != _fHead; f = f._next) { // Skip faces which are outside the result if (!f._inside) { continue; } var eCur = f._anEdge; var vStart = eCur._Org; while (true) { var eNext = eCur._Lnext; var eSym = eCur._Sym; if (eSym != null && eSym._Lface != null && eSym._Lface._inside) { // Try to merge the neighbour faces if the resulting polygons // does not exceed maximum number of vertices. int curNv = f.VertsCount; int symNv = eSym._Lface.VertsCount; if ((curNv + symNv - 2) <= maxVertsPerFace) { // Merge if the resulting poly is convex. if (Geom.VertCCW(eCur._Lprev._Org, eCur._Org, eSym._Lnext._Lnext._Org) && Geom.VertCCW(eSym._Lprev._Org, eSym._Org, eCur._Lnext._Lnext._Org)) { eNext = eSym._Lnext; Delete(pool, eSym); eCur = null; } } } if (eCur != null && eCur._Lnext._Org == vStart) { break; } // Continue to next edge. eCur = eNext; } } }
public void TestMethod1() { var pos = new Vector3(-1.07934f, 12.44121f, -0.9962342f); var normal = new Vector3(-0.4765971f, 0.3736753f, -0.7957524f); var to = new Vector3(-1.138259f, 12.0929f, -1.073817f); var y = pos - to; y.Normalize(); Console.WriteLine("y=" + y.ToString()); var z = -normal; z.Normalize(); Console.WriteLine("z=" + z.ToString()); Console.WriteLine("y*z=" + Vector3.Dot(y, z).ToString()); var x = Vector3.Cross(z, y); z.Normalize(); Console.WriteLine("x=" + x.ToString()); y = Vector3.Cross(x, z); y.Normalize(); Console.WriteLine("y=" + y.ToString()); Console.WriteLine("y*z=" + Vector3.Dot(y, z).ToString()); Vector3 r; r = Geom.ToEuler_ZYX(x, y, z); r *= 180f / (float)Math.PI; Console.WriteLine("r=" + r.ToString()); r = Geom.ToEuler_YXZ(x, y, z); r *= 180f / (float)Math.PI; Console.WriteLine("r=" + r.ToString()); r = Geom.ToEuler_XYZ(x, y, z); r *= 180f / (float)Math.PI; Console.WriteLine("r=" + r.ToString()); }
/// <summary> /// Calculates positions that are parallel to a line. /// </summary> /// <param name="line">The reference line.</param> /// <param name="offpoint">The point the parallel must pass through.</param> /// <param name="sres">The position of the start of the parallel.</param> /// <param name="eres">The position of the end of the parallel.</param> /// <returns>True if positions calculated ok</returns> internal static bool Calculate(LineFeature refline, PointFeature offpoint, out IPosition sres, out IPosition eres) { // No result positions so far. sres = eres = null; // Get the ends of the reference line. IPosition spos = refline.StartPoint; IPosition epos = refline.EndPoint; // If the reference line is a circular arc ArcFeature arc = refline.GetArcBase(); if (arc != null) { // Get the curve info Circle circle = arc.Circle; double radius = circle.Radius; IPosition centre = circle.Center; bool iscw = arc.IsClockwise; // Get the (planar) distance from the centre of the // circle to the offset point. double offdist = Geom.Distance(offpoint, centre); // Project the BC/EC radially. double sbear = Geom.BearingInRadians(centre, spos); sres = Geom.Polar(centre, sbear, offdist); double ebear = Geom.BearingInRadians(centre, epos); eres = Geom.Polar(centre, ebear, offdist); } else { double bearing = Geom.BearingInRadians(spos, epos); // Get the perpendicular distance (signed) from the offset point // to the reference line. double offdist = Geom.SignedDistance(spos.X, spos.Y, bearing, offpoint.X, offpoint.Y); // Calculate the parallel points. bearing += Constants.PIDIV2; sres = Geom.Polar(spos, bearing, offdist); eres = Geom.Polar(epos, bearing, offdist); } return(true); }
internal void Draw() // was Paint { // Nothing to do if parallel points undefined. if (m_South == null || m_North == null) { return; } Debug.Assert(m_Line != null); ISpatialDisplay draw = m_Cmd.ActiveDisplay; IDrawStyle solidStyle = EditingController.Current.Style(Color.Magenta); IDrawStyle dottedStyle = new DottedStyle(); ArcFeature arc = m_Line.GetArcBase(); if (arc != null) { // The parallel portion is solid, while the remaining portion of the circle is dotted. CircularArcGeometry cg = new CircularArcGeometry(arc.Circle.Center, m_South, m_North, arc.IsClockwise); solidStyle.Render(draw, cg); cg.IsClockwise = !cg.IsClockwise; dottedStyle.Render(draw, cg); } else { // What's the bearing from the start to the end of the parallel? double bearing = Geom.BearingInRadians(m_South, m_North); // What's the max length of a diagonal crossing the entire screen? double maxdiag = m_Cmd.MaxDiagonal; // Project to a point below the southern end of the parallel, as // well as a point above the northern end. IPosition below = Geom.Polar(m_South, bearing + Constants.PI, maxdiag); IPosition above = Geom.Polar(m_North, bearing, maxdiag); LineSegmentGeometry.Render(below, m_South, draw, dottedStyle); LineSegmentGeometry.Render(m_South, m_North, draw, solidStyle); LineSegmentGeometry.Render(m_North, above, draw, dottedStyle); // If we have an offset point, draw it in green. if (m_Point != null) { m_Point.Draw(draw, Color.Green); } } }
public void LoadFloor() { //load texture that will visually represent the physics body _floorTexture = DrawingHelper.CreateRectangleTexture(ScreenManager.GraphicsDevice, ScreenManager.ScreenWidth, 100, Color.White, Color.Black); _floorOrigin = new Vector2(_floorTexture.Width / 2f, _floorTexture.Height / 2f); //use the body factory to create the physics body _floorBody = BodyFactory.Instance.CreateRectangleBody(PhysicsSimulator, ScreenManager.ScreenWidth, 100, 1); _floorBody.IsStatic = true; _floorGeom = GeomFactory.Instance.CreateRectangleGeom(PhysicsSimulator, _floorBody, ScreenManager.ScreenWidth, 100); _floorGeom.RestitutionCoefficient = .2f; _floorGeom.FrictionCoefficient = .2f; _floorBody.Position = new Vector2(ScreenManager.ScreenCenter.X, ScreenManager.ScreenHeight - 50); }
/// <summary> /// Returns the equivalent distance on the mapping plane. /// </summary> /// <param name="from">The position the distance is measured from.</param> /// <param name="bearing">The bearing for the distance, in radians.</param> /// <param name="sys">The mapping system</param> /// <returns>The distance on the mapping plane.</returns> internal double GetPlanarMetric(IPosition from, double bearing, ISpatialSystem sys) { // Return zero if this distance is undefined. if (!this.IsDefined) { return(0.0); } // Calculate approximation for the terminal position (treating // this distance as a planar distance). IPosition to = Geom.Polar(from, bearing, m_ObservedMetric); // Use the approximate location to determine line scale factor double sfac = sys.GetLineScaleFactor(from, to); return(m_ObservedMetric * sfac); }
public bool OnCollisionFunction(Geom geom1, Geom geom2, ContactList contactList) { GeomDC g1 = geom1 as GeomDC; GeomDC g2 = geom2 as GeomDC; if (g1 == null || g2 == null) { return(true); } ICollides col1 = g1.thisObject as ICollides; if (col1 == null) { return(true); } return(col1.OnCollision(g2.thisObject)); }
/// <summary> /// Uses the currently displayed information to try to construct a /// circle representing the distance. /// </summary> /// <returns>The constructed circle (null if a circle cannot be created /// based on the information that's currently displayed)</returns> Circle GetCurrentCircle() { Circle result = null; // Undefine the address of the relevant distance observation. m_ObservedDistance = null; if (m_From == null) { return(null); } if (m_DistancePoint != null || (m_Distance != null && m_Distance.Meters > Constants.TINY)) { double radius; // If we have an offset point, get the radius. if (m_DistancePoint != null) { radius = Geom.Distance(m_From, m_DistancePoint); } else { radius = m_Distance.Meters; } // Construct the circle result = new Circle(m_From, radius); // Create the appropriate distance observation (this is what // gets picked up when we actually go to work out the // intersection on the last page of the intersect dialog. if (m_DistancePoint != null) { m_OffsetPoint = new OffsetPoint(m_DistancePoint); m_ObservedDistance = m_OffsetPoint; } else { m_ObservedDistance = m_Distance; } } return(result); }
/// <summary> /// Creates the rectangle geom. /// </summary> /// <param name="body">The body.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="positionOffset">The offset.</param> /// <param name="rotationOffset">The rotation offset.</param> /// <param name="collisionGridSize">Size of the collision grid. - not used with SAT</param> /// <returns></returns> public Geom CreateRectangleGeom(Body body, float width, float height, Vector2 positionOffset, float rotationOffset, float collisionGridSize) { if (width <= 0) { throw new ArgumentOutOfRangeException("width", "Width must be more than 0"); } if (height <= 0) { throw new ArgumentOutOfRangeException("height", "Height must be more than 0"); } Vertices vertices = Vertices.CreateRectangle(width, height); Geom geometry = new Geom(body, vertices, positionOffset, rotationOffset, collisionGridSize); return(geometry); }
/// <summary> /// Creates the ellipse geom. /// </summary> /// <param name="body">The body.</param> /// <param name="xRadius">The x radius.</param> /// <param name="yRadius">The y radius.</param> /// <param name="numberOfEdges">The number of edges.</param> /// <param name="offset">The offset.</param> /// <param name="rotationOffset">The rotation offset.</param> /// <param name="collisionGridSize">Size of the collision grid. - not used with SAT</param> /// <returns></returns> public Geom CreateEllipseGeom(Body body, float xRadius, float yRadius, int numberOfEdges, Vector2 offset, float rotationOffset, float collisionGridSize) { if (xRadius <= 0) { throw new ArgumentOutOfRangeException("xRadius", "xRadius must be more than 0"); } if (yRadius <= 0) { throw new ArgumentOutOfRangeException("yRadius", "yRadius must be more than 0"); } Vertices vertices = Vertices.CreateEllipse(xRadius, yRadius, numberOfEdges); Geom geometry = new Geom(body, vertices, offset, rotationOffset, collisionGridSize); return(geometry); }