public static Vector2[] CircleCircleIntersection( this Vector2 center1, Vector2 center2, float radius1, float radius2) { var d = center1.Distance(center2); if (d > radius1 + radius2 || d <= Math.Abs(radius1 - radius2)) { return(new Vector2[] { }); } var a = (radius1 * radius1 - radius2 * radius2 + d * d) / (2 * d); var h = (float)Math.Sqrt(radius1 * radius1 - a * a); var direction = Vector2Extensions.Normalized((center2 - center1)); var pa = center1 + a * direction; var s1 = pa + h * direction.Perpendicular(); var s2 = pa - h * direction.Perpendicular(); return(new[] { s1, s2 }); }
protected override void Blit(Action <TexturedVertex2D> vertexAction) { var time = currentTime - startTime; foreach (var p in parts) { Vector2 pos = p.PositionAtTime(time); float alpha = p.AlphaAtTime(time); var rect = new RectangleF( pos.X * sourceSize.X - Texture.DisplayWidth / 2, pos.Y * sourceSize.Y - Texture.DisplayHeight / 2, Texture.DisplayWidth, Texture.DisplayHeight); // convert to screen space. var quad = new Quad( Vector2Extensions.Transform(rect.TopLeft, DrawInfo.Matrix), Vector2Extensions.Transform(rect.TopRight, DrawInfo.Matrix), Vector2Extensions.Transform(rect.BottomLeft, DrawInfo.Matrix), Vector2Extensions.Transform(rect.BottomRight, DrawInfo.Matrix) ); DrawQuad(Texture, quad, DrawColourInfo.Colour.MultiplyAlpha(alpha), null, vertexAction, new Vector2(InflationAmount.X / DrawRectangle.Width, InflationAmount.Y / DrawRectangle.Height), null, TextureCoords); } }
private IEnumerable <Vector2> getPolygonAngles(float offset, int sides, int projectiles) { var angles = new List <Vector2>(); var points = getPolygonPoints(sides).ToArray(); var sideLen = Vector2Extensions.Distance(points[0], points[1]); var space = sideLen / (int)(projectiles / sides); for (var i = 0; i < points.Length; i++) { var point = points[i]; var nextPoint = points[(i + 1) % points.Length]; var angle = Math.Atan2(nextPoint.Y - point.Y, nextPoint.X - point.X); var xT = Math.Cos(angle) * space; var yT = Math.Sin(angle) * space; for (var j = 0; j < projectiles / sides; j++) { var x = point.X + xT * j; var y = point.Y + yT * j; var xRot = x * Math.Cos(offset) - y * Math.Sin(offset); var yRot = x * Math.Sin(offset) + y * Math.Cos(offset); angles.Add(new Vector2((float)xRot, (float)yRot)); } } return(angles); }
protected override bool OnMouseMove(InputState state) { if (dragging) { Debug.Assert(state.Mouse.PositionMouseDown != null); // don't start rotating until we're moved a minimum distance away from the mouse down location, // else it can have an annoying effect. startRotation |= Vector2Extensions.Distance(state.Mouse.Position, state.Mouse.PositionMouseDown.Value) > 30; if (startRotation) { Vector2 offset = state.Mouse.Position - state.Mouse.PositionMouseDown.Value; float degrees = (float)MathHelper.RadiansToDegrees(Math.Atan2(-offset.X, offset.Y)) + 24.3f; // Always rotate in the direction of least distance float diff = (degrees - ActiveCursor.Rotation) % 360; if (diff < -180) { diff += 360; } if (diff > 180) { diff -= 360; } degrees = ActiveCursor.Rotation + diff; ActiveCursor.RotateTo(degrees, 600, Easing.OutQuint); } } return(base.OnMouseMove(state)); }
public void Add(DrawableHitObject fruit, Vector2 absolutePosition) { fruit.RelativePositionAxes = Axes.None; fruit.Position = new Vector2(ToLocalSpace(absolutePosition).X - DrawSize.X / 2, 0); fruit.Anchor = Anchor.TopCentre; fruit.Origin = Anchor.BottomCentre; fruit.Scale *= 0.7f; fruit.LifetimeEnd = double.MaxValue; float distance = fruit.DrawSize.X / 2 * fruit.Scale.X; while (caughtFruit.Any(f => f.LifetimeEnd == double.MaxValue && Vector2Extensions.DistanceSquared(f.Position, fruit.Position) < distance * distance)) { fruit.X += RNG.Next(-5, 5); fruit.Y -= RNG.Next(0, 5); } caughtFruit.Add(fruit); if (((CatchBaseHit)fruit.HitObject).LastInCombo) { explode(); } }
private void InitField(Vector2Int size) { cells = new Cell[size.x, size.y]; var cellSize = Vector2Extensions.Multiply(CellPrefab.GetComponent <RectTransform>().sizeDelta, CellPrefab.GetComponent <RectTransform>().localScale); var wholeFieldSize = new Vector2(cellSize.x * Options.FieldSize.x, cellSize.y * Options.FieldSize.y); var shift = new Vector3(-wholeFieldSize.x, -wholeFieldSize.y) / 2; for (int i = 0; i < size.x; ++i) { for (int j = 0; j < size.y; ++j) { var c = new Vector2Int(i, j); var cellObj = Object.Instantiate(CellPrefab, Field.transform); cellObj.transform.localPosition = shift + new Vector3(i * cellSize.x, j * cellSize.y); var cell = cellObj.GetComponent <Cell>(); cells[i, j] = cell; cell.Init(new CellData(false, false, false)); cell.LeftClick += () => CellLeftClick(c); cell.RightClick += () => CellRightClick(c); cell.Opened += OnCellOpened; } } }
public CollisionResult SolveCollision(CollisionBody colA, CollisionBody colB) { Circle circleA = (Circle)colA.Shape; Circle circleB = (Circle)colB.Shape; Vector2 distance = colA.Position - colB.Position; float abSize = circleA.Radius + circleB.Radius; float penetration = abSize - distance.Length(); Vector2 mtv = default(Vector2); if (penetration <= 0) { return(CollisionResult.NoCollision); } mtv = distance; Vector2Extensions.SafeNormalize(ref mtv); // the distance vector determines the direction of movement. the distance and mtv // should always oppose each other to repel collisions. if (Vector2.Dot(distance, mtv) < 0f) { mtv = -mtv; } return(new CollisionResult() { Us = colA, Them = colB, CollisionResponse = penetration * mtv, IsColliding = true }); }
public override void Draw(Action <TexturedVertex2D> vertexAction) { base.Draw(vertexAction); Shader.Bind(); Texture.TextureGL.Bind(); Vector2 localInflationAmount = edge_smoothness * DrawInfo.MatrixInverse.ExtractScale().Xy; foreach (TriangleParticle particle in Parts) { var offset = triangle_size * new Vector2(particle.Scale * 0.5f, particle.Scale * 0.866f); var size = new Vector2(2 * offset.X, offset.Y); var triangle = new Triangle( Vector2Extensions.Transform(particle.Position * Size, DrawInfo.Matrix), Vector2Extensions.Transform(particle.Position * Size + offset, DrawInfo.Matrix), Vector2Extensions.Transform(particle.Position * Size + new Vector2(-offset.X, offset.Y), DrawInfo.Matrix) ); ColourInfo colourInfo = DrawColourInfo.Colour; colourInfo.ApplyChild(particle.Colour); Texture.DrawTriangle( triangle, colourInfo, null, Shared.VertexBatch.AddAction, Vector2.Divide(localInflationAmount, size)); } Shader.Unbind(); }
private void addLineQuads(Line line, RectangleF texRect) { Vector2 ortho = line.OrthogonalDirection; Line lineLeft = new Line(line.StartPoint + ortho * radius, line.EndPoint + ortho * radius); Line lineRight = new Line(line.StartPoint - ortho * radius, line.EndPoint - ortho * radius); Line screenLineLeft = new Line(Vector2Extensions.Transform(lineLeft.StartPoint, DrawInfo.Matrix), Vector2Extensions.Transform(lineLeft.EndPoint, DrawInfo.Matrix)); Line screenLineRight = new Line(Vector2Extensions.Transform(lineRight.StartPoint, DrawInfo.Matrix), Vector2Extensions.Transform(lineRight.EndPoint, DrawInfo.Matrix)); Line screenLine = new Line(Vector2Extensions.Transform(line.StartPoint, DrawInfo.Matrix), Vector2Extensions.Transform(line.EndPoint, DrawInfo.Matrix)); quadBatch.Add(new TexturedVertex3D { Position = new Vector3(screenLineRight.EndPoint.X, screenLineRight.EndPoint.Y, 0), TexturePosition = new Vector2(texRect.Left, texRect.Centre.Y), Colour = colourAt(lineRight.EndPoint) }); quadBatch.Add(new TexturedVertex3D { Position = new Vector3(screenLineRight.StartPoint.X, screenLineRight.StartPoint.Y, 0), TexturePosition = new Vector2(texRect.Left, texRect.Centre.Y), Colour = colourAt(lineRight.StartPoint) }); // Each "quad" of the slider is actually rendered as 2 quads, being split in half along the approximating line. // On this line the depth is 1 instead of 0, which is done properly handle self-overlap using the depth buffer. // Thus the middle vertices need to be added twice (once for each quad). Vector3 firstMiddlePoint = new Vector3(screenLine.StartPoint.X, screenLine.StartPoint.Y, 1); Vector3 secondMiddlePoint = new Vector3(screenLine.EndPoint.X, screenLine.EndPoint.Y, 1); Color4 firstMiddleColour = colourAt(line.StartPoint); Color4 secondMiddleColour = colourAt(line.EndPoint); for (int i = 0; i < 2; ++i) { quadBatch.Add(new TexturedVertex3D { Position = firstMiddlePoint, TexturePosition = new Vector2(texRect.Right, texRect.Centre.Y), Colour = firstMiddleColour }); quadBatch.Add(new TexturedVertex3D { Position = secondMiddlePoint, TexturePosition = new Vector2(texRect.Right, texRect.Centre.Y), Colour = secondMiddleColour }); } quadBatch.Add(new TexturedVertex3D { Position = new Vector3(screenLineLeft.EndPoint.X, screenLineLeft.EndPoint.Y, 0), TexturePosition = new Vector2(texRect.Left, texRect.Centre.Y), Colour = colourAt(lineLeft.EndPoint) }); quadBatch.Add(new TexturedVertex3D { Position = new Vector3(screenLineLeft.StartPoint.X, screenLineLeft.StartPoint.Y, 0), TexturePosition = new Vector2(texRect.Left, texRect.Centre.Y), Colour = colourAt(lineLeft.StartPoint) }); }
/// <summary> /// Applies the positional and rotational state of this rigid body to its source. /// </summary> public virtual void ApplyState() { Matrix3 mat = SimulationToScreenSpace * Parent.DrawInfo.MatrixInverse; Position = Vector2Extensions.Transform(Centre, mat) + (Position - BoundingBox.Centre); Rotation = MathHelper.RadiansToDegrees(RotationRadians); // TODO: Fix rotations }
/// <summary> /// Checks for and records all collisions with another body. If collisions were found, /// their aggregate is handled. /// </summary> public bool CheckAndHandleCollisionWith(IRigidBody other) { if (!other.ScreenSpaceDrawQuad.AABB.IntersectsWith(ScreenSpaceDrawQuad.AABB)) { return(false); } bool didCollide = false; for (int i = 0; i < Vertices.Count; ++i) { if (other.BodyContains(Vector2Extensions.Transform(Vertices[i], SimulationToScreenSpace))) { // Compute both impulse responses _before_ applying them, such that // they do not influence each other. Vector2 impulse = this.ComputeImpulse(other, Vertices[i], Normals[i]); Vector2 impulseOther = other.ComputeImpulse(this, Vertices[i], -Normals[i]); ApplyImpulse(impulse, Vertices[i]); other.ApplyImpulse(impulseOther, Vertices[i]); didCollide = true; } } return(didCollide); }
public virtual void HandleMousePositionChange(InputState state) { var mouse = state.Mouse; foreach (var h in InputHandlers) { if (h.Enabled && h is INeedsMousePositionFeedback handler) { handler.FeedbackMousePositionChange(mouse.Position); } } handleMouseMove(state); if (!dragStarted) { if (mouse.IsPressed(MouseButton.Left) && Vector2Extensions.Distance(mouse.PositionMouseDown ?? mouse.Position, mouse.Position) > click_drag_distance) { handleMouseDragStart(state); } } else { handleMouseDrag(state); } }
public void knightPlacer(PlayerController owner) { AIActor orLoadByGuid = EnemyDatabase.GetOrLoadByGuid("ec8ea75b557d4e7b8ceeaacdf6f8238c"); IntVector2 aim = Vector2Extensions.ToIntVector2(owner.unadjustedAimPoint, VectorConversions.Round); RoomHandler room = GameManager.Instance.Dungeon.data.GetAbsoluteRoomFromPosition(aim); if (room != null && room == owner.CurrentRoom && owner.IsInCombat) { AIActor aiActor = AIActor.Spawn(orLoadByGuid.aiActor, owner.CenterPosition, room, true, AIActor.AwakenAnimationType.Default, true); PhysicsEngine.Instance.RegisterOverlappingGhostCollisionExceptions(aiActor.specRigidbody, null, false); aiActor.CanTargetEnemies = true; aiActor.CanTargetPlayers = false; aiActor.IsHarmlessEnemy = true; aiActor.CanDropCurrency = false; aiActor.IgnoreForRoomClear = true; aiActor.MovementSpeed = 6.3f; aiActor.gameObject.AddComponent <KillOnRoomClear>(); aiActor.reinforceType = AIActor.ReinforceType.Instant; aiActor.HandleReinforcementFallIntoRoom(.1f); nut = aiActor; MindControlEffect orAddComponent = aiActor.gameObject.GetOrAddComponent <MindControlEffect>(); orAddComponent.owner = (this.gun.CurrentOwner as PlayerController); } }
private void subdivide(Vector2 A, Vector2 B, Vector2 C, Vector2 D, List <Vector2> points, float minLength) { if (Vector2.Distance(A, C) < minLength || Vector2.Distance(B, D) < minLength) { return; } // Subdivide the quadrilateral float p = Random.Range(0.2f, 0.8f); // vertical (along A-D and B-C) float q = Random.Range(0.2f, 0.8f); // horizontal (along A-B and D-C) // Midpoints Vector2 E = Vector2Extensions.Interpolate(A, D, p); Vector2 F = Vector2Extensions.Interpolate(B, C, p); Vector2 G = Vector2Extensions.Interpolate(A, B, q); Vector2 I = Vector2Extensions.Interpolate(D, C, q); // Central point Vector2 H = Vector2Extensions.Interpolate(E, F, q); // Divide the quad into subquads, but meet at H float s = 1 - Random.Range(-0.4f, 0.4f); float t = 1 - Random.Range(-0.4f, 0.4f); subdivide(A, Vector2Extensions.Interpolate(G, B, s), H, Vector2Extensions.Interpolate(E, D, t), points, minLength); points.Add(H); subdivide(H, Vector2Extensions.Interpolate(F, C, s), C, Vector2Extensions.Interpolate(I, D, t), points, minLength); }
public CollisionResult SolveCollision(CollisionBody colA, CollisionBody colB) { Box boxA = colA.Shape as Box; Box boxB = colB.Shape as Box; Matrix3 transformA = colA.WorldTransform; Matrix3 transformB = colB.WorldTransform; float projectedDistance = 0; float minPenetration = float.MaxValue; Vector2 distance = colA.Position - colB.Position; Vector2 mtv = default(Vector2); // the minimum translation vector // merge normals from both polygons // NOTE: For OBB's we only need to check their half widths. ie. 4 axis total. // For AABB's we only need to check 2 axis since they don't rotate. boxA.CalculateOrientation(ref transformA, out _axisToCheck[0]); boxB.CalculateOrientation(ref transformB, out _axisToCheck[1]); _axisToCheck[2] = Vector2Extensions.PerpendicularLeft(_axisToCheck[0]); _axisToCheck[3] = Vector2Extensions.PerpendicularLeft(_axisToCheck[1]); // TODO: remove parallel normals for (int i = 0; i < _axisToCheck.Length; i++) { Vector2 projectionA, projectionB; projectedDistance = Math.Abs(Vector2.Dot(distance, _axisToCheck[i])); boxA.ProjectOnto(ref transformA, ref _axisToCheck[i], out projectionA); boxB.ProjectOnto(ref transformB, ref _axisToCheck[i], out projectionB); float aSize = Math.Abs(projectionA.X) + Math.Abs(projectionA.Y); float bSize = Math.Abs(projectionB.X) + Math.Abs(projectionB.Y); float abSize = aSize + bSize; float penetration = abSize - projectedDistance; // a seperating axis found; there is no collision. if (penetration <= 0) { return(CollisionResult.NoCollision); } // project the object along the axis with the smalled penetration depth. else if (Math.Abs(penetration) < Math.Abs(minPenetration)) { minPenetration = penetration; mtv = _axisToCheck[i]; } } // the distance vector determines the direction of movement. the distance and mtv // should always oppose each other to repel collisions. if (Vector2.Dot(distance, mtv) < 0f) { mtv = -mtv; } // seperating axis could not be found; a collision occurs. return(new CollisionResult() { Us = colA, Them = colB, CollisionResponse = minPenetration * mtv, IsColliding = true }); }
// Token: 0x06000056 RID: 86 RVA: 0x00004194 File Offset: 0x00002394 public void KnightPlacer(PlayerController owner) { try { AIActor orLoadByGuid = EnemyDatabase.GetOrLoadByGuid("ec8ea75b557d4e7b8ceeaacdf6f8238c"); IntVector2 intVector = Vector2Extensions.ToIntVector2(owner.unadjustedAimPoint, (VectorConversions)2); RoomHandler absoluteRoomFromPosition = GameManager.Instance.Dungeon.data.GetAbsoluteRoomFromPosition(intVector); bool flag = absoluteRoomFromPosition != null && absoluteRoomFromPosition == owner.CurrentRoom && owner.IsInCombat; if (flag) { AIActor aiactor = AIActor.Spawn(orLoadByGuid.aiActor, owner.CenterPosition, absoluteRoomFromPosition, true, (AIActor.AwakenAnimationType) 2, true); PhysicsEngine.Instance.RegisterOverlappingGhostCollisionExceptions(aiactor.specRigidbody, null, false); aiactor.CanTargetEnemies = true; aiactor.CanTargetPlayers = false; aiactor.IsHarmlessEnemy = true; aiactor.CanDropCurrency = false; aiactor.IgnoreForRoomClear = true; aiactor.MovementSpeed = 5.95f; aiactor.CompanionOwner = owner; aiactor.IsBuffEnemy = true; aiactor.isPassable = true; aiactor.gameObject.AddComponent <KillOnRoomClear>(); aiactor.reinforceType = (AIActor.ReinforceType) 2; aiactor.HandleReinforcementFallIntoRoom(0.1f); //added this so the player doesn't collide with the nut when dodge rolling, he goes through companions aiactor.gameObject.AddComponent <CompanionController>(); CompanionController component = aiactor.gameObject.GetComponent <CompanionController>(); component.Initialize(owner); this.nut = aiactor; MindControlEffect orAddComponent = GameObjectExtensions.GetOrAddComponent <MindControlEffect>(aiactor.gameObject); orAddComponent.owner = (this.gun.CurrentOwner as PlayerController); // to make the nut invincible against the player effects or any other damage effects if (aiactor.healthHaver != null) { aiactor.healthHaver.PreventAllDamage = true; } // to prevent the attacks of the nut from damaging the player if (aiactor.bulletBank != null) { AIBulletBank bulletBank = aiactor.bulletBank; bulletBank.OnProjectileCreated = (Action <Projectile>)Delegate.Combine(bulletBank.OnProjectileCreated, new Action <Projectile>(CopperChariot.OnPostProcessProjectile)); } if (aiactor.aiShooter != null) { AIShooter aiShooter = aiactor.aiShooter; aiShooter.PostProcessProjectile = (Action <Projectile>)Delegate.Combine(aiShooter.PostProcessProjectile, new Action <Projectile>(CopperChariot.OnPostProcessProjectile)); } } } catch (Exception e) { Tools.Print("Copper KnightPlacer", "FFFFFF", true); Tools.PrintException(e); } }
protected virtual void CalculateNormals() { for (int i = 0; i < Vertices.Length; i++) { Normals[i] = Vector2Extensions.PerpendicularLeft(Vertices[(i + 1) % Vertices.Length] - Vertices[i]); Normals[i].Normalize(); } }
public static Quad operator *(Quad r, Matrix3 m) { return(new Quad( Vector2Extensions.Transform(r.TopLeft, m), Vector2Extensions.Transform(r.TopRight, m), Vector2Extensions.Transform(r.BottomLeft, m), Vector2Extensions.Transform(r.BottomRight, m))); }
/// <summary> /// Calculates angles and such between a target point for the enemy /// </summary> /// <param name="target"> Target position </param> void setTargetPosition(Vector2 target) { walkAngle = angleBetween(target, position); velocity = Vector2Extensions.FromAngle(walkAngle); setWalkAngle(walkAngle + MathHelper.PiOver2); }
/// <summary> /// Reads a strip from a byte array /// </summary> /// <param name="source">Byte source</param> /// <param name="address">Address at which the strip is located</param> /// <param name="userAttributes">Amount of user attributes</param> /// <param name="hasUV">Whether the polygons carry uv data</param> /// <param name="HDUV">Whether the uv data repeats at 1024, not 256</param> /// <param name="hasNormal">Whether the polygons carry normal data</param> /// <param name="hasColor">Whether the polygons carry color data</param> /// <returns></returns> public static Strip Read(byte[] source, ref uint address, byte userAttributes, bool hasUV, bool HDUV, bool hasNormal, bool hasColor) { short header = source.ToInt16(address); bool reverse = header < 0; Corner[] corners = new Corner[Math.Abs(header)]; bool flag1 = userAttributes > 0; bool flag2 = userAttributes > 1; bool flag3 = userAttributes > 2; float multiplier = HDUV ? 1f / 1024f : 1f / 256f; address += 2; for (int i = 0; i < corners.Length; i++) { Corner c = new() { Index = source.ToUInt16(address) }; address += 2; if (hasUV) { c.Texcoord = Vector2Extensions.Read(source, ref address, IOType.Short) * multiplier; } if (hasNormal) { c.Normal = Vector3Extensions.Read(source, ref address, IOType.Float); } else if (hasColor) { c.Color = Color.Read(source, ref address, IOType.ARGB8_16); } if (flag1 && i > 1) { c.UserFlag1 = source.ToUInt16(address); address += 2; if (flag2) { c.UserFlag2 = source.ToUInt16(address); address += 2; if (flag3) { c.UserFlag3 = source.ToUInt16(address); address += 2; } } } corners[i] = c; } return(new Strip(corners, reverse)); }
public int GetIndexInDirection(Vector2 vec) { var joyDirection = Vector2Extensions.FullAngle(Vector2.right, vec); var degreesBetweenMarks = 360.0f / characterMarks.Count; var index = joyDirection / degreesBetweenMarks; var portion = index - (int)index; return(Mathf.RoundToInt(index) % characterMarks.Count); }
public void DivideWithFloat() { Vector2 a = Vector2.one * 10f; Assert.AreEqual(Vector2.one * 0.2f, Vector2Extensions.Divide(2f, a)); Assert.AreEqual(Vector2.one * 0.5f, Vector2Extensions.Divide(5f, a)); Assert.AreEqual(Vector2.one, Vector2Extensions.Divide(10f, a)); Assert.AreEqual(Vector2.zero, Vector2Extensions.Divide(0f, a)); }
public ResourceAnimation animate(List <Sprite> sprites, Sprite borders, Color color, bool grayscale, Vector2 sourceScreenPos, Vector2 targetScreenPos, double resourceAmount, int spriteAmount, float durationMin, float durationMax, float localScaleMin, float localScaleMax, float maxOffsetDistance, bool fromMenu, Action <int, int, double, bool> endCallback, [Optional, DefaultParameterValue(-1)] int siblingIndex) { spriteAmount = Mathf.Clamp(spriteAmount, 0, 0x30); ResourceAnimation item = this.m_resourceAnimationPool.getObject(); for (int i = 0; i < spriteAmount; i++) { Vector3 vector; ResourceGainImage image = Binder.ResourceGainImagePool.getObject(); image.transform.SetParent(this.RootTm); if (siblingIndex != -1) { image.transform.SetSiblingIndex(siblingIndex); } else { image.transform.SetAsLastSibling(); } image.Image.sprite = LangUtil.GetRandomValueFromList <Sprite>(sprites); image.Borders.sprite = borders; image.Borders.enabled = borders != null; image.Image.color = color; image.Image.material = !grayscale ? null : Binder.DisabledUiMaterial; if (image.Borders != null) { image.Borders.color = image.Image.color; image.Borders.material = image.Image.material; } image.gameObject.SetActive(true); item.ImageTm[i] = image.transform; item.Image[i] = image; item.ImageTm[i].localScale = (Vector3)(Vector3.one * UnityEngine.Random.Range(localScaleMin, localScaleMax)); item.SourceScreenPos[i] = sourceScreenPos; item.TargetScreenPos[i] = targetScreenPos; RectTransformUtility.ScreenPointToWorldPointInRectangle(this.RootTm, sourceScreenPos, this.m_canvasCam, out vector); image.transform.position = vector; image.transform.localRotation = (spriteAmount <= 1) ? Quaternion.identity : Quaternion.Euler(0f, 0f, UnityEngine.Random.Range((float)-10f, (float)10f)); Vector2 v = sourceScreenPos - targetScreenPos; Vector2 zero = Vector2.zero; float num2 = (UnityEngine.Random.Range(0, 2) != 0) ? 1f : -1f; float max = maxOffsetDistance * (((float)Screen.width) / 1242f); zero = (Vector2)(Vector2Extensions.Rotate(v, num2 * 90f).normalized *UnityEngine.Random.Range(0f, max)); zero.y = UnityEngine.Random.Range(zero.x, -zero.x); item.OffsetScreen[i] = zero; item.Lifetime[i] = UnityEngine.Random.Range(durationMin, durationMax); item.ElapsedTime[i] = 0f; } item.NumSprites = spriteAmount; item.TranslationEasingFunction = Easing.Function.IN_CUBIC; item.EndCallback = endCallback; item.FromMenu = fromMenu; MathUtil.DistributeValuesIntoChunksDouble(resourceAmount, spriteAmount, ref item.ResourceChunks); item.ResourceChunkIndex = 0; this.m_activeResourceAnimations.Add(item); return(item); }
public override void Draw(Action <TexturedVertex2D> vertexAction) { base.Draw(vertexAction); _shader.Bind(); var inflation = DrawInfo.MatrixInverse.ExtractScale().Xy; var colourInfo = DrawColourInfo.Colour; colourInfo.ApplyChild(_colour); if (_audioData != null) { for (var j = 0; j < VisualiserRounds; j++) { for (var i = 0; i < BarsPerVisualiser; i++) { if (_audioData[i] < AmplitudeDeadZone) { continue; } var rotation = MathUtils.DegreesToRadians(i / (float)BarsPerVisualiser * 360 + j * 360 / VisualiserRounds); var rotationCos = MathF.Cos(rotation); var rotationSin = MathF.Sin(rotation); //taking the cos and sin to the 0..1 range var barPosition = new Vector2(rotationCos / 2 + 0.5f, rotationSin / 2 + 0.5f) * _size; var barSize = new Vector2(_size * MathF.Sqrt(2 * (1 - MathF.Cos(MathUtils.DegreesToRadians(360f / BarsPerVisualiser)))) / 2f, BarLength * _audioData[i]); //The distance between the position and the sides of the bar. var bottomOffset = new Vector2(-rotationSin * barSize.X / 2, rotationCos * barSize.X / 2); //The distance between the bottom side of the bar and the top side. var amplitudeOffset = new Vector2(rotationCos * barSize.Y, rotationSin * barSize.Y); var rectangle = new Quad( Vector2Extensions.Transform(barPosition - bottomOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition - bottomOffset + amplitudeOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition + bottomOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition + bottomOffset + amplitudeOffset, DrawInfo.Matrix) ); DrawQuad( _texture, rectangle, colourInfo, null, _vertexBatch.AddAction, //barSize by itself will make it smooth more in the X axis than in the Y axis, this reverts that. Vector2.Divide(inflation, barSize.Yx)); } } } _shader.Unbind(); }
public override void Draw(Action <TexturedVertex2D> vertexAction) { base.Draw(vertexAction); shader.Bind(); Vector2 inflation = DrawInfo.MatrixInverse.ExtractScale().Xy; ColourInfo colourInfo = DrawColourInfo.Colour; colourInfo.ApplyChild(colour); if (audioData != null) { for (int j = 0; j < visualiser_rounds; j++) { for (int i = 0; i < bars_per_visualiser; i++) { if (audioData[i] < amplitude_dead_zone) { continue; } float rotation = MathHelper.DegreesToRadians(i / (float)bars_per_visualiser * 360 + j * 360 / visualiser_rounds); float rotationCos = (float)Math.Cos(rotation); float rotationSin = (float)Math.Sin(rotation); //taking the cos and sin to the 0..1 range var barPosition = new Vector2(rotationCos / 2 + 0.5f, rotationSin / 2 + 0.5f) * size; var barSize = new Vector2(size * (float)Math.Sqrt(2 * (1 - Math.Cos(MathHelper.DegreesToRadians(360f / bars_per_visualiser)))) / 2f, bar_length * audioData[i]); //The distance between the position and the sides of the bar. var bottomOffset = new Vector2(-rotationSin * barSize.X / 2, rotationCos * barSize.X / 2); //The distance between the bottom side of the bar and the top side. var amplitudeOffset = new Vector2(rotationCos * barSize.Y, rotationSin * barSize.Y); var rectangle = new Quad( Vector2Extensions.Transform(barPosition - bottomOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition - bottomOffset + amplitudeOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition + bottomOffset, DrawInfo.Matrix), Vector2Extensions.Transform(barPosition + bottomOffset + amplitudeOffset, DrawInfo.Matrix) ); DrawQuad( texture, rectangle, colourInfo, null, vertexBatch.AddAction, //barSize by itself will make it smooth more in the X axis than in the Y axis, this reverts that. Vector2.Divide(inflation, barSize.Yx)); } } } shader.Unbind(); }
public void TestQuadOrientation(bool normalised) { Quad quad = normalised ? new Quad(Vector2.Zero, new Vector2(1, 0), new Vector2(0, 1), Vector2.One) : new Quad(new Vector2(0, 1), Vector2.One, Vector2.Zero, new Vector2(1, 0)); float orientation = Vector2Extensions.GetOrientation(quad.GetVertices()); Assert.That(orientation, Is.EqualTo(normalised ? 2 : -2).Within(0.001)); }
/// <summary> /// Reads the positional and rotational state of this rigid body from its source. /// </summary> public void ReadState() { Matrix3 mat = Parent.DrawInfo.Matrix * ScreenToSimulationSpace; Centre = Vector2Extensions.Transform(BoundingBox.Centre, mat); RotationRadians = MathHelper.DegreesToRadians(Rotation); // TODO: Fix rotations MomentOfInertia = ComputeI(); UpdateVertices(); }
/// <summary> /// Reads a buffer corner from a byte array /// </summary> /// <param name="source">Byte source</param> /// <param name="address">Address at which the buffer corner is located</param> /// <returns></returns> public static BufferCorner Read(byte[] source, ref uint address) { ushort index = source.ToUInt16(address); address += 2; Color col = Color.Read(source, ref address, IOType.ARGB8_32); Vector2 texcoord = Vector2Extensions.Read(source, ref address, IOType.Float); return(new BufferCorner(index, col, texcoord)); }
private Vector2 transformPosition(Vector2 pos, Vector2 centre, float angle) { float cos = MathF.Cos(angle); float sin = MathF.Sin(angle); float x = centre.X + (pos.X - centre.X) * cos + (pos.Y - centre.Y) * sin; float y = centre.Y + (pos.Y - centre.Y) * cos - (pos.X - centre.X) * sin; return(Vector2Extensions.Transform(new Vector2(x, y), DrawInfo.Matrix)); }
protected override void DoEffect(PlayerController user) { user.secondaryHand.sprite.renderer.enabled = false; var X = user.transform.localScale.x; var Y = user.transform.localScale.y; if (OrigY == 0) { OrigX = X; OrigY = Y; } var deminishX = (user.transform.localScale.x * .45f); var deminishY = (user.transform.localScale.y * .45f); //l RoomHandler room; room = GameManager.Instance.Dungeon.data.GetAbsoluteRoomFromPosition(Vector2Extensions.ToIntVector2(user.CenterPosition, VectorConversions.Round)); CellData cellaim = room.GetNearestCellToPosition(user.CenterPosition); // Oh hey there, // I see you looking through my code... // its okay you can stay // we're all friends here. // take whatever you need // alright have a good day, // see you later //- Skilotar_ if (toggle) { if (cellaim.isNextToWall == false) { user.transform.localScale = new Vector3(deminishX, deminishY, user.transform.localScale.z); user.specRigidbody.UpdateCollidersOnScale = true; user.specRigidbody.UpdateColliderPositions(); toggle = false; } } else { if (cellaim.isNextToWall == false) { user.transform.localScale = new Vector3(OrigX, OrigY, user.transform.localScale.z); user.specRigidbody.UpdateColliderPositions(); toggle = true; } } }