Ejemplo n.º 1
0
        protected virtual void FixedUpdate()
        {
            if (AttachedRigidbody == null)
            {
                AttachedRigidbody = GetComponentInChildren <Rigidbody2D>();
            }

            if (AttachedRigidbody != null)
            {
                if (oldPositionSet == false)
                {
                    oldPositionSet = true;
                    oldPosition    = transform.position;
                }

                var newPosition   = (Vector2)transform.position;
                var deltaPosition = newPosition - oldPosition;
                var deltaSpeed    = deltaPosition.magnitude / Time.fixedDeltaTime;
                var expectedSpeed = deltaSpeed * Vector2.Dot(transform.up, AttachedRigidbody.transform.up);

                oldPosition = newPosition;

                // Match ground speed
                Speed = D2dHelper.Dampen(Speed, expectedSpeed, GripDampening, Time.fixedDeltaTime);

                // Apply speed difference
                var deltaWheel = (Vector2)transform.up * Speed * Time.fixedDeltaTime;

                AttachedRigidbody.AddForceAtPosition(deltaWheel - deltaPosition, transform.position, ForceMode2D.Impulse);

                // Slow wheel down
                Speed = D2dHelper.Dampen(Speed, 0.0f, Friction, Time.fixedDeltaTime);
            }
        }
Ejemplo n.º 2
0
        public void CombineData(byte[] prevData, int prevWidth, int prevHeight)
        {
            var dataX      = Rect.MinX;
            var dataY      = Rect.MinY;
            var dataWidth  = Rect.SizeX;
            var dataHeight = Rect.SizeY;

            if (Data != null && Data.Length >= dataWidth * dataHeight && prevData != null && prevData.Length >= prevWidth * prevHeight)
            {
                for (var y = 0; y < dataHeight; y++)
                {
                    for (var x = 0; x < dataWidth; x++)
                    {
                        var prevX = x + dataX;
                        var prevY = y + dataY;
                        var dataI = x + y * dataWidth;

                        if (prevX >= 0 && prevY >= 0 && prevX < prevWidth && prevY < prevHeight)
                        {
                            var prevI = prevX + prevY * prevWidth;
                            var dataA = D2dHelper.ConvertAlpha(Data[dataI]);
                            var prevA = D2dHelper.ConvertAlpha(prevData[prevI]);

                            Data[dataI] = D2dHelper.ConvertAlpha(dataA * prevA);
                        }
                        else
                        {
                            Data[dataI] = 0;
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public void UpdateSprite()
        {
            if (cropSprite == true)
            {
                if (CachedSpriteRenderer.sprite == null)
                {
                    cachedSpriteRenderer.sprite = originalSprite;
                }

                if (cachedSpriteRenderer.sprite != clonedSprite)
                {
                    originalSprite = cachedSpriteRenderer.sprite;
                    clonedSprite   = D2dHelper.Destroy(clonedSprite);
                    clonedSprite   = cachedSpriteRenderer.sprite = Instantiate(originalSprite);
                }
            }
            else
            {
                if (CachedSpriteRenderer.sprite == clonedSprite)
                {
                    CachedSpriteRenderer.sprite = originalSprite;

                    clonedSprite = D2dHelper.Destroy(clonedSprite);
                }
            }
        }
Ejemplo n.º 4
0
        protected override void OnInspector()
        {
            DrawDefault("DebugCollisions");

            Separator();

            DrawDefault("UseFirstOnly");
            DrawDefault("ImpactMask");
            DrawDefault("ImpactThreshold");

            BeginError(Any(t => t.ImpactDelay < 0.0f));
            DrawDefault("ImpactDelay");
            EndError();

            Separator();

            DrawDefault("DamageOnImpact");

            if (Any(t => t.DamageOnImpact == true))
            {
                BeginIndent();
                DrawDefault("DamageDestructible");
                DrawDefault("DamageScale");
                EndIndent();
            }

            Separator();

            showEvents = EditorGUI.Foldout(D2dHelper.Reserve(), showEvents, "Events");

            if (showEvents == true)
            {
                DrawDefault("OnImpact");
            }
        }
        private void Collision(Collision2D collision)
        {
            if (cooldown <= 0.0f)
            {
                if (D2dHelper.IndexInMask(collision.gameObject.layer, mask) == true)
                {
                    var contacts = collision.contacts;

                    for (var i = contacts.Length - 1; i >= 0; i--)
                    {
                        var normal = collision.relativeVelocity;
                        var force  = normal.magnitude;

                        if (force >= threshold)
                        {
                            cooldown = delay;

                            cachedDamage.Damage += force * scale;

                            if (onImpact != null)
                            {
                                onImpact.Invoke();
                            }

                            if (delay > 0.0f)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public override void OnInspectorGUI()
        {
            EditorGUI.BeginChangeCheck();
            {
                Target  = (T)target;
                Targets = targets.Select(t => (T)t).ToArray();

                Separator();

                OnInspector();

                Separator();

                serializedObject.ApplyModifiedProperties();
            }
            if (EditorGUI.EndChangeCheck() == true)
            {
                GUI.changed = true; Repaint();

                foreach (var t in Targets)
                {
                    D2dHelper.SetDirty(t);
                }
            }
        }
Ejemplo n.º 7
0
        protected virtual void Update()
        {
            var localPosition = transform.localPosition;
            var targetX       = (Input.mousePosition.x - Screen.width / 2) * MoveScale;
            var targetY       = (Input.mousePosition.y - Screen.height / 2) * MoveScale;

            localPosition.x = D2dHelper.Dampen(localPosition.x, targetX, MoveSpeed, Time.deltaTime);
            localPosition.y = D2dHelper.Dampen(localPosition.y, targetY, MoveSpeed, Time.deltaTime);

            transform.localPosition = localPosition;

            // Left click?
            if (Input.GetMouseButtonDown(0) == true)
            {
                var mainCamera = Camera.main;

                if (MuzzlePrefab != null)
                {
                    Instantiate(MuzzlePrefab, transform.position, Quaternion.identity);
                }

                if (BulletPrefab != null && mainCamera != null)
                {
                    var position = mainCamera.ScreenToWorldPoint(Input.mousePosition);

                    Instantiate(BulletPrefab, position, Quaternion.identity);
                }
            }
        }
Ejemplo n.º 8
0
        protected virtual void OnDisable()
        {
            cachedDestructible.OnRebuilt    -= HandleRebuilt;
            cachedDestructible.OnModified   -= HandleModified;
            cachedDestructible.OnSplitStart -= HandleSplitStart;
            cachedDestructible.OnSplitEnd   -= HandleSplitEnd;

            if (child != null)
            {
                child.SetActive(false);
            }

            // If the collider was disabled while splitting then run this special code to destroy the children
            if (cachedDestructible.IsOnStartSplit == true)
            {
                if (child != null)
                {
                    child.transform.SetParent(null, false);

                    child = D2dHelper.Destroy(child);
                }

                if (tempChild != null)
                {
                    tempChild = D2dHelper.Destroy(tempChild);
                }
            }
        }
Ejemplo n.º 9
0
        protected virtual void OnDisable()
        {
            destructible.OnAlphaDataReplaced.RemoveListener(OnAlphaDataReplaced);
            destructible.OnAlphaDataModified.RemoveListener(OnAlphaDataModified);
            destructible.OnAlphaDataSubset.RemoveListener(OnAlphaDataSubset);
            destructible.OnStartSplit.RemoveListener(OnStartSplit);
            destructible.OnEndSplit.RemoveListener(OnEndSplit);

            if (child != null)
            {
                child.SetActive(false);
            }

            // If the collider was disabled while splitting then run this special code to destroy the children
            if (destructible.IsOnStartSplit == true)
            {
                if (child != null)
                {
                    child.transform.SetParent(null, false);

                    child = D2dHelper.Destroy(child);
                }

                if (tempChild != null)
                {
                    tempChild = D2dHelper.Destroy(tempChild);
                }
            }
        }
        public void UpdateFixtures()
        {
            if (Fixtures.Count > 0)
            {
                for (var i = Fixtures.Count - 1; i >= 0; i--)
                {
                    var fixture = Fixtures[i];

                    if (FixtureIsConnected(fixture) == false)
                    {
                        Fixtures.RemoveAt(i);
                    }
                }

                if (Fixtures.Count == 0)
                {
                    if (OnAllFixturesRemoved != null)
                    {
                        OnAllFixturesRemoved.Invoke();
                    }

                    if (AutoDestroy == true)
                    {
                        D2dHelper.Destroy(this);
                    }
                }
            }
        }
        private void Stamp(Vector2 from, Vector2 to)
        {
            // Main camera exists?
            var mainCamera = Camera.main;

            if (mainCamera != null)
            {
                if (from != to)
                {
                    var delta = to - from;

                    lastAngle = -Mathf.Atan2(delta.x, delta.y) * Mathf.Rad2Deg;
                }

                var positionA = D2dHelper.ScreenToWorldPosition(from, Intercept, mainCamera);
                var positionB = D2dHelper.ScreenToWorldPosition(to, Intercept, mainCamera);
                var positionM = (positionA + positionB) * 0.5f;
                var length    = Vector3.Distance(positionA, positionB) * Stretch;

                if (length < Size.y)
                {
                    length = Size.y;
                }

                var size = new Vector2(Size.x, length);

                // Stamp at that point
                D2dDestructible.StampAll(positionM, size, lastAngle, StampTex, Hardness, Layers);
            }
        }
Ejemplo n.º 12
0
        protected virtual void Update()
        {
            Life -= Time.deltaTime;

            if (Life > 0.0f)
            {
                if (Fade == true)
                {
                    UpdateFade();
                }

                if (Shrink == true)
                {
                    UpdateShrink();
                }
            }
            else if (target != null)
            {
                D2dHelper.Destroy(target);
            }
            else
            {
                D2dHelper.Destroy(gameObject);
            }
        }
        protected virtual void FixedUpdate()
        {
            var currentPoint = (Vector2)transform.position;
            var vector       = targetPoint - currentPoint;

            if (vector.magnitude <= MinimumDistance)
            {
                ChangeTargetPoint();

                vector = targetPoint - currentPoint;
            }

            // Limit target speed
            if (vector.magnitude > MaximumSpeed)
            {
                vector = vector.normalized * MaximumSpeed;
            }

            // Acceleration
            if (body == null)
            {
                body = GetComponent <Rigidbody2D>();
            }

            body.velocity = D2dHelper.Dampen2(body.velocity, vector * SpeedBoost, Acceleration, Time.deltaTime);
        }
Ejemplo n.º 14
0
        protected virtual void Update()
        {
            // Get main camera
            var mainCamera = Camera.main;

            // Begin dragging
            if (Input.GetKey(Requires) == true && down == false)
            {
                down = true;
                startMousePosition = Input.mousePosition;
            }

            // Dragging finger released?
            if (Input.GetKey(Requires) == false && down == true)
            {
                down = false;

                // Impact prefab exists?
                if (ImpactPrefab != null)
                {
                    // Main camera exists?
                    if (mainCamera != null)
                    {
                        // Find start and end world points
                        var startPos = mainCamera.ScreenToWorldPoint(startMousePosition);
                        var endPos   = mainCamera.ScreenToWorldPoint(Input.mousePosition);

                        // Extend end pos to raycast hit
                        CalculateEndPos(startPos, ref endPos);

                        // Spawn explosion there
                        Instantiate(ImpactPrefab, endPos, Quaternion.identity);
                    }
                }
            }

            // Update indicator?
            if (down == true && mainCamera != null && IndicatorPrefab != null)
            {
                if (indicatorInstance == null)
                {
                    indicatorInstance = Instantiate(IndicatorPrefab);
                }

                var startPos = mainCamera.ScreenToWorldPoint(startMousePosition);
                var endPos   = mainCamera.ScreenToWorldPoint(Input.mousePosition); CalculateEndPos(startPos, ref endPos);
                var scale    = Vector3.Distance(endPos, startPos);
                var angle    = D2dHelper.Atan2(endPos - startPos) * Mathf.Rad2Deg;

                // Transform the indicator so it lines up with the slice
                indicatorInstance.transform.position   = new Vector3(startPos.x, startPos.y, indicatorInstance.transform.position.z);
                indicatorInstance.transform.rotation   = Quaternion.Euler(0.0f, 0.0f, -angle);
                indicatorInstance.transform.localScale = new Vector3(Thickness, scale, scale);
            }
            // Destroy indicator?
            else if (indicatorInstance != null)
            {
                Destroy(indicatorInstance.gameObject);
            }
        }
Ejemplo n.º 15
0
        private static float Dampen(float current, float target, float dampening, float elapsed, float minStep = 0.0f)
        {
            var factor   = D2dHelper.DampenFactor(dampening, elapsed);
            var maxDelta = Mathf.Abs(target - current) * factor + minStep * elapsed;

            return(Mathf.MoveTowards(current, target, maxDelta));
        }
Ejemplo n.º 16
0
 public void DestroyChild()
 {
     if (child != null)
     {
         child = D2dHelper.Destroy(child);
     }
 }
 private void Sweep()
 {
     while (tempColliders.Count > 0)
     {
         D2dHelper.Destroy(tempColliders.Pop());
     }
 }
Ejemplo n.º 18
0
        public override void OnInspectorGUI()
        {
            D2dHelper.BaseRect    = D2dHelper.Reserve(0.0f);
            D2dHelper.BaseRectSet = true;

            EditorGUI.BeginChangeCheck();

            serializedObject.UpdateIfDirtyOrScript();

            Target  = (T)target;
            Targets = targets.Select(t => (T)t).ToArray();

            Separator();

            OnInspector();

            Separator();

            serializedObject.ApplyModifiedProperties();

            if (EditorGUI.EndChangeCheck() == true)
            {
                GUI.changed = true; Repaint();

                foreach (var t in Targets)
                {
                    D2dHelper.SetDirty(t);
                }
            }

            D2dHelper.BaseRectSet = false;
        }
Ejemplo n.º 19
0
        protected virtual void FixedUpdate()
        {
            var newPosition  = transform.position;
            var rayLength    = (newPosition - oldPosition).magnitude;
            var rayDirection = (newPosition - oldPosition).normalized;
            var hit          = Physics2D.Raycast(oldPosition, rayDirection, rayLength, RaycastMask);

            // Update old position to trail behind
            if (rayLength > MaxLength)
            {
                rayLength   = MaxLength;
                oldPosition = newPosition - rayDirection * rayLength;
            }

            transform.localScale = MaxScale * D2dHelper.Divide(rayLength, MaxLength);

            if (hit.collider != null)
            {
                if (string.IsNullOrEmpty(IgnoreTag) == true || hit.collider.tag != IgnoreTag)
                {
                    if (ExplosionPrefab != null)
                    {
                        Instantiate(ExplosionPrefab, hit.point, Quaternion.identity);
                    }

                    Destroy(gameObject);
                }
            }
        }
Ejemplo n.º 20
0
        private void Collision(Collision2D collision)
        {
            if (cooldown <= 0.0f && prefab != null)
            {
                if (D2dHelper.IndexInMask(collision.gameObject.layer, mask) == true)
                {
                    var contacts = collision.contacts;

                    for (var i = contacts.Length - 1; i >= 0; i--)
                    {
                        var contact = contacts[i];
                        var normal  = collision.relativeVelocity;
                        var force   = normal.magnitude;

                        if (force >= threshold)
                        {
                            switch (rotateTo)
                            {
                            case RotationType.RandomDirection:
                            {
                                var angle = Random.Range(-Mathf.PI, Mathf.PI);

                                normal.x = Mathf.Sin(angle);
                                normal.y = Mathf.Cos(angle);
                            }
                            break;

                            case RotationType.ImpactDirection:
                            {
                                normal /= force;
                            }
                            break;

                            case RotationType.SurfaceNormal:
                            {
                                normal = contact.normal;
                            }
                            break;
                            }

                            var point = contact.point - contact.normal * offset;

                            cooldown = delay;

                            Instantiate(prefab, point, Quaternion.identity);

                            if (onImpact != null)
                            {
                                onImpact.Invoke();
                            }

                            if (delay > 0.0f)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
 private void SweepColliders()
 {
     while (colliderPool.Count > 0)
     {
         D2dHelper.Destroy(colliderPool.Pop());
     }
 }
Ejemplo n.º 22
0
        protected override void OnInspector()
        {
            showUnused = EditorGUI.Foldout(D2dHelper.Reserve(), showUnused, "Show Unused");

            DrawFloat("Damage Min", ref Target.UseDamageMin, ref Target.DamageMin);

            DrawFloat("Damage Max", ref Target.UseDamageMax, ref Target.DamageMax);

            DrawFloat("Alpha Count Min", ref Target.UseAlphaCountMin, ref Target.AlphaCountMin);

            DrawFloat("Alpha Count Max", ref Target.UseAlphaCountMax, ref Target.AlphaCountMax);

            DrawFloat("Remaining Alpha Min", ref Target.UseRemainingAlphaMin, ref Target.RemainingAlphaMin);

            DrawFloat("Remaining Alpha Max", ref Target.UseRemainingAlphaMax, ref Target.RemainingAlphaMax);

            EditorGUILayout.Separator();

            showEvents = EditorGUI.Foldout(D2dHelper.Reserve(), showEvents, "Show Events");

            if (showEvents == true)
            {
                DrawDefault("OnRequirementMet");
            }
        }
Ejemplo n.º 23
0
        private void Rebuild()
        {
            Destroy();

            var alphaTex = destructible.AlphaTex;

            if (alphaTex != null)
            {
                var spriteRenderer = child.GetComponent <SpriteRenderer>();
                var sprite         = Sprite.Create(alphaTex, new Rect(0, 0, alphaTex.width, alphaTex.height), Vector2.zero, 1.0f, 0, SpriteMeshType.FullRect);

                if (spriteRenderer == null)
                {
                    spriteRenderer = child.AddComponent <SpriteRenderer>();
                }

                spriteRenderer.sprite = sprite;

                polygonCollider2D = child.AddComponent <PolygonCollider2D>();

                polygonCollider2D.enabled        = IsDefaultPolygonCollider2D(polygonCollider2D) == false;
                polygonCollider2D.isTrigger      = IsTrigger;
                polygonCollider2D.sharedMaterial = Material;

                D2dHelper.Destroy(sprite);
                D2dHelper.Destroy(spriteRenderer);
            }
        }
        protected virtual void Update()
        {
            // Required key is down?
            if (Input.GetKeyDown(Requires) == true)
            {
                // Prefab exists?
                if (Prefab != null)
                {
                    // Main camera exists?
                    var mainCamera = Camera.main;

                    if (mainCamera != null)
                    {
                        // World position of the mouse
                        var position = D2dHelper.ScreenToWorldPosition(Input.mousePosition, Intercept, mainCamera);

                        // Get a random rotation around the Z axis
                        var rotation = Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f));

                        // Spawn prefab here
                        Instantiate(Prefab, position, rotation);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public static bool ExtractAlpha(Texture2D texture2D, int x, int y, int width, int height)
        {
            if (texture2D != null && x >= 0 && y >= 0 && (x + width) <= texture2D.width && (y + height) <= texture2D.height)
            {
#if UNITY_EDITOR
                D2dHelper.MakeTextureReadable(texture2D);
#endif
                var pixels32       = texture2D.GetPixels32();
                var total          = width * height;
                var texture2DWidth = texture2D.width;

                // Replace alpha data array?
                if (AlphaData == null || AlphaData.Length != total)
                {
                    AlphaData = new byte[total];
                }

                // Copy alpha from texture
                for (var v = height - 1; v >= 0; v--)
                {
                    var aOffset = v * width;
                    var pOffset = (y + v) * texture2DWidth + x;

                    for (var h = width - 1; h >= 0; h--)
                    {
                        AlphaData[aOffset + h] = pixels32[pOffset + h].a;
                    }
                }

                return(true);
            }

            return(false);
        }
        public void Heal(Matrix4x4 newMatrix, Texture2D newShape, Color newColor)
        {
            if (ready == true && newShape != null && CanHeal == true)
            {
                var healData = healSnapshot.Data;
                var rect     = default(D2dRect);

                matrix     = WorldToAlphaMatrix * newMatrix;
                alphaCount = -1;

                if (D2dHelper.CalculateRect(matrix, ref rect, alphaWidth, alphaHeight) == true)
                {
                    inverse    = matrix.inverse;
                    shape      = newShape;
                    shapeW     = newShape.width;
                    shapeH     = newShape.height;
                    shapeColor = newColor * paintMultiplier;

                    rect.MinX = Mathf.Clamp(rect.MinX, 0, alphaWidth);
                    rect.MaxX = Mathf.Clamp(rect.MaxX, 0, alphaWidth);
                    rect.MinY = Mathf.Clamp(rect.MinY, 0, alphaHeight);
                    rect.MaxY = Mathf.Clamp(rect.MaxY, 0, alphaHeight);

                    var alphaPixelX     = D2dHelper.Reciprocal(alphaWidth);
                    var alphaPixelY     = D2dHelper.Reciprocal(alphaHeight);
                    var alphaHalfPixelX = alphaPixelX * 0.5f;
                    var alphaHalfPixelY = alphaPixelY * 0.5f;

                    for (var y = rect.MinY; y < rect.MaxY; y++)
                    {
                        var v      = y * alphaPixelY + alphaHalfPixelY;
                        var offset = y * alphaWidth;

                        for (var x = rect.MinX; x < rect.MaxX; x++)
                        {
                            var u = x * alphaPixelX + alphaHalfPixelX;

                            if (CalculateShapeCoord(u, v) == true)
                            {
                                var index      = offset + x;
                                var alphaPixel = alphaData[index];
                                var shapePixel = SampleShapeA();

                                alphaPixel.a = (byte)System.Math.Min(alphaPixel.a + shapePixel, healData.AlphaData[index].a);

                                if (pixels == PixelsType.PixelatedBinary)
                                {
                                    alphaPixel.a = alphaPixel.a > 127 ? (byte)255 : (byte)0;
                                }

                                alphaData[index] = alphaPixel;
                            }
                        }
                    }

                    AlphaModified.Add(rect);
                }
            }
        }
Ejemplo n.º 27
0
        protected virtual void Update()
        {
            var factor = D2dHelper.DampenFactor(Dampening, Time.deltaTime);

            currentThrottle = Mathf.Lerp(currentThrottle, Throttle, factor);

            transform.localScale = MaxScale * Random.Range(1.0f - Flicker, 1.0f + Flicker) * currentThrottle;
        }
Ejemplo n.º 28
0
        private void Sweep()
        {
            for (var i = unusedColliders.Count - 1; i >= 0; i--)
            {
                D2dHelper.Destroy(unusedColliders[i]);
            }

            unusedColliders.Clear();
        }
Ejemplo n.º 29
0
        protected void DirtyEach(System.Action <T> update)
        {
            foreach (var t in Targets)
            {
                update(t);

                D2dHelper.SetDirty(t);
            }
        }
Ejemplo n.º 30
0
        /// <summary>This will return the transformation matrix used to convert between world space and slice sprite space.</summary>
        public static Matrix4x4 CalculateMatrix(Vector2 startPos, Vector2 endPos, float thickness)
        {
            var mid   = (startPos + endPos) / 2.0f;
            var vec   = endPos - startPos;
            var size  = new Vector2(thickness, vec.magnitude);
            var angle = D2dHelper.Atan2(vec) * -Mathf.Rad2Deg;

            return(D2dStamp.CalculateMatrix(mid, size, angle));
        }