Beispiel #1
0
        void PlayAnimationArmsShooting(float direction)
        {
            Vector2 cart = new Vector2(1, direction).ToCartesian();
            if (FlipX)
                cart.X *= -1;
            direction = cart.Angle();

            float factor = MathHelper.Clamp(shotAnimationTimer, 0, 1);

            shoulderLeft.TargetRotation = 30 + VectorExtensions.AngleDifference(0, direction) +  factor * 100;
            elbowLeft.TargetRotation = -60 - factor * 100;

            shoulderRight.TargetRotation = -110 + direction + factor * 80;//120
            elbowRight.TargetRotation = -80 - factor * 80;
            gun.TargetRotation = 110 + 80;
            head.TargetRotation = VectorExtensions.AngleDifference(0, direction) * 0.5f;
            body.TargetRotation = VectorExtensions.AngleDifference(0, direction) * 0.2f;
        }
Beispiel #2
0
            // return true if frame skipped
            public override bool Update()
            {
                if (!ChangeProp.Set(ref updatedFrameCount, Time.frameCount))
                {
                    return(true);
                }

                var deviceIndex = m_map.GetMappedDeviceByRoleValue(m_roleValue);

                // treat this frame as updated if both prevDeviceIndex and currentDeviceIndex are invalid
                if (!VRModule.IsValidDeviceIndex(prevDeviceIndex) && !VRModule.IsValidDeviceIndex(deviceIndex))
                {
                    return(false);
                }

                // get device state
                var currState = VRModule.GetCurrentDeviceState(deviceIndex);

                // copy to previous states and reset current state
                prevDeviceIndex = deviceIndex;

                prevButtonPressed  = currButtonPressed;
                currButtonPressed  = 0;
                currentInput2DType = currState.input2DType;

                for (int i = CONTROLLER_AXIS_COUNT - 1; i >= 0; --i)
                {
                    prevAxisValue[i] = currAxisValue[i];
                    currAxisValue[i] = 0f;
                }

                // update button states
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.System, currState.GetButtonPress(VRModuleRawButton.System));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Menu, currState.GetButtonPress(VRModuleRawButton.ApplicationMenu));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.MenuTouch, currState.GetButtonTouch(VRModuleRawButton.ApplicationMenu));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Trigger, currState.GetButtonPress(VRModuleRawButton.Trigger));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.TriggerTouch, currState.GetButtonTouch(VRModuleRawButton.Trigger));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Pad, currState.GetButtonPress(VRModuleRawButton.Touchpad));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.PadTouch, currState.GetButtonTouch(VRModuleRawButton.Touchpad));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Grip, currState.GetButtonPress(VRModuleRawButton.Grip));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.GripTouch, currState.GetButtonTouch(VRModuleRawButton.Grip));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.CapSenseGrip, currState.GetButtonPress(VRModuleRawButton.CapSenseGrip));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.CapSenseGripTouch, currState.GetButtonTouch(VRModuleRawButton.CapSenseGrip));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.ProximitySensor, currState.GetButtonPress(VRModuleRawButton.ProximitySensor));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.AKey, currState.GetButtonPress(VRModuleRawButton.A));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.AKeyTouch, currState.GetButtonTouch(VRModuleRawButton.A));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Bumper, currState.GetButtonTouch(VRModuleRawButton.Bumper));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.BumperTouch, currState.GetButtonTouch(VRModuleRawButton.Bumper));

                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Axis4, currState.GetButtonPress(VRModuleRawButton.Axis4));
                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.Axis4Touch, currState.GetButtonTouch(VRModuleRawButton.Axis4));

                // update axis values
                currAxisValue[(int)ControllerAxis.PadX]         = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                currAxisValue[(int)ControllerAxis.PadY]         = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                currAxisValue[(int)ControllerAxis.Trigger]      = currState.GetAxisValue(VRModuleRawAxis.Trigger);
                currAxisValue[(int)ControllerAxis.CapSenseGrip] = currState.GetAxisValue(VRModuleRawAxis.CapSenseGrip);
                currAxisValue[(int)ControllerAxis.IndexCurl]    = currState.GetAxisValue(VRModuleRawAxis.IndexCurl);
                currAxisValue[(int)ControllerAxis.MiddleCurl]   = currState.GetAxisValue(VRModuleRawAxis.MiddleCurl);
                currAxisValue[(int)ControllerAxis.RingCurl]     = currState.GetAxisValue(VRModuleRawAxis.RingCurl);
                currAxisValue[(int)ControllerAxis.PinkyCurl]    = currState.GetAxisValue(VRModuleRawAxis.PinkyCurl);

                switch (currentInput2DType)
                {
                case VRModuleInput2DType.Unknown:
                case VRModuleInput2DType.TrackpadOnly:
                    currAxisValue[(int)ControllerAxis.PadX] = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                    currAxisValue[(int)ControllerAxis.PadY] = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                    if (!VIUSettings.individualTouchpadJoystickValue)
                    {
                        currAxisValue[(int)ControllerAxis.JoystickX] = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                        currAxisValue[(int)ControllerAxis.JoystickY] = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                    }
                    break;

                case VRModuleInput2DType.JoystickOnly:
                    currAxisValue[(int)ControllerAxis.JoystickX] = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                    currAxisValue[(int)ControllerAxis.JoystickY] = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                    if (!VIUSettings.individualTouchpadJoystickValue)
                    {
                        currAxisValue[(int)ControllerAxis.PadX] = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                        currAxisValue[(int)ControllerAxis.PadY] = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                    }
                    break;

                case VRModuleInput2DType.Both:
                    currAxisValue[(int)ControllerAxis.PadX]      = currState.GetAxisValue(VRModuleRawAxis.TouchpadX);
                    currAxisValue[(int)ControllerAxis.PadY]      = currState.GetAxisValue(VRModuleRawAxis.TouchpadY);
                    currAxisValue[(int)ControllerAxis.JoystickX] = currState.GetAxisValue(VRModuleRawAxis.JoystickX);
                    currAxisValue[(int)ControllerAxis.JoystickY] = currState.GetAxisValue(VRModuleRawAxis.JoystickY);
                    break;
                }

                // update d-pad
                var axis     = new Vector2(currAxisValue[(int)ControllerAxis.PadX], currAxisValue[(int)ControllerAxis.PadY]);
                var deadZone = VIUSettings.virtualDPadDeadZone;

                if (axis.sqrMagnitude >= deadZone * deadZone)
                {
                    var padPress = GetPress(ControllerButton.Pad);
                    var padTouch = GetPress(ControllerButton.PadTouch);

                    var right = Vector2.Angle(Vector2.right, axis) < 45f;
                    var up    = Vector2.Angle(Vector2.up, axis) < 45f;
                    var left  = Vector2.Angle(Vector2.left, axis) < 45f;
                    var down  = Vector2.Angle(Vector2.down, axis) < 45f;

                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadRight, padPress && right);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUp, padPress && up);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLeft, padPress && left);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadDown, padPress && down);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadRightTouch, padTouch && right);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUpTouch, padTouch && up);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLeftTouch, padTouch && left);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadDownTouch, padTouch && down);

                    var upperRight = axis.x > 0f && axis.y > 0f;
                    var upperLeft  = axis.x <0f && axis.y> 0f;
                    var lowerLeft  = axis.x < 0f && axis.y < 0f;
                    var lowerRight = axis.x > 0f && axis.y < 0f;

                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUpperRight, padPress && upperRight);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUpperLeft, padPress && upperLeft);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLowerLeft, padPress && lowerLeft);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLowerRight, padPress && lowerRight);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUpperRightTouch, padTouch && upperRight);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadUpperLeftTouch, padTouch && upperLeft);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLowerLeftTouch, padTouch && lowerLeft);
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.DPadLowerRightTouch, padTouch && lowerRight);
                }

                // update hair trigger
                var currTriggerValue = currAxisValue[(int)ControllerAxis.Trigger];

                EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.FullTrigger, currTriggerValue >= 0.99f);

                if (EnumUtils.GetFlag(prevButtonPressed, (int)ControllerButton.HairTrigger))
                {
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.HairTrigger, currTriggerValue >= (hairTriggerLimit - hairDelta) && currTriggerValue > 0.0f);
                }
                else
                {
                    EnumUtils.SetFlag(ref currButtonPressed, (int)ControllerButton.HairTrigger, currTriggerValue > (hairTriggerLimit + hairDelta) || currTriggerValue >= 1.0f);
                }

                if (EnumUtils.GetFlag(currButtonPressed, (int)ControllerButton.HairTrigger))
                {
                    hairTriggerLimit = Mathf.Max(hairTriggerLimit, currTriggerValue);
                }
                else
                {
                    hairTriggerLimit = Mathf.Min(hairTriggerLimit, currTriggerValue);
                }

                // record pad down axis values
                if (GetPressDown(ControllerButton.Pad))
                {
                    padDownAxis = new Vector2(currAxisValue[(int)ControllerAxis.PadX], currAxisValue[(int)ControllerAxis.PadY]);
                }

                if (GetPressDown(ControllerButton.PadTouch))
                {
                    padTouchDownAxis = new Vector2(currAxisValue[(int)ControllerAxis.PadX], currAxisValue[(int)ControllerAxis.PadY]);
                }

                // record press down time and click count
                var timeNow = Time.unscaledTime;

                for (int button = 0; button < CONTROLLER_BUTTON_COUNT; ++button)
                {
                    if (GetPressDown((ControllerButton)button))
                    {
                        if (timeNow - lastPressDownTime[button] < clickInterval)
                        {
                            ++clickCount[button];
                        }
                        else
                        {
                            clickCount[button] = 1;
                        }

                        lastPressDownTime[button] = timeNow;
                    }
                }

                // invoke event listeners
                for (ControllerButton button = 0; button < (ControllerButton)CONTROLLER_BUTTON_COUNT; ++button)
                {
                    if (GetPress(button))
                    {
                        if (GetPressDown(button))
                        {
                            // PressDown event
                            TryInvokeListener(button, ButtonEventType.Down);
                            TryInvokeTypeListener(button, ButtonEventType.Down);
                        }

                        // Press event
                        TryInvokeListener(button, ButtonEventType.Press);
                        TryInvokeTypeListener(button, ButtonEventType.Press);
                    }
                    else if (GetPressUp(button))
                    {
                        // PressUp event
                        TryInvokeListener(button, ButtonEventType.Up);
                        TryInvokeTypeListener(button, ButtonEventType.Up);

                        if (timeNow - lastPressDownTime[(int)button] < clickInterval)
                        {
                            // Click event
                            TryInvokeListener(button, ButtonEventType.Click);
                            TryInvokeTypeListener(button, ButtonEventType.Click);
                        }
                    }
                }

                return(false);
            }
    IEnumerator PerformFollowPath(List <Node> path)
    {
        int node = 1;

        while (node < path.Count)
        {
            if (!activated)
            {
                yield return(WaitFor.EndOfFrame);

                yield break;
            }

            if (!movingToTile)
            {
                if (tickRate != 0f)
                {
                    yield return(WaitFor.Seconds(tickRate));
                }

                var dir = path[node].position - Vector2Int.RoundToInt(transform.localPosition);
                if (!registerTile.Matrix.IsPassableAt(registerTile.LocalPositionServer + (Vector3Int)dir, true))
                {
                    var dC = registerTile.Matrix.GetFirst <DoorController>(
                        registerTile.LocalPositionServer + (Vector3Int)dir, true);
                    if (dC != null)
                    {
                        dC.MobTryOpen(gameObject);
                        yield return(WaitFor.Seconds(1f));
                    }
                    else
                    {
                        ResetMovingValues();
                        FollowCompleted();
                        Logger.Log("Path following timed out. Something must be in the way", Category.Movement);
                        yield break;
                    }
                }

                var angleOfDir = Vector2.Angle(dir, transform.up);
                if (dir.x < 0f)
                {
                    angleOfDir = -angleOfDir;
                }

                if (dirSprites != null)
                {
                    dirSprites.CheckSpriteServer(angleOfDir);
                }

                cnt.Push(dir);
                movingToTile = true;
            }
            else
            {
                if (arrivedAtTile)
                {
                    movingToTile  = false;
                    arrivedAtTile = false;
                    timeOut       = 0f;
                    node++;
                }
                else
                {
                    //Mob has 5 seconds to get to the next tile
                    //or the AI should do something else
                    timeOut += Time.deltaTime;
                    if (timeOut > 5f)
                    {
                        ResetMovingValues();
                        Logger.Log("Path following timed out. Something must be in the way", Category.Movement);
                        FollowCompleted();
                        yield break;
                    }
                }
            }

            yield return(WaitFor.EndOfFrame);
        }

        yield return(WaitFor.EndOfFrame);

        ResetMovingValues();
        FollowCompleted();
    }
Beispiel #4
0
        private void PopulateMesh(VertexHelper vh, Vector2[] pointsToDraw)
        {
            //If Bezier is desired, pick the implementation
            if (BezierMode != BezierType.None && BezierMode != BezierType.Catenary && pointsToDraw.Length > 3)
            {
                BezierPath bezierPath = new BezierPath();

                bezierPath.SetControlPoints(pointsToDraw);
                bezierPath.SegmentsPerCurve = bezierSegmentsPerCurve;
                List <Vector2> drawingPoints;
                switch (BezierMode)
                {
                case BezierType.Basic:
                    drawingPoints = bezierPath.GetDrawingPoints0();
                    break;

                case BezierType.Improved:
                    drawingPoints = bezierPath.GetDrawingPoints1();
                    break;

                default:
                    drawingPoints = bezierPath.GetDrawingPoints2();
                    break;
                }

                pointsToDraw = drawingPoints.ToArray();
            }
            if (BezierMode == BezierType.Catenary && pointsToDraw.Length == 2)
            {
                CableCurve cable = new CableCurve(pointsToDraw);
                cable.slack  = Resoloution;
                cable.steps  = BezierSegmentsPerCurve;
                pointsToDraw = cable.Points();
            }

            if (ImproveResolution != ResolutionMode.None)
            {
                pointsToDraw = IncreaseResolution(pointsToDraw);
            }

            // scale based on the size of the rect or use absolute, this is switchable
            var sizeX   = !relativeSize ? 1 : rectTransform.rect.width;
            var sizeY   = !relativeSize ? 1 : rectTransform.rect.height;
            var offsetX = -rectTransform.pivot.x * sizeX;
            var offsetY = -rectTransform.pivot.y * sizeY;

            // Generate the quads that make up the wide line
            var segments = new List <UIVertex[]> ();

            if (lineList)
            {
                for (var i = 1; i < pointsToDraw.Length; i += 2)
                {
                    var start = pointsToDraw [i - 1];
                    var end   = pointsToDraw [i];
                    start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY);
                    end   = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY);

                    if (lineCaps)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.Start));
                    }

                    segments.Add(CreateLineSegment(start, end, SegmentType.Middle, segments.Count > 1 ? segments[segments.Count - 2] : null));

                    if (lineCaps)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.End));
                    }
                }
            }
            else
            {
                for (var i = 1; i < pointsToDraw.Length; i++)
                {
                    var start = pointsToDraw [i - 1];
                    var end   = pointsToDraw [i];
                    start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY);
                    end   = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY);

                    if (lineCaps && i == 1)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.Start));
                    }

                    segments.Add(CreateLineSegment(start, end, SegmentType.Middle));

                    if (lineCaps && i == pointsToDraw.Length - 1)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.End));
                    }
                }
            }

            // Add the line segments to the vertex helper, creating any joins as needed
            for (var i = 0; i < segments.Count; i++)
            {
                if (!lineList && i < segments.Count - 1)
                {
                    var vec1  = segments [i] [1].position - segments [i] [2].position;
                    var vec2  = segments [i + 1] [2].position - segments [i + 1] [1].position;
                    var angle = Vector2.Angle(vec1, vec2) * Mathf.Deg2Rad;

                    // Positive sign means the line is turning in a 'clockwise' direction
                    var sign = Mathf.Sign(Vector3.Cross(vec1.normalized, vec2.normalized).z);

                    // Calculate the miter point
                    var miterDistance = lineThickness / (2 * Mathf.Tan(angle / 2));
                    var miterPointA   = segments [i] [2].position - vec1.normalized * miterDistance * sign;
                    var miterPointB   = segments [i] [3].position + vec1.normalized * miterDistance * sign;

                    var joinType = LineJoins;
                    if (joinType == JoinType.Miter)
                    {
                        // Make sure we can make a miter join without too many artifacts.
                        if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_MITER_JOIN)
                        {
                            segments [i] [2].position     = miterPointA;
                            segments [i] [3].position     = miterPointB;
                            segments [i + 1] [0].position = miterPointB;
                            segments [i + 1] [1].position = miterPointA;
                        }
                        else
                        {
                            joinType = JoinType.Bevel;
                        }
                    }

                    if (joinType == JoinType.Bevel)
                    {
                        if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_BEVEL_NICE_JOIN)
                        {
                            if (sign < 0)
                            {
                                segments [i] [2].position     = miterPointA;
                                segments [i + 1] [1].position = miterPointA;
                            }
                            else
                            {
                                segments [i] [3].position     = miterPointB;
                                segments [i + 1] [0].position = miterPointB;
                            }
                        }

                        var join = new UIVertex[] { segments [i] [2], segments [i] [3], segments [i + 1] [0], segments [i + 1] [1] };
                        vh.AddUIVertexQuad(join);
                    }
                }

                vh.AddUIVertexQuad(segments [i]);
            }
            if (vh.currentVertCount > 64000)
            {
                Debug.LogError("Max Verticies size is 64000, current mesh vertcies count is [" + vh.currentVertCount + "] - Cannot Draw");
                vh.Clear();
                return;
            }
        }
Beispiel #5
0
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            if (m_points == null)
            {
                return;
            }
            Vector2[] pointsToDraw = m_points;
            //If Bezier is desired, pick the implementation
            if (BezierMode != BezierType.None && m_points.Length > 3)
            {
                BezierPath bezierPath = new BezierPath();

                bezierPath.SetControlPoints(pointsToDraw);
                bezierPath.SegmentsPerCurve = BezierSegmentsPerCurve;
                List <Vector2> drawingPoints;
                switch (BezierMode)
                {
                case BezierType.Basic:
                    drawingPoints = bezierPath.GetDrawingPoints0();
                    break;

                case BezierType.Improved:
                    drawingPoints = bezierPath.GetDrawingPoints1();
                    break;

                default:
                    drawingPoints = bezierPath.GetDrawingPoints2();
                    break;
                }

                pointsToDraw = drawingPoints.ToArray();
            }

            var sizeX   = rectTransform.rect.width;
            var sizeY   = rectTransform.rect.height;
            var offsetX = -rectTransform.pivot.x * rectTransform.rect.width;
            var offsetY = -rectTransform.pivot.y * rectTransform.rect.height;

            // don't want to scale based on the size of the rect, so this is switchable now
            if (!relativeSize)
            {
                sizeX = 1;
                sizeY = 1;
            }

            if (UseMargins)
            {
                sizeX   -= Margin.x;
                sizeY   -= Margin.y;
                offsetX += Margin.x / 2f;
                offsetY += Margin.y / 2f;
            }

            vh.Clear();

            // Generate the quads that make up the wide line
            var segments = new List <UIVertex[]>();

            if (LineList)
            {
                for (var i = 1; i < pointsToDraw.Length; i += 2)
                {
                    var start = pointsToDraw[i - 1];
                    var end   = pointsToDraw[i];
                    start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY);
                    end   = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY);

                    if (LineCaps)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.Start));
                    }

                    segments.Add(CreateLineSegment(start, end, SegmentType.Middle));

                    if (LineCaps)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.End));
                    }
                }
            }
            else
            {
                for (var i = 1; i < pointsToDraw.Length; i++)
                {
                    var start = pointsToDraw[i - 1];
                    var end   = pointsToDraw[i];
                    start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY);
                    end   = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY);

                    if (LineCaps && i == 1)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.Start));
                    }

                    segments.Add(CreateLineSegment(start, end, SegmentType.Middle));

                    if (LineCaps && i == pointsToDraw.Length - 1)
                    {
                        segments.Add(CreateLineCap(start, end, SegmentType.End));
                    }
                }
            }

            // Add the line segments to the vertex helper, creating any joins as needed
            for (var i = 0; i < segments.Count; i++)
            {
                if (!LineList && i < segments.Count - 1)
                {
                    var vec1  = segments[i][1].position - segments[i][2].position;
                    var vec2  = segments[i + 1][2].position - segments[i + 1][1].position;
                    var angle = Vector2.Angle(vec1, vec2) * Mathf.Deg2Rad;

                    // Positive sign means the line is turning in a 'clockwise' direction
                    var sign = Mathf.Sign(Vector3.Cross(vec1.normalized, vec2.normalized).z);

                    // Calculate the miter point
                    var miterDistance = LineThickness / (2 * Mathf.Tan(angle / 2));
                    var miterPointA   = segments[i][2].position - vec1.normalized * miterDistance * sign;
                    var miterPointB   = segments[i][3].position + vec1.normalized * miterDistance * sign;

                    var joinType = LineJoins;
                    if (joinType == JoinType.Miter)
                    {
                        // Make sure we can make a miter join without too many artifacts.
                        if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_MITER_JOIN)
                        {
                            segments[i][2].position     = miterPointA;
                            segments[i][3].position     = miterPointB;
                            segments[i + 1][0].position = miterPointB;
                            segments[i + 1][1].position = miterPointA;
                        }
                        else
                        {
                            joinType = JoinType.Bevel;
                        }
                    }

                    if (joinType == JoinType.Bevel)
                    {
                        if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_BEVEL_NICE_JOIN)
                        {
                            if (sign < 0)
                            {
                                segments[i][2].position     = miterPointA;
                                segments[i + 1][1].position = miterPointA;
                            }
                            else
                            {
                                segments[i][3].position     = miterPointB;
                                segments[i + 1][0].position = miterPointB;
                            }
                        }

                        var join = new UIVertex[] { segments[i][2], segments[i][3], segments[i + 1][0], segments[i + 1][1] };
                        vh.AddUIVertexQuad(join);
                    }
                }

                vh.AddUIVertexQuad(segments[i]);
            }
        }
    void Update()
    {
        Vector2 dir = carMovement.GetDirection().normalized;

        dir    = new Vector2(Mathf.RoundToInt(dir.x), Mathf.RoundToInt(dir.y));
        delay -= Time.deltaTime;

        if (handleCollision.Key)
        {
            float distance = Vector2.Distance(Vector2.Scale(this.transform.position, dir)
                                              + Vector2.Scale(collisionOffsetNegative, new Vector2(dir.x < 0 ? -1 : 0, dir.y > 0 ? -1 : 0))
                                              + Vector2.Scale(collisionOffsetPositive, new Vector2(dir.x > 0 ? -1 : 0, dir.y < 0 ? -1 : 0)),
                                              Vector2.Scale(handleCollision.Value.transform.position, dir));

            if (distance < minDistanceToCollide)
            {
                for (int i = 0; i < objectsInGrid.Length; i++)
                {
                    CarGridObject obj = objectsInGrid[i];
                    if (obj == handleCollision.Value)
                    {
                        continue;
                    }

                    Vector2 direction = handleCollision.Value.useCustomDirection ? handleCollision.Value.customDirection : (Vector2)(Quaternion.Euler(0, 0, 90 * (cw ? -1 : 1)) * dir);
                    if ((obj.isObstacle && obj.objectType == CarGridObject.GridObjectType.Wall && ((obj.obstacleDirection.x == -direction.x && obj.obstacleDirection.x != 0) || (obj.obstacleDirection.y == -direction.y && obj.obstacleDirection.y != 0))))
                    {
                        handleCollision = new KeyValuePair <bool, CarGridObject>(true, obj);
                        return;
                    }
                }

                if (handleCollision.Value.useCustomDirection)
                {
                    if ((dir.x == -handleCollision.Value.customDirection.x && dir.x != 0) || (dir.y == -handleCollision.Value.customDirection.y && dir.y != 0))
                    {
                        cw = !cw;
                    }
                    dir = handleCollision.Value.customDirection;
                    carMovement.SetDirection(dir);
                    spriteRenderer.transform.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Sign(dir.x) * -Vector2.Angle(Vector2.up, dir)));
                    handleCollision = new KeyValuePair <bool, CarGridObject>(false, null);
                    return;
                }

                if (Vector2.Scale(dir, handleCollision.Value.obstacleDirection) == Vector2.zero)
                {
                    handleCollision = new KeyValuePair <bool, CarGridObject>(false, null);
                    return;
                }


                cw = (dir.x > 0 && handleCollision.Value.obstacleDirection.y <= 0) || (dir.y > 0 && handleCollision.Value.obstacleDirection.x > 0) || (dir.y < 0 && handleCollision.Value.obstacleDirection.x <= 0) ||
                     (dir.x < 0 && handleCollision.Value.obstacleDirection.y > 0);
                //cw = cw && Mathf.Sign(dir.x * handleCollision.Value.obstacleDirection.x == -1 ? -1 : 1) != ((handleCollision.Value.obstacleDirection.y*-dir.y == -1 ? -1 : 1)) ? true : cw;

                float value = cw ? -1 : 1;
                dir = Quaternion.Euler(0, 0, 90 * value) * dir;
                carMovement.SetDirection(dir);
                spriteRenderer.transform.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Sign(dir.x) * -Vector2.Angle(Vector2.up, dir)));
                handleCollision = new KeyValuePair <bool, CarGridObject>(false, null);
            }
        }

        if (carGridObject.xInGrid == savedX && carGridObject.yInGrid == savedY)
        {
            return;
        }

        savedX = carGridObject.xInGrid;
        savedY = carGridObject.yInGrid;

        objectsInGrid = carGridObject.grid.GetObjectsInCell(savedX, savedY).ToArray();

        for (int i = 0; i < objectsInGrid.Length; i++)
        {
            CarGridObject obj = objectsInGrid[i];

            if (obj.alwaysTrigger || (obj.isObstacle && ((obj.obstacleDirection.x != 0 || obj.obstacleDirection.y != 0) && (obj.obstacleDirection.x == -dir.x || obj.obstacleDirection.y == -dir.y))))
            {
                if (handleCollision.Key)
                {
                    handleCollision = new KeyValuePair <bool, CarGridObject>(true, obj.objectType > handleCollision.Value.objectType ? obj : handleCollision.Value);
                    continue;
                }
                handleCollision = new KeyValuePair <bool, CarGridObject>(true, obj);
                //if (obj.useCustomDirection)
            }
        }


        //if (delay <= 0 && ((onHWallCollision.Value && dir.x != 0) || (onVWallCollision.Value && dir.y != 0)))
        //{
        //    float value = ccw ? -1 : 1;
        //    dir = Quaternion.Euler(0, 0, 90 * value) * dir;
        //    carMovement.SetDirection(dir);
        //    spriteRenderer.transform.Rotate(new Vector3(0, 0, 90 * value));
        //    delay = 0.2f;
        //    for (int i = 0; i < collisions.Length; i++)
        //    {
        //        collisions[i].overriddenRayDirection = dir;
        //    }

        //    return;
        //}

        //if (onArrowCollision.Value && delay <= 0)
        //{
        //    ArrowChange arr = arrowEventCollision.impactOnPoints[0].collider.GetComponent<ArrowChange>();
        //    if (dir.x == -arr.direction.x || dir.y == -arr.direction.y)
        //    {
        //        ccw = !ccw;
        //    }
        //    dir = arr.direction; //Quaternion.Euler(0, 0, 90) * dir;
        //    carMovement.SetDirection(dir);
        //    spriteRenderer.transform.rotation = Quaternion.AngleAxis(0, dir);
        //    delay = 0.2f;

        //    for (int i = 0; i < collisions.Length; i++)
        //    {
        //        collisions[i].overriddenRayDirection = dir;
        //    }
        //    return;
        //}
    }
Beispiel #7
0
        private void verticalCollision(ref Vector3 velocity)
        {
            float directionY = Mathf.Sign(velocity.y);
            float rayLength  = Mathf.Abs(velocity.y) + Raycaster.c_SkinWidth;

            for (int i = 0; i < m_Raycaster.VerticalRayCount; i++)
            {
                Vector2 rayOrigin = (directionY == -1) ? m_Raycaster.Origins.BottomLeft : m_Raycaster.Origins.TopLeft;

                // offset horizontal direction to precise detection
                rayOrigin += Vector2.right * (m_Raycaster.VerticalRaySpacing * i + velocity.x);
                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, m_Raycaster.CollisionLayer);

                Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.yellow);

                if (hit)
                {
                    if (hit.collider.CompareTag("OneWayPlatform"))
                    {
                        if (directionY == 1 || hit.distance == 0)
                        {
                            continue;
                        }

                        if (m_IsFallingThrough)
                        {
                            continue;
                        }
                    }

                    // change velocity y so it stops at the hit point
                    velocity.y = (hit.distance - Raycaster.c_SkinWidth) * directionY;
                    rayLength  = hit.distance;

                    if (m_CollisionInfo.ClimbingSlope)
                    {
                        velocity.x =
                            velocity.y / Mathf.Tan(m_CollisionInfo.Curr_SlopeAngle * Mathf.Deg2Rad);
                    }

                    setBelow(directionY == -1, hit.normal);
                    setAbove(directionY == 1, hit.normal);
                }
            }

            // to check if there is a new slope
            if (m_CollisionInfo.ClimbingSlope)
            {
                float directionX = Mathf.Sign(velocity.x);
                rayLength = Math.Abs(velocity.x) + Raycaster.c_SkinWidth;
                Vector2 rayOrigin = ((directionX == -1) ? m_Raycaster.Origins.BottomLeft : m_Raycaster.Origins.BottomRight) +
                                    Vector2.up * velocity.y;

                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, m_Raycaster.CollisionLayer);

                if (hit)
                {
                    float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                    if (slopeAngle != m_CollisionInfo.Curr_SlopeAngle)
                    {
                        //Debug.Log("New slope");
                        velocity.x = (hit.distance - Raycaster.c_SkinWidth) * directionX;
                        m_CollisionInfo.Curr_SlopeAngle = slopeAngle;
                    }
                }
            }
        }
Beispiel #8
0
    // Update is called once per frame
    void Update()
    {
        if (gameObject.GetComponent <ShipController>().rocketExists)
        {
            Vector2 rocketVector2 = new Vector2(SC.rocketModel.transform.position.x - SC.earth.transform.position.x, SC.rocketModel.transform.position.y - SC.earth.transform.position.y);
            Vector2 spawnVector2  = new Vector2(Spawnpoint.position.x - -SC.earth.transform.position.x, Spawnpoint.transform.position.y - -SC.earth.transform.position.y);
            rocketObjectiveAngle = Vector2.Angle(rocketVector2, spawnVector2);
        }



        if (textFade)
        {
            alpha = Mathf.Lerp(alpha, 1, 0.035f);
            missionAccomplishTextMat.SetColor("_FaceColor", new Color(1f, 1f, 1f, alpha));
        }
        else
        {
            alpha = Mathf.Lerp(alpha, 0, 0.035f);
            missionAccomplishTextMat.SetColor("_FaceColor", new Color(1f, 1f, 1f, alpha));
        }
        if (textFade2)
        {
            alpha2 = Mathf.Lerp(alpha2, 1, 0.025f);
            tutorialTextMat.SetColor("_FaceColor", new Color(1f, 1f, 1f, alpha2));
        }
        else
        {
            alpha2 = Mathf.Lerp(alpha2, 0, 0.035f);
            tutorialTextMat.SetColor("_FaceColor", new Color(1f, 1f, 1f, alpha2));
        }

        if (!playOnce2 && !SC.refueling && !SC.hasCrashed && startMission)
        {
            playOnce2 = true;
            StartCoroutine(FadeToolTip());
        }

        if (SC.rocketExists && startMission)
        {
            if (WayPointTarget_1 != null)
            {
                if (!WayPoint_1)
                {
                    //scoreText.text = "Fly to Waypoint";
                }

                if (rocketObjectiveAngle > 170 && !playOnce)
                {
                    WayPoint_1 = true;
                    playOnce   = true;
                    StartCoroutine(DisableDelayed(WayPointTarget_1.gameObject));
                    WayPointTarget_2.gameObject.SetActive(true);
                    StartCoroutine(ChangeText(missionAccomplished, "Land Safely"));
                }
            }

            if (WayPointTarget_2 != null && startMission && WayPoint_1)
            {
                if ((WayPointTarget_2.position - SC.rocketModel.transform.position).magnitude < 0.7f && !WayPoint_2)
                {
                    if (SC.FuelPercentage == 1 && !checking && SC.hasLanded && WayPoint_1)
                    {
                        StartCoroutine(SafetyCheck());
                    }
                    if (safetyCheck)
                    {
                        if (!playOnce3)
                        {
                            WayPoint_2 = true;
                            playOnce3  = true;
                            StartCoroutine(DisableDelayed(WayPointTarget_2.gameObject));
                        }
                        if (WayPoint_1 && WayPoint_2 && !levelCompleted)
                        {
                            StartCoroutine(ChangeText(missionAccomplished, "Mission Accomplished"));
                            levelCompleted      = true;
                            SC.zoomLevel        = 5;
                            SC.boosterEnabled   = false;
                            SC.missionCompleted = true;
                        }
                    }
                }
            }
        }
        else
        {
            if (!levelCompleted)
            {
                WayPointTarget_1.gameObject.SetActive(true);
                WayPoint_2 = false;
                WayPointTarget_2.gameObject.SetActive(false);
                WayPoint_1  = false;
                checking    = false;
                safetyCheck = false;
                playOnce    = false;
                playOnce3   = false;
            }
        }

        if (Input.GetKey(KeyCode.Mouse1) && zoomCheck)
        {
            StartCoroutine(LaserCheck());
        }

        if (gameObject.GetComponent <ShipController>().FuelPercentage == 0 && !gameObject.GetComponent <ShipController>().hasCrashed&& !gameObject.GetComponent <ShipController>().selfDestruct)
        {
            if (Input.GetKey(KeyCode.Mouse0) && Input.GetKey(KeyCode.Mouse1))
            {
                selfdestructTImer -= Time.deltaTime;
                tutorialText.text  = Mathf.RoundToInt(selfdestructTImer).ToString();
                if (selfdestructTImer < 0.5f)
                {
                    textFade2 = false;
                    gameObject.GetComponent <ShipController>().selfDestruct = true;
                }
            }
            else if (!gameObject.GetComponent <ShipController>().selfDestruct)
            {
                selfdestructTImer = 3.45f;
                tutorialText.text = "(Hold Right + Left Mouse) = Selfdestruct";
                textFade2         = true;
            }
        }

        if (gameObject.GetComponent <ShipController>().hasCrashed&& !Input.GetKey(KeyCode.Mouse0))
        {
            tutorialText.text = "(Hold Right Mouse) = Respawn";
            textFade2         = true;
            textFade          = false;
            WayPoint_1        = false;
        }
        else if (gameObject.GetComponent <ShipController>().respawning&& laserCheck)
        {
            textFade2 = false;
            textFade  = true;
            missionAccomplished.text = "Orbit the Planet";
        }
    }
Beispiel #9
0
    // Update is called once per frame
    void Update()
    {
        foodAmount -= hungerRate * Time.deltaTime;
        if (foodAmount <= 0)
        {
            Die();
        }
        distanceTraveled = Mathf.Max(distanceTraveled, transform.position.x);
        maxDist          = maxPower / distPowerRatio;
        if (checkGround)
        {
            onGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
        }
        if (timesJumped > 0 && onGround)
        {
            timesJumped = 0;
        }
        anim.SetBool("onGround", onGround);
        canJump = timesJumped < numJumps;
        if (!onGround)
        {
            glideAngle = Mathf.Deg2Rad * Vector2.Angle
                             (rigidbody2D.velocity.normalized, new Vector2(rigidbody2D.velocity.x, 0));
        }

/*
 #if UNITY_EDITOR
 *                      canJump = true;
 #endif
 */
        anim.SetBool("gliding", false);
        //start jump calc
        if (Input.GetMouseButton(0) && canJump)
        {
            dragBall.GetComponent <SpriteRenderer>().enabled = true;
            ballMove.x = Input.GetAxis("Mouse X");
            ballMove.y = Input.GetAxis("Mouse Y");
            dragBall.transform.localPosition += ballMove * aimSensitivity;
            dragBall.transform.localPosition  = Vector3.ClampMagnitude(dragBall.transform.localPosition, maxDist);
            Vector3 nextVel = ((transform.position - dragBall.position) * distPowerRatio);
            predictor.enabled = true;
            UpdatePredictions(transform.position, nextVel, 5, predictionResolution);
            //perform jump
        }
        else if (Input.GetMouseButtonUp(0) && canJump)
        {
            dragBall.GetComponent <SpriteRenderer>().enabled = false;
            //fire the frog
            rigidbody2D.velocity             = ((transform.position - dragBall.position) * distPowerRatio);
            dragBall.transform.localPosition = Vector3.zero;
            predictor.enabled = false;
            if (timesJumped == 0)
            {
                onGround    = false;
                checkGround = false;
                StartCoroutine(Timers.Countdown(0.1f, delegate() { checkGround = true; }));
            }
            timesJumped++;
            //gliding
        }
        else if (canGlide && Input.GetMouseButton(0) && !onGround && rigidbody2D.velocity.y < 0)
        {
            Vector2 liftDir = Quaternion.AngleAxis(90, Vector3.forward) * rigidbody2D.velocity.normalized;
            Debug.DrawLine(transform.position, transform.position + new Vector3(liftDir.x, liftDir.y));
            Debug.DrawLine(transform.position, transform.position + new Vector3(rigidbody2D.velocity.x, rigidbody2D.velocity.y).normalized, Color.red);
            rigidbody2D.velocity += Time.deltaTime * Mathf.Clamp(glideCoef * Mathf.Cos(glideAngle) / Mathf.Sin(glideAngle), 0, glideCoef * 10) * liftDir;
            rigidbody2D.velocity -= rigidbody2D.velocity * dragCoef * Time.deltaTime;
            anim.SetBool("gliding", true);
            //mouth stuff
        }
        else if (Input.GetMouseButtonDown(1) && mouth.CanActivate())
        {
            mouth.DoAvailableMouthAction();
        }
    }
        // Find the next selectable object in the specified world-space direction.
        public static Selectable FindNextSelectable(Selectable selectable, Transform transform, Vector3 direction)
        {
            RectTransform rectTransform = transform as RectTransform;

            if (rectTransform == null)
            {
                return(null);
            }

            IList <Selectable> allSelectables;
            int selectableCount;

#if UNITY_2019_PLUS
            // Resize array as needed to fit all Selectables
            if (Selectable.allSelectableCount > s_reusableAllSelectables.Length)
            {
                s_reusableAllSelectables = new Selectable[Selectable.allSelectableCount];
            }
            selectableCount = Selectable.AllSelectablesNoAlloc(s_reusableAllSelectables);
            allSelectables  = s_reusableAllSelectables;
#else
            allSelectables  = Selectable.allSelectables;
            selectableCount = allSelectables.Count;
#endif

            direction.Normalize();

            Vector2 localDir       = direction;
            Vector2 searchStartPos = Rewired.UI.ControlMapper.UITools.GetPointOnRectEdge(rectTransform, localDir); // search from point on rect edge from center out in direction
            bool    isHoriz        = localDir == Vector2.right * -1f || localDir == Vector2.right;

            float      minCenterDistSqMag = Mathf.Infinity;
            float      minDirectLineSqMag = Mathf.Infinity;
            Selectable bestCenterDistPick = null;
            Selectable bestDirectLinePick = null;

            const float length = 999999f; // Mathf.Infinity fails
            Vector2     directLineCastEndPos = searchStartPos + localDir * length;

            for (int i = 0; i < selectableCount; ++i)
            {
                Selectable targetSelectable = allSelectables[i];

                if (targetSelectable == selectable || targetSelectable == null)
                {
                    continue;                                                            // skip if self or null
                }
                if (targetSelectable.navigation.mode == Navigation.Mode.None)
                {
                    continue;                                                          // skip if non-navigable
                }
                // Allow selection of non-interactable elements because it makes navigating easier and more predictable
                // but the CanvasGroup interactable value is private in Selectable
#if !UNITY_WSA
                // Reflect to get group intaractability if non-interactable
                bool canvasGroupAllowsInteraction = targetSelectable.IsInteractable() || Rewired.Utils.ReflectionTools.GetPrivateField <Selectable, bool>(targetSelectable, "m_GroupsAllowInteraction");
                if (!canvasGroupAllowsInteraction)
                {
                    continue;                               // skip if disabled by canvas group, otherwise allow it
                }
#else
                // Can't do private field reflection in Metro
                if (!targetSelectable.IsInteractable())
                {
                    continue;                                    // skip if disabled
                }
#endif

                var targetSelectableRectTransform = targetSelectable.transform as RectTransform;
                if (targetSelectableRectTransform == null)
                {
                    continue;
                }

                // Check direct line cast from center edge of object in direction pressed
                float directLineSqMag;
                Rect  targetSelecableRect = UITools.InvertY(UITools.TransformRectTo(targetSelectableRectTransform, transform, targetSelectableRectTransform.rect));

                // Check for direct line rect intersection
                if (Rewired.Utils.MathTools.LineIntersectsRect(searchStartPos, directLineCastEndPos, targetSelecableRect, out directLineSqMag))
                {
                    if (isHoriz)
                    {
                        directLineSqMag *= 0.25f;         // give extra bonus to horizontal directions because most of the UI groups are laid out horizontally
                    }
                    if (directLineSqMag < minDirectLineSqMag)
                    {
                        minDirectLineSqMag = directLineSqMag;
                        bestDirectLinePick = targetSelectable;
                    }
                }

                // Check distance to center
                Vector2 targetSelectableCenter            = Rewired.Utils.UnityTools.TransformPoint(targetSelectableRectTransform, transform, targetSelectableRectTransform.rect.center);
                Vector2 searchPosToTargetSelectableCenter = targetSelectableCenter - searchStartPos;

                const float maxSafeAngle = 75.0f;

                // Get the angle the target center deviates from straight
                float angle = Mathf.Abs(Vector2.Angle(localDir, searchPosToTargetSelectableCenter));

                if (angle > maxSafeAngle)
                {
                    continue;                      // only consider if within a reasonable angle of the desired direction
                }
                float score = searchPosToTargetSelectableCenter.sqrMagnitude;

                // Lower score is better
                if (score < minCenterDistSqMag)
                {
                    minCenterDistSqMag = score;
                    bestCenterDistPick = targetSelectable;
                }
            }

            // Choose between direct line and center dist
            if (bestDirectLinePick != null && bestCenterDistPick != null)
            {
                if (minDirectLineSqMag > minCenterDistSqMag)
                {
                    return(bestCenterDistPick);
                }
                return(bestDirectLinePick);
            }

#if UNITY_2019_PLUS
            System.Array.Clear(s_reusableAllSelectables, 0, s_reusableAllSelectables.Length);
#endif

            return(bestDirectLinePick ?? bestCenterDistPick);
        }
Beispiel #11
0
    void Update()
    {
        if (hasExploded)
        {
            return;
        }

        float horizontal = joystick.Horizontal;
        float vertical   = joystick.Vertical;

        Vector2 vec       = new Vector2(horizontal, vertical);
        float   magnitude = vec.magnitude;

        vec.Normalize();

        // Up boosting movement
        if (magnitude > 0)
        {
            rb2d.velocity = new Vector2(transform.up.x * vec.magnitude * speed, transform.up.y * vec.magnitude * speed * 1.1f);
            //rb2d.velocity = new Vector2(vec.x * speed, vec.y * speed);

            tr.enabled = true;

            if (!engineSparkPlayed) // Hard to hear, probably just ignore this
            {
                audioSource.PlayOneShot(engineSpark, 1.0f);
                engineSparkPlayed = true;
            }
            audioSource.volume = 0.1f;

            // Drain fuel
            currentFuel -= fuelRate * Time.deltaTime;
            if (currentFuel <= 0)
            {
                currentFuel = 0;
                Explode();
            }
        }
        else
        {
            tr.Clear();
            tr.enabled = false;

            audioSource.volume = 0.0f;
            engineSparkPlayed  = false;
        }

        // Left right tilt movement
        if (horizontal != 0)
        {
            float angle = Vector2.Angle(vec, transform.up);

            Quaternion target = Quaternion.FromToRotation(Vector2.up, vec);
            if ((transform.up.y < 0 && vec.y >= 0) || (transform.up.y >= 0 && vec.y < 0))
            {
                target.eulerAngles = new Vector4(target.eulerAngles.x, target.eulerAngles.y, target.eulerAngles.z + Mathf.PI * 3 / 2);
            }
            //if ((transform.up.y > 0 && vec.y < 0) || (transform.up.y <= 0 && vec.y >= 0)) target = Quaternion.FromToRotation(transform.up * -1, vec * -1);
            //else target = Quaternion.FromToRotation(transform.up, vec);
            transform.rotation = Quaternion.Lerp(transform.rotation, target, tiltSpeed * Time.deltaTime);

            //    Old stuff
            //transform.Rotate(0.0f, 0.0f, -horizontal * tiltSpeed, Space.Self);
        }

        //float currAngle = transform.rotation.z;
        //Debug.Log("currangle = " + currAngle.ToString());

        //float newAngle = Vector2.Angle(transform.up, vec);
        //if (horizontal > 0)
        //{
        //    newAngle *= -1;
        //}
        //Debug.Log("newAngle = " + newAngle.ToString());

        //transform.Rotate(0.0f, 0.0f, newAngle, Space.Self);

        //Quaternion target = Quaternion.FromToRotation(transform.up, vec);
        //transform.rotation = Quaternion.Lerp(transform.rotation, target, tiltSpeed * Time.deltaTime);

        // Old stuff
        //transform.Rotate(0.0f, 0.0f, -horizontal * tiltSpeed, Space.World);


        // Screen wrapping
        WrapXPosition();
        if (transform.position.x > X_LIMIT + 0.3f || transform.position.x < -X_LIMIT - 0.3f)
        {
            tr.Clear();
            tr.enabled = false;
        }

        // Smoke particles if fuel < 30%
        if (currentFuel < 30f)
        {
            if (smokeParticles.isStopped)
            {
                smokeParticles.Play();
            }
        }
        else if (currentFuel >= 30f)
        {
            if (smokeParticles.isPlaying)
            {
                smokeParticles.Stop();
            }
        }

        // Set fuel amount
        fuelBar.SetFuelAmount(currentFuel);
    }
Beispiel #12
0
        public static float AngleSigned(this Vector2 a, Vector2 b)
        {
            var sign = Mathf.Sign(a.x * b.y - a.y * b.x);

            return(Vector2.Angle(a, b) * sign);
        }
    // Update is called once per frame
    void Update()
    {
        /*//mobile input stuff
         * float smooth = 1, sensV = 1, sensH = 1;
         * CurAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);
         * GetAxisV = Mathf.Clamp(curAc.y * sensV, -1, 1);
         * GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);*/

        float previousAngle = transform.rotation.eulerAngles.z;

        myVelocity = gameObject.GetComponent <Rigidbody2D>().velocity;       //Gets our current velocity, used for sound, and speed checks
        float currentSpeed = myVelocity.magnitude;

        //Analog Rotating stuff
        if (directionShootingJoystick.Vertical() < 0)           //Checks if the shoot analog/keys has negative vertial direction. If so, a negative rotation is applied (ask Ben if needed).
        {
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, Quaternion.AngleAxis(
                    -Vector2.Angle(Vector2.right, new Vector2(directionShootingJoystick.Horizontal(), directionShootingJoystick.Vertical())) - 90f,
                    Vector3.forward),
                rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*/);
        }
        else if (directionShootingJoystick.Vertical() != 0 || directionShootingJoystick.Horizontal() != 0)             //Checks if the shoot analog/keys is in use in any other direction
        {
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, Quaternion.AngleAxis(
                    Vector2.Angle(Vector2.right, new Vector2(directionShootingJoystick.Horizontal(), directionShootingJoystick.Vertical())) - 90f,
                    Vector3.forward),
                rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*/);
        }
        else if (movementJoystick.Vertical() < 0)              //Checks if the move analog/keys has negative vertial direction. If so, a negative rotation is applied (ask Ben if needed).
        {
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, Quaternion.AngleAxis(
                    -Vector2.Angle(Vector2.right, new Vector2(movementJoystick.Horizontal(), movementJoystick.Vertical())) - 90f,
                    Vector3.forward),
                rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*/);
        }
        else if (movementJoystick.Vertical() != 0 || movementJoystick.Horizontal() != 0)              //Checks if the move analog/keys is in use in any other direction
        {
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, Quaternion.AngleAxis(
                    Vector2.Angle(Vector2.right, new Vector2(movementJoystick.Horizontal(), movementJoystick.Vertical())) - 90f,
                    Vector3.forward),
                rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*/);
        }

        //Should ship also start shooting?
        if (directionShootingJoystick.Vertical() != 0 || directionShootingJoystick.Horizontal() != 0)
        {
            gameObject.GetComponent <Shoot> ().startShooting();
        }

        /*//This is purely a control for PC/Mac. It checks keyboard input at the same time so it only works to shoot as you move, but doesn't work on mobile touch screens
         * else if (Input.GetMouseButton (0) && (Input.GetKey (KeyCode.W) || Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.D))) {//Mouse control for pc/mac where mouse is used to aim and shoot
         *
         *      gameObject.GetComponent<Shoot> ().startShooting ();
         *
         *      Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
         *      Vector2 mouseRelativePos = new Vector2 (mouseWorldPos.x - transform.position.x, mouseWorldPos.y - transform.position.y);
         *
         *      if (mouseRelativePos.y > 0) {
         *              transform.rotation = Quaternion.RotateTowards (
         *                      transform.rotation, Quaternion.AngleAxis (
         *                      Vector2.Angle (Vector2.right, new Vector2 (mouseRelativePos.x, mouseRelativePos.y)) - 90f,
         *                      Vector3.forward),
         *                      rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*//*);
         *      } else {
         *              transform.rotation = Quaternion.RotateTowards (
         *                      transform.rotation, Quaternion.AngleAxis (
         *                      -Vector2.Angle (Vector2.right, new Vector2 (mouseRelativePos.x, mouseRelativePos.y)) - 90f,
         *                      Vector3.forward),
         *                      rotationSpeed * (Time.deltaTime * 60) /* (1.3f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude), 0.3f, 1f))*//*);
         *      }
         * }*/else
        {
            gameObject.GetComponent <Shoot> ().stopShooting();            //As the shoot analog wasn't in use, don't shoot
        }



        //Zero all the thrusters
        theParticleSystem                       = rightThruster.GetComponent <ParticleSystem> ().emission;
        theParticleSystemsRateCurve             = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax = 0;
        theParticleSystem.rate                  = theParticleSystemsRateCurve;

        theParticleSystem                       = leftThruster.GetComponent <ParticleSystem> ().emission;
        theParticleSystemsRateCurve             = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax = 0;
        theParticleSystem.rate                  = theParticleSystemsRateCurve;

        //Increase particles to front thrusts
        theParticleSystem                       = rightFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve             = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax = 0;
        theParticleSystem.rate                  = theParticleSystemsRateCurve;

        theParticleSystem                       = leftFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve             = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax = 0;
        theParticleSystem.rate                  = theParticleSystemsRateCurve;
        //All thrusters are now zeroed

        float newAngle = transform.rotation.eulerAngles.z;

        float rotationAmount = newAngle - previousAngle;

        if (rotationAmount > 0)
        {
            //Increase particles to rear thrusts
            theParticleSystem                       = rightThruster.GetComponent <ParticleSystem> ().emission;
            theParticleSystemsRateCurve             = theParticleSystem.rate;
            theParticleSystemsRateCurve.constantMax = 100;
            theParticleSystem.rate                  = theParticleSystemsRateCurve;

            theParticleSystem                       = leftFrontThrust.GetComponent <ParticleSystem>().emission;
            theParticleSystemsRateCurve             = theParticleSystem.rate;
            theParticleSystemsRateCurve.constantMax = 100;
            theParticleSystem.rate                  = theParticleSystemsRateCurve;
        }
        else if (rotationAmount < 0)
        {
            theParticleSystem                       = leftThruster.GetComponent <ParticleSystem> ().emission;
            theParticleSystemsRateCurve             = theParticleSystem.rate;
            theParticleSystemsRateCurve.constantMax = 100;
            theParticleSystem.rate                  = theParticleSystemsRateCurve;

            //Increase particles to front thrusts
            theParticleSystem                       = rightFrontThrust.GetComponent <ParticleSystem>().emission;
            theParticleSystemsRateCurve             = theParticleSystem.rate;
            theParticleSystemsRateCurve.constantMax = 100;
            theParticleSystem.rate                  = theParticleSystemsRateCurve;
        }


        //Movement and sound
        Vector2 moveAngleInput = new Vector2(movementJoystick.Horizontal(), movementJoystick.Vertical());
        //Vector2 myVelocity = gameObject.GetComponent<Rigidbody2D>().velocity;//Gets our current velocity, used for sound, and speed checks


        float thrustMagnitude = moveAngleInput.magnitude;        //This is just for sound

        //float percentOfThrustFromRear = (180 - Mathf.Abs(Vector2.Angle (Vector2.right, new Vector2 (transform.up.x,transform.up.y)) - Vector2.Angle (Vector2.right, new Vector2 (movementJoystick.Horizontal (), movementJoystick.Vertical ())))) / 180;
        thrusterSound.pitch  = thrusterIdlePitch + myVelocity.magnitude / 30 + (thrustMagnitude / 3);        //Increase pitch a bit more for faster sound
        thrusterSound.volume = thrusterIdleVolume + myVelocity.magnitude / 100 + (thrustMagnitude / 3);

        //This works good as well
        //velocityToAdd += moveAngleInput * (((180 - angleDifference) / 360) + 0.5f);



        //angle of analog from nose
        angleDifference = (Vector2.Angle(moveAngleInput, new Vector2(transform.up.x, transform.up.y)));

        if (angleDifference < 90)
        {
            //Increases speed limit when going forward
            speedLimitToUse = Mathf.Clamp(strafeAndReverseSpeedLimit + ((forwardSpeedLimit - strafeAndReverseSpeedLimit) * (1 - angleDifference / 90)), currentSpeed, forwardSpeedLimit);

            //Add velocity for forward movement, using accerlation curve
            velocityToAdd += (moveAngleInput * (1 - angleDifference / 90) * forwardAccel * Time.deltaTime) * (1.5f - Mathf.Clamp((currentSpeed / forwardSpeedLimit - 4), 0.5f, 1f));
        }
        else
        {
            speedLimitToUse = Mathf.Clamp(strafeAndReverseSpeedLimit, currentSpeed, forwardSpeedLimit);
        }

        speedLimitToUse *= (1 - percentageFrostSlow);

        //Debug.Log (currentSpeed);

        //Inrcase velocity in move direction accordingly

        //Limit magnitude based on newly calculated top speed


        /*
         * //Try to apply some amount forward velocity
         * angleDifference = ( Vector2.Angle (moveAngleInput, new Vector2 (transform.up.x, transform.up.y)));
         * if (angleDifference < 90) {
         *
         *      //velocity to add is here
         *      velocityToCheck = moveAngleInput * (1 - angleDifference / 90) * forwardAccel * Time.deltaTime;
         *      velocityToCheck *= 1.5f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude - 4), 0.5f, 1f);//Better working one
         *
         *      //float currentSpeed = myVelocity.y * -transform.up.y + myVelocity.x * -transform.up.x;
         *      float newSpeed = (myVelocity.y + velocityToCheck.y) * transform.up.y + (myVelocity.x + velocityToCheck.x) * transform.up.x;
         *
         *      //Don't add it if it puts you over the speed limit
         *      if (newSpeed < forwardSpeedLimit * (1 - angleDifference / 90)) {
         *              velocityToAdd += velocityToCheck;
         *      }
         * }
         */

        //Increase particles to rear thrusts
        theParticleSystem                        = rightThruster.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 300);
        theParticleSystem.rate                   = theParticleSystemsRateCurve;

        theParticleSystem                        = leftThruster.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 300);
        theParticleSystem.rate                   = theParticleSystemsRateCurve;

        /*
         * //Try to apply some amount of backward velocity
         * angleDifference = ( Vector2.Angle (moveAngleInput, new Vector2 (-transform.up.x, -transform.up.y)));
         * if (angleDifference < 90) {
         *
         *      velocityToCheck = /*-transform.up*//* moveAngleInput * (1 - angleDifference / 90) * backwardAccel * Time.deltaTime;
         *
         *      //float currentSpeed = myVelocity.y * -transform.up.y + myVelocity.x * -transform.up.x;
         *      float newSpeed = (myVelocity.y + velocityToCheck.y) * -transform.up.y + (myVelocity.x + velocityToCheck.x) * -transform.up.x;
         *
         *      //Don't add it if it puts you over the speed limit
         *      if (newSpeed < backwardSpeedLimit * (1 - angleDifference / 90)) {
         *              velocityToAdd += velocityToCheck;
         *      }
         * }*/

        angleDifference = (Vector2.Angle(moveAngleInput, new Vector2(-transform.up.x, -transform.up.y)));
        if (angleDifference < 90)
        {
            velocityToAdd += moveAngleInput * (1 - angleDifference / 90) * backwardAccel * Time.deltaTime;
        }

        //Increase particles to front thrusts
        theParticleSystem                        = rightFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 50) + 0;
        theParticleSystem.rate                   = theParticleSystemsRateCurve;

        theParticleSystem                        = leftFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 50) + 0;
        theParticleSystem.rate                   = theParticleSystemsRateCurve;


        /*
         * //Try to apply some amount of rightward velocity
         * angleDifference = ( Vector2.Angle (moveAngleInput, new Vector2 (transform.right.x, transform.right.y)));
         * if (angleDifference < 90) {
         *
         *      velocityToCheck = moveAngleInput * (1 - angleDifference / 90) * strafeAccel * Time.deltaTime;
         *
         *      //float currentSpeed = myVelocity.y * transform.right.y + myVelocity.x * transform.right.x;
         *      float newSpeed = (myVelocity.y + velocityToCheck.y) * transform.right.y + (myVelocity.x + velocityToCheck.x) * transform.right.x;
         *
         *      //Don't add it if it puts you over the speed limit
         *      if (newSpeed < strafeSpeedLimit * (1 - angleDifference / 90)) {
         *              velocityToAdd += velocityToCheck;
         *      }
         * }*/

        angleDifference = (Vector2.Angle(moveAngleInput, new Vector2(transform.right.x, transform.right.y)));
        if (angleDifference < 90)
        {
            velocityToAdd += moveAngleInput * (1 - angleDifference / 90) * strafeAccel * Time.deltaTime;
        }

        theParticleSystem                        = leftFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 50) + 0;
        theParticleSystem.rate                   = theParticleSystemsRateCurve;

        /*
         * //Try to apply some amount of leftward velocity
         * angleDifference = ( Vector2.Angle (moveAngleInput, new Vector2 (-transform.right.x, -transform.right.y)));
         * if (angleDifference < 90) {
         *
         *      velocityToCheck = moveAngleInput * (1 - angleDifference / 90) * strafeAccel * Time.deltaTime;
         *
         *      //float currentSpeed = myVelocity.y * -transform.right.y + myVelocity.x * -transform.right.x;
         *      float newSpeed = (myVelocity.y + velocityToCheck.y) * -transform.right.y + (myVelocity.x + velocityToCheck.x) * -transform.right.x;
         *      //Debug.Log (newSpeed);
         *      //Don't add it if it puts you over the speed limit
         *      if (newSpeed < strafeSpeedLimit * (1 - angleDifference / 90)) {
         *              velocityToAdd += velocityToCheck;
         *      }
         * }*/

        angleDifference = (Vector2.Angle(moveAngleInput, new Vector2(-transform.right.x, -transform.right.y)));
        if (angleDifference < 90)
        {
            velocityToAdd += moveAngleInput * (1 - angleDifference / 90) * strafeAccel * Time.deltaTime;
        }

        //Increase particles to front right thrusts
        theParticleSystem                        = rightFrontThrust.GetComponent <ParticleSystem>().emission;
        theParticleSystemsRateCurve              = theParticleSystem.rate;
        theParticleSystemsRateCurve.constantMax += ((1 - angleDifference / 90) * 50) + 0;
        theParticleSystem.rate                   = theParticleSystemsRateCurve;


        //IMPROVE
        //Ship accelerates slower at speed, similar to a plane
        //Debug.Log(1.0f - (myVelocity.magnitude / maxSpeedMagnitude));

        //velocityToAdd *= 1.5f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude - 4), 0.5f, 1f);//Old one
        //velocityToAdd *= 1.5f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude - 4), 0.5f, 1f);//Better working one

        //velocityToAdd *= 2f - Mathf.Clamp( (myVelocity.magnitude  / maxSpeedMagnitude) * 1.5f, 1f, 1.5f);//Other decent alternative

        //Slow acceleration
        velocityToAdd *= (1 - percentageFrostSlow);

        gameObject.GetComponent <Rigidbody2D> ().velocity += velocityToAdd;       //Add the velocity
        //Debug.Log (gameObject.GetComponent<Rigidbody2D> ().velocity.magnitude);

        velocityToAdd = Vector2.zero;        //Reset the velocity to add value, ready for the next update

        //If the ship's velocity is above the max speed, it is reduced to the max speed instead.
        if (gameObject.GetComponent <Rigidbody2D> ().velocity.magnitude > /*maxSpeedMagnitude*/ speedLimitToUse)
        {
            gameObject.GetComponent <Rigidbody2D> ().velocity = gameObject.GetComponent <Rigidbody2D> ().velocity.normalized *speedLimitToUse;
        }

        //Debug.Log (gameObject.GetComponent<Rigidbody2D> ().velocity.magnitude);

        //UNSURE

        /*if (gameObject.GetComponent<Rigidbody2D> ().velocity.magnitude < 10f && moveAngleInput.magnitude < 0.5f) {
         *      gameObject.GetComponent<Rigidbody2D> ().drag = originalDrag + (1 - (gameObject.GetComponent<Rigidbody2D> ().velocity.magnitude / 10)) * 1.2f;
         *      //gameObject.GetComponent<Rigidbody2D> ().drag = originalDrag + 1;
         * } else
         *      gameObject.GetComponent<Rigidbody2D> ().drag = originalDrag;
         */


        /*//stuff for recharging boost
         * remainingBoostRechargeDelay -= Time.deltaTime;
         * if (remainingBoostRechargeDelay <= 0) {
         *      remainingBoostDuration += (maxBoostDuration / fullBoostRechargeTime) * Time.deltaTime;
         *      if (remainingBoostDuration > maxBoostDuration)
         *              remainingBoostDuration = maxBoostDuration;
         * }*/
    }
    public event Action <float> OnScanPerformed; //Energy cost

    public List <EMSReading> PerformScan(float heading, float arc, float range)
    {
        float scanArea = Mathf.Pi * Mathf.Pow(range, 2) * arc / (Mathf.Pi * 2);

        List <EMSReading> readings = new List <EMSReading>();

        var bodies = GetOverlappingBodies();
        var areas  = GetOverlappingAreas();

        List <Node2D> nodes = new List <Node2D>();

        foreach (Node2D body in bodies)
        {
            nodes.Add(body);
        }
        foreach (Node2D area in areas)
        {
            nodes.Add(area);
        }

        foreach (Node2D node2D in nodes)
        {
            //Does the current body fall within the scan region?
            Vector2 toNode = node2D.GlobalPosition - GlobalPosition;

            if (toNode.Length() > range)
            {
                //Outside of range
                continue;
            }

            float angleA       = Vector2.Right.Rotated(heading).Angle() % (Mathf.Pi * 2f);
            float angleB       = toNode.Angle() % (Mathf.Pi * 2f);
            float angleBetween = angleA - angleB;

            if (Mathf.Abs(angleBetween) > arc * 0.5f)
            {
                //Outside of heading/arc
                continue;
            }

            //If so, package it up as an EMSReading to return to the caller
            ulong   instanceID        = node2D.GetInstanceId();
            Vector2 positionDiff      = node2D.GlobalPosition - GlobalPosition;
            float   amplitude         = GlobalPosition.DistanceTo(node2D.GlobalPosition) / GConstant;
            float   angle             = Vector2.Right.AngleTo(positionDiff);
            string  materialSignature = string.Empty;
            Vector2 velocity          = Vector2.Zero;
            float   collisionRadius   = -1f;
            string  specialInfo       = null;

            if (node2D is IHasScanSignature signature)
            {
                materialSignature = signature.ScanSignature;
            }

            if (node2D is RigidBody2D rigidBody)
            {
                velocity = rigidBody.LinearVelocity;
            }

            if (node2D is IHasCollisionRadius hasRadius)
            {
                collisionRadius = hasRadius.CollisionRadius;
            }

            if (node2D is WarpGate warpGate)
            {
                specialInfo = warpGate.DestinationSolarSystemName;
            }

            var newReading = new EMSReading(instanceID, angle, amplitude, velocity, collisionRadius, materialSignature, specialInfo);
            readings.Add(newReading);
        }

        OnScanPerformed?.Invoke(scanArea * 0.001f);

        return(readings);
    }
Beispiel #15
0
 public static void Line(Vector2 start, Vector2 end, Color color, float alpha = 1.0f)
 {
     SpriteBatch.Draw(Pixel, start, null, color * Math.Min(alpha, 1), start.Angle(end).Radians, Vector2.Zero, new Vector2(start.Length(end), 1), SpriteEffects.None, 0);
 }
 void GuardButtonProcess()
 {
     if (isGuardButtonPressed && !guardInput)
     {
         guardInput           = true;
         guardInitialPosition = GuardButton.position;
     }
     if (guardInput)
     {
         inputType = InputType.Guard;
     }
     if ((!isGuardButtonPressed && guardInput) || (guardFinalPosition - guardInitialPosition).magnitude > 0.5f || guardFinalPosition.magnitude > 0.9f)
     {
         Vector2 delta;
         float   angle;
         if (guardFinalPosition.magnitude > 0.9f)
         {
             delta = guardFinalPosition;
             angle = Vector2.Angle(Vector2.up, guardFinalPosition);
         }
         else
         {
             delta = guardFinalPosition - guardInitialPosition;
             angle = Vector2.Angle(Vector2.up, delta);
         }
         if (angle < 45)               //Side Dodge
         {
             inputDirection = Vector2.up;
         }
         else if (angle < 135)                 //Roll
         {
             if (delta.x > 0)
             {
                 inputDirection = Vector2.right;
             }
             else
             {
                 inputDirection = Vector2.left;
             }
         }
         else                 //Side Dodge
         {
             inputDirection = Vector2.down;
         }
         if (delta.magnitude > 0.5f)
         {
             inputType = InputType.Roll;
         }
         else
         {
             inputType = InputType.Guard;
         }
         guardHoldTime = 0f;
     }
     if (!isGuardButtonPressed)
     {
         guardInput           = false;
         guardInitialPosition = Vector2.zero;
         guardFinalPosition   = Vector2.zero;
     }
     if (guardInput)
     {
         guardHoldTime     += Time.deltaTime;
         guardFinalPosition = GuardButton.position;
     }
 }
    private void InitStation()
    {
        for (int time = 0; time < 1000; time++)
        {
            if (myStationList.Count < myStationAmount)
            {
                //creat a position
                Vector2 t_position = new Vector2(
                    Random.Range(-myStationPosition.x, myStationPosition.x),
                    Random.Range(-myStationPosition.y, myStationPosition.y)
                    );
                //check if it's at a good position
                bool isGood = true;
                //check if it's too close to sites
                isGood = CheckIfFarEnough(t_position, mySiteList, myStationDistance);

                //check if it's too close to other stations
                if (isGood)
                {
                    isGood = CheckIfFarEnough(t_position, myStationList, myStationDistance);
                }

                if (isGood)
                {
                    isGood = CheckIfFarEnoughLine(t_position, myStationList, myStationDistance);
                }

                if (isGood)
                {
                    GameObject t_station = Instantiate(myStation, t_position, Quaternion.identity) as GameObject;
                    myStationList.Add(t_station);
                }
            }
            else
            {
                Debug.Log("InitStation times : " + time + "; Count : " + myStationList.Count);
                break;
            }
        }

        //draw line
        for (int i = 0; i < myStationList.Count; i++)
        {
            int t_next = i + 1;
            if (t_next >= myStationList.Count)
            {
                t_next -= myStationList.Count;
            }
            Vector2 t_direction = myStationList [t_next].transform.position - myStationList [i].transform.position;
            Vector2 t_position  = (myStationList [t_next].transform.position + myStationList [i].transform.position) / 2;

            Quaternion t_quaternion = Quaternion.Euler(0, 0,
                                                       Vector2.Angle(Vector2.up, t_direction) * Vector3.Cross(Vector3.up, (Vector3)t_direction).normalized.z);
            //Debug.Log (Vector3.Cross (Vector3.up, (Vector3)t_direction));
            GameObject t_line = Instantiate(myStationLine, t_position, t_quaternion) as GameObject;
            t_line.transform.localScale = new Vector3(t_line.transform.localScale.x, t_direction.magnitude, 1);
        }

        //place subway
        for (int i = 0; i < myStationList.Count; i++)
        {
            myStationPositionList.Add(myStationList [i].transform.position);
        }
        int t_stationsPerSubway = myStationPositionList.Count / mySubwayAmount;

        for (int i = 0; i < mySubwayAmount; i++)
        {
            int        t_lastStationNumber = i * t_stationsPerSubway;
            GameObject t_subway            = Instantiate(
                mySubway,
                myStationPositionList [t_lastStationNumber],
                Quaternion.identity
                ) as GameObject;
            t_subway.GetComponent <CS_Subway> ().Init(myStationPositionList, t_lastStationNumber);
        }
    }
Beispiel #18
0
        private void horizontalCollision(ref Vector3 velocity)
        {
            float directionX = m_MovingDirection;
            float rayLength  = Mathf.Abs(velocity.x) + Raycaster.c_SkinWidth;

            if (Mathf.Abs(velocity.x) < Raycaster.c_SkinWidth)
            {
                rayLength = 2 * Raycaster.c_SkinWidth;
            }

            for (int i = 0; i < m_Raycaster.HorizontalRayCount; i++)
            {
                Vector2 rayOrigin = (directionX == -1) ? m_Raycaster.Origins.BottomLeft : m_Raycaster.Origins.BottomRight;

                rayOrigin += Vector2.up * (m_Raycaster.HorizontalRaySpacing * i);
                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, m_Raycaster.CollisionLayer);

                Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.yellow);

                if (hit)
                {
                    if (hit.distance == 0)
                    {
                        continue;
                    }

                    float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);

                    // climbing a slope
                    if (i == 0 && slopeAngle <= m_MaxClimbAngle)
                    {
                        // if descending, reset velocity. Since descendSlope has changed velocity.x
                        if (m_CollisionInfo.DescendingSlope)
                        {
                            m_CollisionInfo.DescendingSlope = false;
                            velocity = Raw_Velocity;
                        }

                        float distanceToSlopeStart = 0;
                        // its a new slope
                        if (slopeAngle != m_CollisionInfo.Prev_SlopeAngle)
                        {
                            distanceToSlopeStart = hit.distance - Raycaster.c_SkinWidth;
                            velocity.x          -= distanceToSlopeStart * directionX;
                        }
                        climbSlope(ref velocity, slopeAngle, hit.normal);

                        velocity.x += distanceToSlopeStart * directionX;
                    }

                    // only check other raycasts if not climbing
                    if (!m_CollisionInfo.ClimbingSlope || slopeAngle > m_MaxClimbAngle)
                    {
                        if (hit.collider.CompareTag("OneWayPlatform"))
                        {
                            continue;
                        }

                        // change velocity x so it stops at the hit point
                        velocity.x = (hit.distance - Raycaster.c_SkinWidth) * directionX;
                        rayLength  = hit.distance;

                        if (m_CollisionInfo.ClimbingSlope)
                        {
                            velocity.y =
                                Mathf.Tan(m_CollisionInfo.Curr_SlopeAngle * Mathf.Deg2Rad) *
                                Mathf.Abs(velocity.x);
                        }

                        setLeft(directionX == -1, hit.normal);
                        setRight(directionX == 1, hit.normal);
                    }
                }
            }
        }
Beispiel #19
0
    /// <summary>
    /// Update this JelloAttachPoint .
    /// Will derive the new position for the JelloAttachPoint.point, AttachTransform.Position and AttachedTrasnform.Angle.
    /// This will be called by the simulation and should not need to be called manualy.
    /// </summary>
    /// <param name="useBaseShape">Whether to use the JelloBody.Shape positions to determine the new position.</param>
    public Vector2 Update(bool useBaseShape)
    {
        point = Vector2.zero;
        if (useBaseShape)
        {
            for (int i = 0; i < affectedIndices.Length; i++)
            {
                point += body.Shape.getVertex(affectedIndices[i]) * scalars[i];
            }

            if (point.x == float.NaN)
            {
                for (int i = 0; i < affectedIndices.Length; i++)
                {
                    Debug.Log(body.Shape.getVertex(affectedIndices[i]) + "     " + scalars[i]);
                }
            }
        }
        else
        {
            for (int i = 0; i < affectedIndices.Length; i++)
            {
                point += body.getPointMass(affectedIndices[i]).Position *scalars[i];
            }

            point = transform.InverseTransformPoint(point);

            if (point.x == float.NaN)
            {
                for (int i = 0; i < affectedIndices.Length; i++)
                {
                    Debug.Log(body.getPointMass(affectedIndices[i]).Position + "     " + scalars[i]);
                }
            }
        }


        if (mAttachedTransform != null)
        {
            Vector3 newPos = transform.TransformPoint(point);
            newPos.z = mAttachedTransform.position.z;
            mAttachedTransform.position = newPos;
            if (rotate)
            {
                float   angle         = 0;
                int     originalSign  = 1;
                float   originalAngle = 0;
                float   thisAngle;
                Vector2 center       = Vector2.zero;
                Vector2 centerGlobal = Vector2.zero;

                if (affectedIndices.Length == 1)
                {
                    centerGlobal = body.Position;
                }
                else
                {
                    for (int i = 0; i < affectedIndices.Length; i++)
                    {
                        center += body.Shape.getVertex(affectedIndices[i]);
                    }
                    center /= affectedIndices.Length;

                    centerGlobal = Vector2.zero;
                    for (int i = 0; i < affectedIndices.Length; i++)
                    {
                        centerGlobal += body.getPointMass(affectedIndices[i]).Position;
                    }
                    centerGlobal /= affectedIndices.Length;
                }

                for (int i = 0; i < affectedIndices.Length; i++)
                {
                    thisAngle = Vector2.Angle(body.Shape.getVertex(affectedIndices[i]) - center, body.getPointMass(affectedIndices[i]).Position - centerGlobal);                  //(Vector2)body.transform.TransformPoint(center));
                    if (Vector3.Cross(body.Shape.getVertex(affectedIndices[i]) - center, body.getPointMass(affectedIndices[i]).Position - centerGlobal).z < 0f)                   //(Vector2)body.transform.TransformPoint(center)).z < 0f)
                    {
                        thisAngle *= -1f;
                    }

                    if (i == 0)
                    {
                        originalSign  = (thisAngle >= 0f) ? 1 : -1;
                        originalAngle = thisAngle;
                    }
                    else
                    {
                        if ((Mathf.Abs(thisAngle - originalAngle) > 180f) && ((thisAngle >= 0f ? 1 : -1) != originalSign))
                        {
                            thisAngle = ((thisAngle >= 0f ? 1 : -1) == -1) ? 360f + thisAngle : -thisAngle;
                        }
                    }

                    angle += thisAngle;
                }

                angle /= affectedIndices.Length;

                mAttachedTransform.eulerAngles = new Vector3(mAttachedTransform.eulerAngles.x, mAttachedTransform.eulerAngles.y, angle + transformAngle);
            }
        }

        return(point);
    }
    public void Move(Vector2 moveVector)
    {
        grounded = false;

        Vector2 candidateMoveVector = moveVector;
        int     iterations          = 0;

        candidateMoveVector = moveVector;

        //SidesCollision
        while (true)
        {
            int numberOfCollisions = 0;

            float        rayCastDistance;
            Vector2      candidatePosition = (Vector2)(this.transform.position) + candidateMoveVector;
            RaycastHit2D hit;

            rayCastDistance = Vector2.Distance(topLeft, bottomLeft);

            // Push Down from Left
            hit = Physics2D.Linecast(candidatePosition + topLeft, candidatePosition + bottomLeft);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                if ((Vector2.Angle(hit.normal, Vector2.up) < steepThreshold) && (rayCastDistance - hit.distance) < stepThreshold)
                {
                    candidateMoveVector += Vector2.up * 1.02f * (rayCastDistance - hit.distance);
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                    grounded             = true;
                }
            }

            // Push Down from Right
            hit = Physics2D.Linecast(candidatePosition + topRight, candidatePosition + bottomRight);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                if ((Vector2.Angle(hit.normal, Vector2.up) < steepThreshold) && (rayCastDistance - hit.distance) < stepThreshold)
                {
                    candidateMoveVector += Vector2.up * 1.02f * (rayCastDistance - hit.distance);
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                    grounded             = true;
                }
            }

            // Push Up from Left
            hit = Physics2D.Linecast(candidatePosition + bottomLeft, candidatePosition + topLeft);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                candidateMoveVector -= Vector2.up * 1.02f * (rayCastDistance - hit.distance);
                candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
            }

            // Push Up from Right
            hit = Physics2D.Linecast(candidatePosition + bottomRight, candidatePosition + topRight);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                candidateMoveVector -= Vector2.up * 1.02f * (rayCastDistance - hit.distance);
                candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
            }

            if (numberOfCollisions == 0)
            {
                moveVector = candidateMoveVector;
                break;
            }

            iterations++;
            if (iterations > NUMBER_OF_ITERATIONS)
            {
                return;
            }
        }

        iterations = 0;
        //Top and BottomCollision
        while (true)
        {
            int          numberOfCollisions = 0;
            float        rayCastDistance;
            Vector2      candidatePosition = (Vector2)(this.transform.position) + candidateMoveVector;
            Vector2      raycastUsed;
            RaycastHit2D hit;

            rayCastDistance = Vector2.Distance(topLeft, topRight);

            // Push Right From Top
            hit = Physics2D.Linecast(candidatePosition + topLeft, candidatePosition + topRight);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                candidateMoveVector -= Vector2.right * 1.02f * (rayCastDistance - hit.distance);
                candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
            }

            // Push Right From Bottom
            hit = Physics2D.Linecast(candidatePosition + bottomLeft, candidatePosition + bottomRight);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                if (Vector2.Angle(hit.normal, Vector3.up) < steepThreshold)
                {
                    candidateMoveVector += Vector2.up * .05f;
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                }
                else
                {
                    candidateMoveVector += Vector2.left * 1.02f * (rayCastDistance - hit.distance);
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                }
            }

            // Push Left From Top
            hit = Physics2D.Linecast(candidatePosition + topRight, candidatePosition + topLeft);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                candidateMoveVector += Vector2.right * 1.02f * (rayCastDistance - hit.distance);
                candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
            }

            // Push Left from Bottom
            hit = Physics2D.Linecast(candidatePosition + bottomRight, candidatePosition + bottomLeft);
            if (hit.transform != null && hit.distance > 0)
            {
                numberOfCollisions++;
                if (Vector2.Angle(hit.normal, Vector3.up) < steepThreshold)
                {
                    candidateMoveVector += Vector2.up * .05f;
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                }
                else
                {
                    candidateMoveVector += Vector2.right * 1.02f * (rayCastDistance - hit.distance);
                    candidatePosition    = (Vector2)(this.transform.position) + candidateMoveVector;
                }
            }

            if (numberOfCollisions == 0)
            {
                moveVector = candidateMoveVector;
                break;
            }

            iterations++;
            if (iterations > NUMBER_OF_ITERATIONS)
            {
                return;
            }
        }
        //		if (checkAllEdges((Vector2)transform.position + moveVector))
        transform.position += (Vector3)moveVector;
    }
Beispiel #21
0
    void VerticalCollisions(ref Vector2 moveAmount)
    {
        float directionY = Mathf.Sign(moveAmount.y);
        float rayLength  = Mathf.Abs(moveAmount.y) + skinWidth;

        for (int i = 0; i < verticalRayCount; i++)
        {
            Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
            rayOrigin += Vector2.right * (verticalRaySpacing * i + moveAmount.x);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);

            Debug.DrawRay(rayOrigin, Vector2.up * directionY, Color.red);

            if (hit)
            {
                //jump up through platforms
                if (hit.collider.tag == "Through")
                {
                    if (directionY == 1 || hit.distance == 0)
                    {
                        continue;
                    }
                    //remove in future
                    if (collisions.fallingThroughPlatform)
                    {
                        continue;
                    }
                    if (playerInput.y == -1)
                    {
                        //collisions.fallingThroughPlatform = true;
                        //remove in future
                        //Invoke("ResetFallingThroughPlatform", .5f);
                        continue;
                    }
                }

                moveAmount.y = (hit.distance - skinWidth) * directionY;
                rayLength    = hit.distance;

                if (collisions.climbingSlope)
                {
                    moveAmount.x = moveAmount.y / Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Sign(moveAmount.x);
                }

                collisions.below = directionY == -1;
                collisions.above = directionY == 1;
            }
        }

        if (collisions.climbingSlope)
        {
            float directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + skinWidth;
            Vector2      rayOrigin = ((directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight) + Vector2.up * moveAmount.y;
            RaycastHit2D hit       = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            if (hit)
            {
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (slopeAngle != collisions.slopeAngle)
                {
                    moveAmount.x           = (hit.distance - skinWidth) * directionX;
                    collisions.slopeAngle  = slopeAngle;
                    collisions.slopeNormal = hit.normal;
                }
            }
        }
    }
Beispiel #22
0
    void VerticalCollisions(ref Vector3 velocity)
    {
        float direction_y = Mathf.Sign(velocity.y);
        float ray_length  = Mathf.Abs(velocity.y) + skin_width;

        bool add_platform_back = false;

        if (direction_y != -1)
        {
            add_platform_back = RemovePlatformFromMask();
        }

        if (collisions.descended_last_frame && direction_y == -1)
        {
            ray_length = ray_length + max_slope_correction;
        }
        for (int i = 0; i < vertical_ray_count; i++)
        {
            Vector2 ray_origin = (direction_y == -1) ? origins.bottom_left : origins.top_left;
            if (direction_y == -1)
            {
                ray_origin = origins.bottom_left;
            }
            else
            {
                ray_origin = origins.top_left;
            }
            ray_origin += Vector2.right * (vertical_ray_spacing * i + velocity.x);

            RaycastHit2D hit = Physics2D.Raycast(ray_origin, Vector2.up * direction_y, ray_length, direction_y == 1 ? collision_mask : floor_collision_mask);

            if (hit)
            {
                velocity.y = (hit.distance - skin_width) * direction_y;
                ray_length = hit.distance;

                if (collisions.climbing_slope)
                {
                    velocity.x = velocity.y / Mathf.Tan(collisions.slope_angle * Mathf.Deg2Rad) * Mathf.Sign(velocity.x);
                }

                collisions.below = direction_y == -1;
                collisions.above = direction_y == 1;
            }
            else
            {
                if (i == 0 && direction_y == -1)
                {
                    hit = Physics2D.Raycast(ray_origin, Vector2.down, 0.8f, floor_collision_mask);
                    if (hit)
                    {
                        collisions.over_slope_left = true;
                    }
                    else
                    {
                        collisions.hanging_left = true;
                    }
                }
                if (i == vertical_ray_count - 1 && direction_y == -1)
                {
                    hit = Physics2D.Raycast(ray_origin, Vector2.down, .8f, floor_collision_mask);
                    if (hit)
                    {
                        collisions.over_slope_right = true;
                    }
                    else
                    {
                        collisions.hanging_right = true;
                    }
                }
            }
        }

        if (collisions.climbing_slope)
        {
            float direction_x = Mathf.Sign(velocity.x);
            ray_length = Mathf.Abs(velocity.x) + skin_width;

            Vector2      origin = (direction_x == -1 ? origins.bottom_left : origins.bottom_right) + Vector2.up * velocity.y;
            RaycastHit2D hit    = Physics2D.Raycast(origin, Vector2.right * direction_x, ray_length, collision_mask);

            if (hit)
            {
                float angle = Vector2.Angle(hit.normal, Vector2.up);
                if (angle != collisions.slope_angle)
                {
                    velocity.x             = (hit.distance - skin_width) * direction_x;
                    collisions.slope_angle = angle;
                }
            }
        }
        if (add_platform_back)
        {
            AddPlatformToMask();
        }
    }
Beispiel #23
0
    // Update is called once per frame
    //Change to be based on force
    void Update()
    {
        //Movment controls
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        Vector3 tempVect = new Vector3(h, v, 0);

        tempVect = tempVect.normalized * speed * Time.deltaTime;
        if (!Input.anyKey)
        {
            tempVect = new Vector3(0, 0, 0);
        }
        rb2d.MovePosition(rb2d.transform.position + tempVect);
        //Shooting / aiming
        Vector3 mouseVect  = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y);
        Vector3 currentDir = new Vector3(aim_sprite.transform.position.x - transform.position.x, aim_sprite.transform.position.y - transform.position.y);
        float   angleTemp  = Mathf.Acos(Vector3.Dot(currentDir, mouseVect) / (currentDir.magnitude * mouseVect.magnitude));

        if (Vector3.Cross(mouseVect.normalized, currentDir.normalized).z < 0 && angleTemp > Mathf.Abs(0.01f))
        {
            angle -= Vector2.Angle(mouseVect, currentDir) * Time.deltaTime;
            aim_sprite.transform.RotateAround(transform.position, new Vector3(0, 0, 1), Vector2.Angle(mouseVect, currentDir) * Time.deltaTime); //0.1f
        }
        else if (Vector3.Cross(mouseVect.normalized, currentDir.normalized).z > 0 && angleTemp > Mathf.Abs(0.01f))
        {
            angle += Vector2.Angle(mouseVect, currentDir) * Time.deltaTime;
            aim_sprite.transform.RotateAround(transform.position, new Vector3(0, 0, 1), -Vector2.Angle(mouseVect, currentDir) * Time.deltaTime); //-0.1f
        }
        //print("Angle: " + angleTemp);
        //print("Cross: " + Vector3.Cross(mouseVect.normalized, currentDir.normalized).z);
        Debug.DrawLine(aim_sprite.transform.position, transform.position, Color.blue);
        Debug.DrawLine(Camera.main.ScreenToWorldPoint(Input.mousePosition), transform.position, Color.blue);

        //print(aim_sprite.transform.position.x - transform.position.x);
        //aim_sprite.transform.RotateAround(transform.position, new Vector3(0, 0, 1), angleTemp);
        if (Input.GetKeyDown(KeyCode.F))
        {
            fireSpell();
            //GameObject tele = Instantiate(teleStor, transform.position, aim_sprite.transform.rotation);
            //tele.transform.position = Vector2.MoveTowards(tele.transform.position, aim_sprite.transform.position, 50);
            //tele.GetComponent<Rigidbody2D>().AddForce(100 * (aim_sprite.transform.position - transform.position));
        }
        else if (Input.GetKeyDown(KeyCode.J))
        {
            markTarget();
        }
        countText.text = "Objects Stolen: " + curInvSize.ToString();
        if (curInvSize >= 3)
        {
            winText.text = "You have stolen everything!\nYou have won the game!";
        }
        if (line.enabled)
        {
            lineTimer += 1 * Time.deltaTime;
        }
        if (lineTimer > 3f)
        {
            lineTimer    = 0;
            line.enabled = false;
        }
    }
    //水平碰撞判定
    void HorizontalCollisions(ref Vector2 v)
    {
        if (v.x != 0)
        {
            facingDir = v.x > 0 ? 1 : -1;
        }

        //速度正负方向
        float directionX = facingDir;
        //光束长度
        float rayLength = Mathf.Abs(v.x) + skinWidth;

        if (Mathf.Abs(v.x) < skinWidth)
        {
            rayLength = 2 * skinWidth;  //刚好能检测到相邻物体的距离
        }

        for (int i = 0; i < horizontalRayCount; i++)
        {
            Vector2 rayOrigin = (directionX == -1) ? raycastOrigin.bottomLeft : raycastOrigin.bottomRight;

            rayOrigin += Vector2.up * (horizontalRaySpacing * i);
            RaycastHit2D hit = Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            //碰到物体
            if (hit)
            {
                if (hit.distance == 0)
                {
                    continue;
                }

                //坡角度
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (i == 0 && slopeAngle <= maxClambAngle)
                {
                    if (collisions.descendingSlope)
                    {
                        collisions.descendingSlope = false;
                        v = collisions.velocityOld;
                    }
                    float distanceToSlopeStart = 0;
                    //进入新的坡
                    if (slopeAngle != collisions.slopeAngleOld)
                    {
                        distanceToSlopeStart = hit.distance - skinWidth;
                        v.x -= distanceToSlopeStart * directionX;
                    }
                    //爬坡
                    ClampSlope(ref v, slopeAngle);
                    v.x += distanceToSlopeStart * directionX;
                }
                //爬不动坡
                if (!collisions.clambingSlope || slopeAngle > maxClambAngle)
                {
                    //根据距离确定下一步移动距离
                    v.x       = (hit.distance - skinWidth) * directionX;
                    rayLength = hit.distance;
                    //在爬坡
                    if (collisions.clambingSlope)
                    {
                        v.y = Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(v.x);
                    }

                    //若方向向左则为真
                    collisions.left = directionX == -1;
                    //向右
                    collisions.right = directionX == 1;
                }
            }
        }
    }
Beispiel #25
0
    private void Update()
    {
        // Use GetAxisRaw to ensure our input is either 0, 1 or -1.

        float moveInput;

        if (Input.GetKey("a"))
        {
            moveInput = -1;
        }
        else if (Input.GetKey("d"))
        {
            moveInput = 1;
        }
        else
        {
            moveInput = 0;
        }

        bool jumpInput = Input.GetKeyDown("space");

        if (grounded)
        {
            velocity.y = 0;

            if (jumpInput)
            {
                // Calculate the velocity required to achieve the target jump height.
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }

        float acceleration = grounded ? walkAcceleration : airAcceleration;
        float deceleration = grounded ? groundDeceleration : 0;

        if (moveInput != 0)
        {
            velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, acceleration * Time.deltaTime);
        }
        else
        {
            velocity.x = Mathf.MoveTowards(velocity.x, 0, deceleration * Time.deltaTime);
        }

        velocity.y += Physics2D.gravity.y * Time.deltaTime;

        transform.Translate(velocity * Time.deltaTime);

        grounded = false;

        // Retrieve all colliders we have intersected after velocity has been applied.
        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        foreach (Collider2D hit in hits)
        {
            // Ignore our own collider.
            if (hit == boxCollider)
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hit.Distance(boxCollider);

            // Ensure that we are still overlapping this collider.
            // The overlap may no longer exist due to another intersected collider
            // pushing us out of this one.
            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);

                // If we intersect an object beneath us, set grounded to true.
                if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
                {
                    grounded = true;
                }
            }
        }
    }
        void HorizontalCollisions(ref RaycastHit2D ray, ref Vector3 velocity, int dir, int idx)
        {
            if (ray && ray.distance != 0)
            {
                // ignore oneWayPlatformsUp/Down, both aren't walls
                if (Configuration.IsOneWayPlatformUp(ray.collider) || Configuration.IsOneWayPlatformDown(ray.collider))
                {
                    return;
                }

                if ((
                        // ignore left wall while moving left
                        Configuration.IsOneWayWallLeft(ray.collider) &&
                        velocity.x < 0
                        ) || (
                        // ignore right wall while moving right
                        Configuration.IsOneWayWallRight(ray.collider) &&
                        velocity.x > 0
                        ))
                {
                    return;
                }


                if (dir == -1)
                {
                    collisions.PushLeftCollider(ray);
                }
                else
                {
                    collisions.PushRightCollider(ray);
                }

                float slopeAngle = Vector2.Angle(ray.normal, Vector2.up);
                if (slopeAngle > maxClimbAngle)
                {
                    if (dir == -1)
                    {
                        collisions.left = true;
                        if (Mathf.Approximately(slopeAngle, 90))
                        {
                            collisions.leftIsWall = true;
                        }
                    }

                    if (dir == 1)
                    {
                        collisions.right = true;
                        if (Mathf.Approximately(slopeAngle, 90))
                        {
                            collisions.rightIsWall = true;
                        }
                    }
                    // same direction
                    // TODO REVIEW check variable-slope. while on ground i the slope push
                    // the character strange things happens because of this
                    if (velocity.x == 0 || dir == Mathf.Sign(velocity.x))
                    {
                        velocity.x = dir == 1 ?
                                     Mathf.Min(velocity.x, (ray.distance - minDistanceToEnv) * dir) :
                                     Mathf.Max(velocity.x, (ray.distance - minDistanceToEnv) * dir);

                        Log.Silly("(PlatformerCollider2D) HorizontalCollisions new velocity {0}", velocity.ToString("F4"));
                    }
                }
            }
        }
Beispiel #27
0
 public static Vector2 Rotate(this Vector2 vec, float angleRadians)
 {
     return(AngleToVector(vec.Angle() + angleRadians, vec.Length()));
 }
Beispiel #28
0
    private static float GetAngle(Vector2 v1, Vector2 v2)
    {
        var sign = Mathf.Sign(v1.x * v2.y - v1.y * v2.x);

        return(Vector2.Angle(v1, v2) * sign);
    }
Beispiel #29
0
        public static Vector2 RotateTowards(this Vector2 vec, float targetAngleRadians, float maxMoveRadians)
        {
            float angle = AngleApproach(vec.Angle(), targetAngleRadians, maxMoveRadians);

            return(AngleToVector(angle, vec.Length()));
        }
Beispiel #30
0
        /// <summary>
        /// Return real angle between 2 vector2 (Have - or + angle)
        /// </summary>
        /// <param name="vt1"></param>
        /// <param name="vt2"></param>
        /// <returns></returns>
        public static float RealAngleVector2(Vector2 vt1, Vector2 vt2)
        {
            int Dir = 0;

            vt1.Normalize();
            vt2.Normalize();

            var angle = Vector2.Angle(vt1, vt2);

            if (vt1.x >= 0 && vt1.y >= 0)
            {
                if (vt2.x >= 0 && vt2.y >= 0)
                {
                    Dir = ((vt2.y - vt1.y) > 0) ? -1 : 1;
                }
                else if (vt2.x < 0 && vt2.y >= 0)
                {
                    Dir = -1;
                }
                else if (vt2.x >= 0 && vt2.y < 0)
                {
                    Dir = 1;
                }
                else
                {
                    if (Mathf.Abs(vt2.x) <= Mathf.Abs(vt1.x))
                    {
                        Dir = 1;
                    }
                    else
                    {
                        Dir = -1;
                    }
                }
            }
            else if (vt1.x >= 0 && vt1.y < 0)
            {
                if (vt2.x >= 0 && vt2.y < 0)
                {
                    Dir = ((vt2.y - vt1.y) > 0) ? -1 : 1;
                }
                else if (vt2.x < 0 && vt2.y < 0)
                {
                    Dir = 1;
                }
                else if (vt2.x >= 0 && vt2.y >= 0)
                {
                    Dir = -1;
                }
                else
                {
                    if (Mathf.Abs(vt2.x) <= Mathf.Abs(vt1.x))
                    {
                        Dir = -1;
                    }
                    else
                    {
                        Dir = 1;
                    }
                }
            }
            else if (vt1.x < 0 && vt1.y < 0)
            {
                if (vt2.x < 0 && vt2.y < 0)
                {
                    Dir = ((vt2.y - vt1.y) > 0) ? 1 : -1;
                }
                else if (vt2.x >= 0 && vt2.y < 0)
                {
                    Dir = -1;
                }
                else if (vt2.x < 0 && vt2.y >= 0)
                {
                    Dir = 1;
                }
                else
                {
                    if (Mathf.Abs(vt2.x) <= Mathf.Abs(vt1.x))
                    {
                        Dir = 1;
                    }
                    else
                    {
                        Dir = -1;
                    }
                }
            }
            else
            {
                if (vt2.x < 0 && vt2.y >= 0)
                {
                    Dir = ((vt2.y - vt1.y) >= 0) ? 1 : -1;
                }
                else if (vt2.x < 0 && vt2.y < 0)
                {
                    Dir = -1;
                }
                else if (vt2.x >= 0 && vt2.y >= 0)
                {
                    Dir = 1;
                }
                else
                {
                    if (Mathf.Abs(vt2.x) <= Mathf.Abs(vt1.x))
                    {
                        Dir = -1;
                    }
                    else
                    {
                        Dir = 1;
                    }
                }
            }
            return(Dir * angle);
        }
Beispiel #31
0
 public static float ReflectAngle(float angleRadians, Vector2 axis)
 {
     return(ReflectAngle(angleRadians, axis.Angle()));
 }
 private void Attack(AttackType type)
 {
     if (type == AttackType.Gash)
     {
         Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, gashAreaRadius);
         foreach (Collider2D enemy in hitEnemies)
         {
             enemy.GetComponent <AXD_Enemy>().GetHit(GashDamage);
         }
     }
     else if (type == AttackType.Thrust)
     {
         Collider2D[] hitEnemies = Physics2D.OverlapBoxAll(attackPoint.position, new Vector2(thrustWidth, thrustlength), Vector2.Angle(Vector2.up, lastDirection));
         foreach (Collider2D enemy in hitEnemies)
         {
             enemy.GetComponent <AXD_Enemy>().GetHit(ThrustDamage);
         }
     }
     nextAttackTime = Time.time + 1f / attackRate;
 }
Beispiel #33
0
 private void RotateTowards(Vector2 direction, float rotationSpeed)
 {
     // Rotation is limited by rocket movement so that the rocket can only turn
     // in a small angle from the direction it is currently moving towards.
     var rotationGoal = direction.Angle();
     var moveDirection = Move.Angle();
     var rotationLimitedByMove = rotationGoal.ClampAngle(moveDirection - TURN_LIMIT, moveDirection + TURN_LIMIT);
     var elapsedSeconds = (float)Game.GameTime.ElapsedGameTime.TotalSeconds;
     Rotation = AWMathHelper.InterpolateTowardsAngle(Rotation, rotationLimitedByMove, rotationSpeed * elapsedSeconds);
 }