//-------------------------------------------------------------- public void modify() { if (mInputTriangleBuffer == null) { OGRE_EXCEPT("Exception::ERR_INVALID_STATE", "Input triangle buffer must be set", "__FUNCTION__"); } ; //for (List<TriangleBuffer.Vertex>.Enumerator it = mInputTriangleBuffer.getVertices().begin(); it != mInputTriangleBuffer.getVertices().end(); ++it) foreach (var it in mInputTriangleBuffer.getVertices()) { Vector3 input = it.mPosition.NormalisedCopy; Vector3 v = new Vector3(); Radian r = new Radian(); if (input.y > 0) { Vector3.UNIT_Y.GetRotationTo(input).ToAngleAxis(out r, out v); } else { Vector3.NEGATIVE_UNIT_Y.GetRotationTo(input).ToAngleAxis(out r, out v); } Vector2 v2 = new Vector2(input.x, input.z); v2.Normalise(); Vector2 uv = new Vector2(0.5f, 0.5f) + 0.5f * (r / Math.HALF_PI).ValueRadians * v2; if (input.y > 0) { it.mUV = Utils.reframe(mTextureRectangleTop, uv); } else { it.mUV = Utils.reframe(mTextureRectangleBottom, uv); } } }
public override void OnCollision(GameObject _otherObj) { Console.WriteLine("Colliding"); //--------------------------------------------------------------------------------- // Circle Collision // Calculate reflection // Push objects apart // Change Direction //--------------------------------------------------------------------------------- m_LocalTransform.m7 = m_PreviousPos.x; m_LocalTransform.m8 = m_PreviousPos.y; Vector2 normal = GetGlobalPosition() - _otherObj.GetGlobalPosition(); normal.Normalise(); Vector2 reflection = -1.0f * m_Velocity; m_Velocity = reflection; UpdateTransforms(); base.OnCollision(_otherObj); DrawText("Reflect X : " + reflection.x.ToString(), 50, 100, 16, RLColor.RED); DrawText("Reflect Y : " + reflection.y.ToString(), 50, 130, 16, RLColor.RED); }
/// <summary> /// /// </summary> /// <param name="ret"></param> /// <returns></returns> public static float Normalize(Vector2 ret) { //float fLength = Utility.Sqrt(ret.x * ret.x + ret.y * ret.y); //// Will also work for zero-sized vectors, but will change nothing //if (fLength > 1e-08) //{ // float fInvLength = 1.0f / fLength; // ret.x *= fInvLength; // ret.y *= fInvLength; //} //return fLength; return(ret.Normalise()); }
private static void NudgeTowers(MapSegment segment) { List <int> [] groups = Utils.GroupTowers(segment, Constants.nudging_distance_threshold); Console.WriteLine(segment.name); foreach (List <int> group in groups.Where(x => x.Count >= 2)) { Tower [] towers = group .Select(x => segment.towers [x]) .ToArray(); Vector2 centre = Tower.Centre(towers); if (towers.Length == 2) { if (!towers [0].map_position.Equals(towers [1].map_position)) { foreach (Tower tower in towers) { tower.map_position = centre + (tower.map_position - centre).normalised * (Constants.nudged_distance / 2); } } else { Vector2 direction = Vector2.one; direction.Normalise(); towers [0].map_position = centre + direction * (Constants.nudged_distance / 2); towers [1].map_position = centre - direction * (Constants.nudged_distance / 2); } } else { Console.WriteLine("!!!!!!! MORE THAN TWO TOWERS NOT IMPLEMENTED !!!!!"); } } }
public override void Update(float _deltatime) { m_MousePosition = GetMousePosition().ToVector2(); currentGlobalPos = GetGlobalPosition(); targetDirection = m_MousePosition - currentGlobalPos; targetDirection.Normalise(); float rotation = 0.0f; if (IsKeyDown(KeyboardKey.KEY_RIGHT)) { rotation += m_TurretTurnSpeed * _deltatime; } if (IsKeyDown(KeyboardKey.KEY_LEFT)) { rotation -= m_TurretTurnSpeed * _deltatime; } if (IsKeyPressed(KeyboardKey.KEY_SPACE)) { FireGun(); CollisionManager.AddObject(m_Bullet); } Matrix3 rotationMatrix = new Matrix3(); rotationMatrix.SetRotateZ(rotation); m_LocalTransform = m_LocalTransform * rotationMatrix; m_Bullet.Update(_deltatime); m_Bullet.UpdateTransforms(); m_Bullet.SetRotation(rotation); base.Update(_deltatime); }
public void ResolveCollision(CollisionComp colliderA, CollisionComp colliderB) { RidgedBodyComp objectA = colliderA.gameObject.getComponent <RidgedBodyComp>() as RidgedBodyComp; RidgedBodyComp objectB = colliderB.gameObject.getComponent <RidgedBodyComp>() as RidgedBodyComp; Vector2 relVelocity = objectB.GetVelocity() - objectA.GetVelocity(); Vector2 normal = relVelocity.Normalise(); float velByNormal = relVelocity.DotProduct(normal); //do not resolve if moving away from each other if (velByNormal < 0) { return; } Vector2 tempnorm;//= (objectA.gameObject.GetTransform().Position - objectB.gameObject.GetTransform().Position).Normalise(); //Console.WriteLine("X: " + tempnorm.X + " Y: " + tempnorm.Y); minPosA = (colliderA as BoundingBoxComp).min + colliderA.gameObject.GetTransform().Position; maxPosA = (colliderA as BoundingBoxComp).max + colliderA.gameObject.GetTransform().Position; minPosB = (colliderB as BoundingBoxComp).min + colliderB.gameObject.GetTransform().Position; maxPosB = (colliderB as BoundingBoxComp).max + colliderB.gameObject.GetTransform().Position; xAxisleft = minPosA.X - maxPosB.X; xAxisRight = maxPosA.X - minPosB.X; yAxisUp = minPosA.Y - maxPosB.Y; yAxisDown = maxPosA.Y - minPosB.Y; maxY = Math.Max(yAxisDown, yAxisUp); maxX = Math.Max(xAxisleft, xAxisRight); tempnorm = new Vector2(1, 1); if (maxY > maxX) { tempnorm.X = -1; } else { tempnorm.Y = -1; } // if (tempnorm.Y !=1) // if (tempnorm.Y < 0 || tempnorm.Y > 0) // { // tempnorm.Y = -1; // } // if(tempnorm.X != 1) //if (tempnorm.X < 0 || tempnorm.X > 0) // { // tempnorm.X = -1; // } objectA.velocity.X = objectA.velocity.X * tempnorm.X; objectA.velocity.Y = objectA.velocity.Y * tempnorm.Y; /* float epsilon = Math.Min(objectA.restitution, objectB.restitution); * * float impulseScalar = -(1 + epsilon) * velByNormal; * * impulseScalar /= objectA.GetInvMass() + objectB.GetInvMass(); * * Vector2 impulse = impulseScalar * normal; * * float mass_sum = objectA.GetMass() + objectB.GetMass(); * float ratio = objectA.GetMass() / mass_sum; * objectA.RemoveForce(ratio * impulse); * * ratio = objectB.GetMass() / mass_sum; * objectB.AddForce(ratio * impulse);*/ }
public static void GetCollisionInformation(CollisionPair pair, out float penetration, out Vector2 collisionNormal, out CollisionPoints collisionPoints) { //Collision Detection using SAT //only works with rectangles, but because of that it is way more efficient! (or it would be if rotation wasn't involved) Collider aCol = pair.a.GetCollider(); Collider bCol = pair.b.GetCollider(); Vector2 aHalfWidth = aCol.GetHalfWidthVector(); Vector2 aHalfHeight = aCol.GetHalfHeightVector(); Vector2 aCentre = aCol.GetCentrePoint(); Vector2 bHalfWidth = bCol.GetHalfWidthVector(); Vector2 bHalfHeight = bCol.GetHalfHeightVector(); Vector2 bCentre = bCol.GetCentrePoint(); Matrix3 aTransform = pair.a.GetGlobalTransform(); Matrix3 bTransform = pair.b.GetGlobalTransform(); Vector2 normal = new Vector2(float.PositiveInfinity, float.PositiveInfinity); float pValue = float.PositiveInfinity; float pV; float a; float b; penetration = 0; collisionNormal = Vector2.zero; collisionPoints = null; //https://www.metanetsoftware.com/technique/tutorialA.html //I used this to get how to find penetration and stuff with rectangles //it doesn't expressly explain how to do it with non axis aligned //rectangles that are stored like mine are, but it explains all the pieces //A X Axis /////////////////////////////////////////////////////////////////// if (!doPA(aTransform.GetRightVector())) { return; } //A Y Axis ////////////////////////////////////////////////////////////////// if (!doPA(aTransform.GetUpVector())) { return; } //B X Axis ////////////////////////////////////////////////////////////////// if (!doPB(bTransform.GetRightVector())) { return; } //B Y Axis ////////////////////////////////////////////////////////////////// if (!doPB(bTransform.GetUpVector())) { return; } ////////////////////////////////////////////////////////////////// collisionNormal = normal; penetration = pValue; //The rest is to find collision points //reference: //http://www.dyn4j.org/2011/11/contact-points-using-clipping/ // ^ all other sources I could find on the internet are based off this //this is from the guy that made the box2d engine //this also explains very well how clipping is used to find collision points //https://research.ncl.ac.uk/game/mastersdegree/gametechnologies/previousinformation/physics5collisionmanifolds/2017%20Tutorial%205%20-%20Collision%20Manifolds.pdf if (pair.a.GetInverseInertia() == 0 && pair.b.GetInverseInertia() == 0) { //no need to calculate collisionPoints = new CollisionPoints(new List <Vector2>() { Vector2.one }); return; } Vector2[] mainPoints; Vector2[] secondaryPoints; mainPoints = bCol.GetGlobalPoints(); secondaryPoints = aCol.GetGlobalPoints(); Edge e1 = GetMostPerpendicular(mainPoints, -1 * normal); Edge e2 = GetMostPerpendicular(secondaryPoints, normal); Edge reference; Edge incident; if (Math.Abs((e1.v1 - e1.v2).Dot(normal)) <= Math.Abs((e2.v1 - e2.v2).Dot(normal))) { reference = e1; incident = e2; } else { reference = e2; incident = e1; } Vector2 refV = (reference.v2 - reference.v1).Normalised(); float o1 = refV.Dot(reference.v1); CollisionPoints cP = Trim(incident.v1, incident.v2, refV, o1); if (cP.points.Count < 2) { collisionPoints = null; return; } float o2 = refV.Dot(reference.v2); cP = Trim(cP.points[0], cP.points[1], -1 * refV, -o2); if (cP.points.Count < 2) { collisionPoints = null; return; } Vector2 refNorm = Vector2.ZCross(refV, -1); float max = refNorm.Dot(reference.max); //I don't actually use these depths at any point but too late to remove it now (aka I am too lasy right now) cP.depths.Add(refNorm.Dot(cP.points[0]) - max); cP.depths.Add(refNorm.Dot(cP.points[1]) - max); if (cP.depths[0] < 0) { cP.depths.RemoveAt(0); cP.points.RemoveAt(0); } if (cP.depths[cP.depths.Count - 1] < 0) { cP.depths.RemoveAt(cP.depths.Count - 1); cP.points.RemoveAt(cP.points.Count - 1); } collisionPoints = cP; return; #region Local Functions CollisionPoints Trim(Vector2 point1, Vector2 point2, Vector2 norm, float limit) { List <Vector2> clippedPoints = new List <Vector2>(2); float d1 = norm.Dot(point1) - limit; float d2 = norm.Dot(point2) - limit; if (d1 >= 0) { clippedPoints.Add(point1); } if (d2 >= 0) { clippedPoints.Add(point2); } if (d1 * d2 < 0) { Vector2 e = point2 - point1; float u = d1 / (d1 - d2); e *= u; e += point1; clippedPoints.Add(e); } return(new CollisionPoints(clippedPoints)); } Edge GetMostPerpendicular(Vector2[] points, Vector2 n) { float furthestVertex = float.NegativeInfinity; int index = 0; for (int i = 0; i < 4; i++) { float projectedDist = n.Dot(points[i]); if (projectedDist > furthestVertex) { furthestVertex = projectedDist; index = i; } } Vector2 v = points[index]; Vector2 v1 = points[(index + 1) % 4]; //forward one Vector2 v0 = points[(index + 3) % 4]; //back one Vector2 l = v - v1; Vector2 r = v - v0; l.Normalise(); r.Normalise(); if (r.Dot(n) <= l.Dot(n)) { return(new Edge(v, v0, v)); } else { return(new Edge(v, v, v1)); } } bool doPA(Vector2 ax) { float aW = ax.Dot(aHalfWidth); float aH = ax.Dot(aHalfHeight); //aW + aH will equal half the size of the box on a given axis float bH = ax.Dot(bHalfHeight * Math.Sign(bHalfHeight.Dot(ax))); float bW = ax.Dot(bHalfWidth * Math.Sign(bHalfWidth.Dot(ax))); a = ax.Dot(aCentre); b = ax.Dot(bCentre); pV = (((aW + aH) + (bH + bW)) - Math.Abs(a - b)); //this is basically exactly the same as circle1radius + circle2radius > distancebetweencentrepoints if (pV > 0) { if (pV < pValue) { pValue = pV; normal = ax * Math.Sign(b - a); } return(true); } else { return(false); } } bool doPB(Vector2 ax) { float aW = ax.Dot(aHalfWidth * Math.Sign(aHalfWidth.Dot(ax))); float aH = ax.Dot(aHalfHeight * Math.Sign(aHalfHeight.Dot(ax))); float bH = ax.Dot(bHalfHeight); float bW = ax.Dot(bHalfWidth); a = ax.Dot(aCentre); b = ax.Dot(bCentre); pV = (((aW + aH) + (bH + bW)) - Math.Abs(a - b)); if (pV > 0) { if (pV < Math.Abs(pValue)) { pValue = pV; normal = ax * Math.Sign(b - a); } return(true); } else { return(false); } } #endregion }
static void Main(string[] args) { Vector2 <float> nvec = new Vector2 <float>(5.2f, 5.0f); Vector2 <float> nvec1 = new Vector2 <float>(5.0f, 5.2f); Vector2 <float> Sum = nvec + nvec1; Vector2 <float> Difference = nvec - nvec1; Vector2 <float> Product = nvec * nvec1; Vector2 <float> Quotient = nvec / nvec1; Vector2 <float> Modulus = nvec % nvec1; float Magnitude = Vector2 <float> .Mag(nvec1); Vector2 <float> Normalise = Vector2 <float> .Normalise(nvec1); float Dot = Vector2 <float> .Dot(nvec, nvec1); Console.WriteLine("Vector 2 Math: "); Console.WriteLine("Sum is: ({0})", Sum); Console.WriteLine("Difference is: ({0})", Difference); Console.WriteLine("Product is: ({0})", Product); Console.WriteLine("Quotient is: ({0})", Quotient); Console.WriteLine("Modulus is: ({0})", Modulus); Console.WriteLine("Magnitude is: ({0})", Magnitude); Console.WriteLine("Normalised is: ({0})", Normalise); Console.WriteLine("Dot Product is: ({0})", Dot); Vector3 <int> nvec2 = new Vector3 <int>(1, 2, 3); Vector3 <int> nvec3 = new Vector3 <int>(1, 2, 3); int mag = Vector3 <int> .Mag(nvec2); Vector3 <int> Sum2 = nvec2 + nvec3; Vector3 <int> Difference2 = nvec2 - nvec3; Vector3 <int> Product2 = nvec2 * nvec3; Vector3 <int> Quotient2 = nvec2 / nvec3; Vector3 <int> Modulus2 = nvec2 % nvec3; int Magnitude2 = Vector3 <int> .Mag(nvec2); Vector3 <int> Normalise2 = Vector3 <int> .Normalise(nvec2); int Dot2 = Vector3 <int> .Dot(nvec2, nvec3); Vector3 <int> Cross = Vector3 <int> .Cross(nvec2, nvec3); Console.WriteLine("\nVector 3 Math: "); Console.WriteLine("Sum is: ({0})", Sum2); Console.WriteLine("Difference is: ({0})", Difference2); Console.WriteLine("Product is: ({0})", Product2); Console.WriteLine("Quotient is: ({0})", Quotient2); Console.WriteLine("Modulus is: ({0})", Modulus2); Console.WriteLine("Magnitude is: ({0})", Magnitude2); Console.WriteLine("Normalised is: ({0})", Normalise2); Console.WriteLine("Dot Product is: ({0})", Dot2); Console.WriteLine("Cross Product is: ({0})", Cross); Color <double> white = new Color <double>(1.0f, 1.0f, 1.0f, 1.0f); Color <double> black = new Color <double>(1.0f, 1.0f, 1.0f, 1.0f); Color <double> Sum3 = white + black; Color <double> Difference3 = white - black; Color <double> Product3 = white * black; Color <double> Quotient3 = white / black; Color <double> Modulus3 = white % black; double Magnitude3 = Color <double> .Mag(white); Color <double> Normalise3 = Color <double> .Normalise(white); double Dot3 = Color <double> .Dot(white, black); Console.WriteLine("\nColor Math: "); Console.WriteLine("Sum is: ({0})", Sum3); Console.WriteLine("Difference is: ({0})", Difference3); Console.WriteLine("Product is: ({0})", Product3); Console.WriteLine("Quotient is: ({0})", Quotient3); Console.WriteLine("Modulus is: ({0})", Modulus3); Console.WriteLine("Magnitude is: ({0})", Magnitude3); Console.WriteLine("Normalised is: ({0})", Normalise3); Console.WriteLine("Dot Product is: ({0})", Dot3); //Create An Array For Storing The Input Variables From The User char[] cHex = { '#', '1', '1', '1', '1', '1', '1' }; Color <int> hecdec = Color <int> .HexConv(cHex); Console.WriteLine("RGBA Values Are: ({0})\n", hecdec); Console.ReadLine(); }
public void Vector2IsNormaliseTest() { var a = new Vector2(3.0f, 4.0f); var expectedResult = true; a.Normalise(); var r = a.IsNormalised; Assert.Equal<bool>(expectedResult, r); }
public void Vector2NormaliseTest() { var a = new Vector2(3.0f, 4.0f); var expectedResult = new Vector2(0.6f, 0.8f); a.Normalise(); Assert.Equal<Vector2>(expectedResult, a); }