Ejemplo n.º 1
0
    void OnMouseDrag()
    {
        if (isFreezed || Game.IsOver)
        {
            return;
        }

        isGrabbed = true;
        Game.Objectives["Grab"] = true;

        if (Input.GetMouseButton(1))
        {
            //Cursor.lockState = CursorLockMode.Locked;
            rb.useGravity      = false;
            rb.velocity        = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
            float   hInput         = Input.GetAxis("Mouse X");
            float   vInput         = Input.GetAxis("Mouse Y");
            float   h              = horizontalSpeed * hInput;
            float   v              = verticalSpeed * vInput;
            Vector3 horizontalAxis = Vector3.zero;
            Vector3 verticalAxis   = Vector3.zero;
            Vector3 cameraPos      = Camera.main.transform.position;
            float   x              = cameraPos.x;
            float   z              = cameraPos.z;

            if (x > z && x + z < 0)
            {
                horizontalAxis = Vector3.back;
                verticalAxis   = Vector3.right;
            }
            else if (x < z && x + z < 0)
            {
                horizontalAxis = Vector3.left;
                verticalAxis   = Vector3.back;
            }
            else if (x < z && x + z > 0)
            {
                horizontalAxis = Vector3.forward;
                verticalAxis   = Vector3.left;
            }
            else if (x > z && x + z > 0)
            {
                horizontalAxis = Vector3.right;
                verticalAxis   = Vector3.forward;
            }


            if (Input.GetKey(KeyCode.LeftControl))
            {
                rotationDelay -= Time.deltaTime;

                if (rotationDelay <= 0)
                {
                    //transform.rotation = transform.rotation.AlignToRightAngles();

                    if (vInput > 0.5 || vInput < -0.5)
                    {
                        transform.RotateAround(handle.transform.position, verticalAxis, 90 * Mathf.Sign(vInput));

                        rotationDelay = 0.2f;
                    }
                    if (hInput > 0.5 || hInput < -0.5)
                    {
                        transform.RotateAround(handle.transform.position, horizontalAxis, 90 * Mathf.Sign(hInput));

                        rotationDelay = 0.2f;
                    }
                }
            }
            else
            {
                transform.RotateAround(handle.transform.position, verticalAxis, v);
                transform.RotateAround(handle.transform.position, horizontalAxis, h);
            }
        }
        else
        {
            rb.useGravity = true;
            Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
            Vector3 destination   = Camera.main.ScreenToWorldPoint(mousePosition);

            rb.velocity = (destination - handle.transform.position) * currentSensitivity;
        }
    }
 private float GetOuterRingFlex()
 {
     return(button.State == ButtonState.Pressed ?
            Mathf.Pow(button.Outro / .3f, .5f) :
            Mathf.Max(0, -button.Pressedness) / distToFlex);
 }
        public override void OnInspectorGUI()
        {
            if (m_EditorUserSettings != null && !m_EditorUserSettings.targetObject)
            {
                LoadEditorUserSettings();
            }

            serializedObject.Update();

            // GUI.enabled hack because we don't want some controls to be disabled if the EditorSettings.asset is locked
            // since some of the controls are not dependent on the Editor Settings asset. Unfortunately, this assumes
            // that the editor will only be disabled because of version control locking which may change in the future.
            var editorEnabled = GUI.enabled;

            ShowUnityRemoteGUI(editorEnabled);

            GUILayout.Space(10);
            bool collabEnabled = Collab.instance.IsCollabEnabledForCurrentProject();
            using (new EditorGUI.DisabledScope(!collabEnabled))
            {
                GUI.enabled = !collabEnabled;
                GUILayout.Label(Content.versionControl, EditorStyles.boldLabel);

                ExternalVersionControl selvc = EditorSettings.externalVersionControl;
                CreatePopupMenuVersionControl(Content.mode.text, vcPopupList, selvc, SetVersionControlSystem);
                GUI.enabled = editorEnabled && !collabEnabled;
            }
            if (collabEnabled)
            {
                EditorGUILayout.HelpBox("Version Control not available when using Collaboration feature.", MessageType.Warning);
            }

            if (VersionControlSystemHasGUI())
            {
                GUI.enabled = true;
                bool hasRequiredFields = false;

                if (EditorSettings.externalVersionControl == ExternalVersionControl.Generic ||
                    EditorSettings.externalVersionControl == ExternalVersionControl.Disabled)
                {
                    // no specific UI for these VCS types
                }
                else
                {
                    ConfigField[] configFields = Provider.GetActiveConfigFields();

                    hasRequiredFields = true;

                    foreach (ConfigField field in configFields)
                    {
                        string newVal;
                        string oldVal = EditorUserSettings.GetConfigValue(field.name);
                        if (field.isPassword)
                        {
                            newVal = EditorGUILayout.PasswordField(field.label, oldVal);
                            if (newVal != oldVal)
                                EditorUserSettings.SetPrivateConfigValue(field.name, newVal);
                        }
                        else
                        {
                            newVal = EditorGUILayout.TextField(field.label, oldVal);
                            if (newVal != oldVal)
                                EditorUserSettings.SetConfigValue(field.name, newVal);
                        }

                        if (field.isRequired && string.IsNullOrEmpty(newVal))
                            hasRequiredFields = false;
                    }
                }

                // Log level popup
                string logLevel = EditorUserSettings.GetConfigValue("vcSharedLogLevel");
                int idx = System.Array.FindIndex(logLevelPopupList, (item) => item.ToLower() == logLevel);
                if (idx == -1)
                {
                    logLevel = "notice";
                    idx = System.Array.FindIndex(logLevelPopupList, (item) => item.ToLower() == logLevel);
                    if (idx == -1)
                    {
                        idx = 0;
                    }
                    logLevel = logLevelPopupList[idx];
                    EditorUserSettings.SetConfigValue("vcSharedLogLevel", logLevel);
                }
                int newIdx = EditorGUILayout.Popup(Content.logLevel, idx, logLevelPopupList);
                if (newIdx != idx)
                {
                    EditorUserSettings.SetConfigValue("vcSharedLogLevel", logLevelPopupList[newIdx].ToLower());
                }

                GUI.enabled = editorEnabled;

                string osState = "Connected";
                if (Provider.onlineState == OnlineState.Updating)
                    osState = "Connecting...";
                else if (Provider.onlineState == OnlineState.Offline)
                    osState = "Disconnected";
                else if (EditorUserSettings.WorkOffline)
                    osState = "Work Offline";

                EditorGUILayout.LabelField(Content.status.text, osState);

                if (Provider.onlineState != OnlineState.Online && !string.IsNullOrEmpty(Provider.offlineReason))
                {
                    GUI.enabled = false;
                    GUILayout.TextArea(Provider.offlineReason);
                    GUI.enabled = editorEnabled;
                }

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                GUI.enabled = hasRequiredFields && Provider.onlineState != OnlineState.Updating;
                if (GUILayout.Button("Connect", EditorStyles.miniButton))
                    Provider.UpdateSettings();
                GUILayout.EndHorizontal();

                EditorUserSettings.AutomaticAdd = EditorGUILayout.Toggle(Content.automaticAdd, EditorUserSettings.AutomaticAdd);

                if (Provider.requiresNetwork)
                {
                    bool workOfflineNew = EditorGUILayout.Toggle(Content.workOffline, EditorUserSettings.WorkOffline); // Enabled has a slightly different behaviour
                    if (workOfflineNew != EditorUserSettings.WorkOffline)
                    {
                        // On toggling on show a warning
                        if (workOfflineNew && !EditorUtility.DisplayDialog("Confirm working offline", "Working offline and making changes to your assets means that you will have to manually integrate changes back into version control using your standard version control client before you stop working offline in Unity. Make sure you know what you are doing.", "Work offline", "Cancel"))
                        {
                            workOfflineNew = false; // User cancelled working offline
                        }
                        EditorUserSettings.WorkOffline = workOfflineNew;
                        EditorApplication.RequestRepaintAllViews();
                    }

                    EditorUserSettings.allowAsyncStatusUpdate = EditorGUILayout.Toggle(Content.allowAsyncUpdate, EditorUserSettings.allowAsyncStatusUpdate);
                }

                if (Provider.hasCheckoutSupport)
                {
                    EditorUserSettings.showFailedCheckout = EditorGUILayout.Toggle(Content.showFailedCheckouts, EditorUserSettings.showFailedCheckout);
                    EditorUserSettings.overwriteFailedCheckoutAssets = EditorGUILayout.Toggle(Content.overwriteFailedCheckoutAssets, EditorUserSettings.overwriteFailedCheckoutAssets);
                }

                var newOverlayIcons = EditorGUILayout.Toggle(Content.overlayIcons, EditorUserSettings.overlayIcons);
                if (newOverlayIcons != EditorUserSettings.overlayIcons)
                {
                    EditorUserSettings.overlayIcons = newOverlayIcons;
                    EditorApplication.RequestRepaintAllViews();
                }

                GUI.enabled = editorEnabled;

                // Semantic merge popup
                EditorUserSettings.semanticMergeMode = (SemanticMergeMode)EditorGUILayout.Popup(Content.smartMerge, (int)EditorUserSettings.semanticMergeMode, semanticMergePopupList);

                DrawOverlayDescriptions();
            }

            GUILayout.Space(10);

            int index = (int)EditorSettings.serializationMode;
            using (new EditorGUI.DisabledScope(!collabEnabled))
            {
                GUI.enabled = !collabEnabled;
                GUILayout.Label(Content.assetSerialization, EditorStyles.boldLabel);
                GUI.enabled = editorEnabled && !collabEnabled;


                CreatePopupMenu("Mode", serializationPopupList, index, SetAssetSerializationMode);
            }
            if (collabEnabled)
            {
                EditorGUILayout.HelpBox("Asset Serialization is forced to Text when using Collaboration feature.", MessageType.Warning);
            }

            GUILayout.Space(10);

            GUI.enabled = true;
            GUILayout.Label(Content.defaultBehaviorMode, EditorStyles.boldLabel);
            GUI.enabled = editorEnabled;

            index = Mathf.Clamp((int)EditorSettings.defaultBehaviorMode, 0, behaviorPopupList.Length - 1);
            CreatePopupMenu(Content.mode.text, behaviorPopupList, index, SetDefaultBehaviorMode);

            {
                var wasEnabled = GUI.enabled;
                GUI.enabled = true;

                DoAssetPipelineSettings();

                if (m_AssetPipelineMode.intValue == (int)AssetPipelineMode.Version2)
                    DoCacheServerSettings();

                GUI.enabled = wasEnabled;
            }
            GUILayout.Space(10);

            GUI.enabled = true;
            GUILayout.Label("Prefab Editing Environments", EditorStyles.boldLabel);
            GUI.enabled = editorEnabled;

            {
                EditorGUI.BeginChangeCheck();
                SceneAsset scene = EditorSettings.prefabRegularEnvironment;
                scene = (SceneAsset)EditorGUILayout.ObjectField("Regular Environment", scene, typeof(SceneAsset), false);
                if (EditorGUI.EndChangeCheck())
                    EditorSettings.prefabRegularEnvironment = scene;
            }
            {
                EditorGUI.BeginChangeCheck();
                SceneAsset scene = EditorSettings.prefabUIEnvironment;
                scene = (SceneAsset)EditorGUILayout.ObjectField("UI Environment", scene, typeof(SceneAsset), false);
                if (EditorGUI.EndChangeCheck())
                    EditorSettings.prefabUIEnvironment = scene;
            }

            GUILayout.Space(10);

            GUI.enabled = true;
            GUILayout.Label(Content.graphics, EditorStyles.boldLabel);
            GUI.enabled = editorEnabled;

            EditorGUI.BeginChangeCheck();
            bool showRes = LightmapVisualization.showResolution;
            showRes = EditorGUILayout.Toggle(Content.showLightmapResolutionOverlay, showRes);
            if (EditorGUI.EndChangeCheck())
                LightmapVisualization.showResolution = showRes;

            GUILayout.Space(10);

            GUI.enabled = true;
            GUILayout.Label(Content.spritePacker, EditorStyles.boldLabel);
            GUI.enabled = editorEnabled;

            index = Mathf.Clamp((int)EditorSettings.spritePackerMode, 0, spritePackerPopupList.Length - 1);
            CreatePopupMenu(Content.mode.text, spritePackerPopupList, index, SetSpritePackerMode);

            if (EditorSettings.spritePackerMode == SpritePackerMode.AlwaysOn
                || EditorSettings.spritePackerMode == SpritePackerMode.BuildTimeOnly)
            {
                index = Mathf.Clamp((int)(EditorSettings.spritePackerPaddingPower - 1), 0, 2);
                CreatePopupMenu("Padding Power (Legacy Sprite Packer)", spritePackerPaddingPowerPopupList, index, SetSpritePackerPaddingPower);
            }

            DoProjectGenerationSettings();
            DoEtcTextureCompressionSettings();
            DoLineEndingsSettings();
            DoStreamingSettings();
            DoShaderCompilationSettings();
            DoEnterPlayModeSettings();

            serializedObject.ApplyModifiedProperties();
            m_EditorUserSettings.ApplyModifiedProperties();
        }
Ejemplo n.º 4
0
 public void invert(bool ison)
 {
     if (ison)
     {
         GameObject.Find("birdy").GetComponent <MoveBird>().invertgravity = 1;
         PlayerPrefs.SetInt("invertgravity", 1);
         Physics.gravity = new Vector3(Mathf.Abs(Physics.gravity.x), Mathf.Abs(Physics.gravity.y), Mathf.Abs(Physics.gravity.z));
     }
     else
     {
         GameObject.Find("birdy").GetComponent <MoveBird>().invertgravity       = 0;
         GameObject.Find("birdy").GetComponent <Rigidbody>().transform.position = new Vector3(
             GameObject.Find("birdy").GetComponent <Rigidbody>().transform.position.x,
             2.39f,
             GameObject.Find("birdy").GetComponent <Rigidbody>().transform.position.z);
         PlayerPrefs.SetInt("invertgravity", 0);
         Physics.gravity = new Vector3(-Mathf.Abs(Physics.gravity.x), -Mathf.Abs(Physics.gravity.y), -Mathf.Abs(Physics.gravity.z));
     }
 }
		private static float GetGenerationChanceAgeFactor(Pawn p)
		{
			float value = GenMath.LerpDouble(14f, 27f, 0f, 1f, p.ageTracker.AgeBiologicalYearsFloat);
			return Mathf.Clamp(value, 0f, 1f);
		}
Ejemplo n.º 6
0
    public float RaycastVertical(float distance)
    {
        RaycastHit hit = new RaycastHit();

        Vector3 actualSize = new Vector3(selfCollider.size.x * selfTr.lossyScale.x, selfCollider.size.y * selfTr.lossyScale.y * skinWidthMultiplier, selfCollider.size.z * selfTr.lossyScale.z);

        if (Physics.BoxCast(selfTr.position + selfCollider.center, actualSize * 0.5f, Vector3.up * Mathf.Sign(distance), out hit, selfTr.rotation, Mathf.Abs(distance), checkMask))
        {
            float startPoint = selfTr.position.y + selfCollider.center.y + selfCollider.size.y * 0.5f * Mathf.Sign(distance);
            float newDistance = Mathf.Sign(distance) * Mathf.Abs(hit.point.y - startPoint);

            if (distance < 0) { flags.below = true; OnLanded?.Invoke(); }
            if (distance > 0) flags.above = true;

            lastVerticalHitResult = hit;

            return newDistance;
        }

        lastVerticalHitResult = hit;

        if (distance < 0) flags.below = false;
        if (distance > 0) flags.above = false;

        return distance;
    }
Ejemplo n.º 7
0
    private void MakeRays()
    {
        float stepAngleDeg = 360 / numberOfRays;

        foreach (float j in radii)
        {
            for (int i = 0; i < numberOfRays; i++)
            {
                Vector3    localRotation = camPos.right * Mathf.Cos(i * stepAngleDeg) * j + camPos.up * Mathf.Sin(i * stepAngleDeg) * j;
                Vector3    direction     = (Quaternion.Euler(localRotation) * camPos.forward).normalized;
                Ray        ray           = new Ray(camPos.position, direction);
                RaycastHit hitInfo;
                if (Physics.Raycast(ray, out hitInfo, depth, layerMask:mask.value))
                {
                    GameObject g = hitInfo.collider.gameObject;
                    if (!objects.Contains(g))
                    {
                        objects.Add(g);
                        RM.Add(w1 / j * 1 / 1440);
                    }
                    else
                    {
                        RM[objects.IndexOf(g)] += w1 / j * 1 / 1440;
                    }
                }

                //Debug.DrawLine(ray.origin, ray.origin+(direction*depth), Color.red);
            }
        }

        foreach (RaycastHit hit in ConeCastExtension.ConeCastAll(physics, camPos.position, r, camPos.forward, d, a, mask))
        {
            float       extraValue  = 0f;
            FocusWeight f           = hit.collider.gameObject.GetComponent <FocusWeight>();
            float       metricValue = 0f;
            if (f != null)
            {
                extraValue = f.weight;
            }
            if (objects.Contains(hit.collider.gameObject))
            {
                metricValue = RM[objects.IndexOf(hit.collider.gameObject)];
            }

            float value = a1 * metricValue + a2 * Mathf.Exp(-w2 * hit.distance) + a3 * extraValue;

            if (value > threshold)
            {
                hit.collider.gameObject.layer = LayerMask.NameToLayer("Default");
            }
            else
            {
                hit.collider.gameObject.layer = LayerMask.NameToLayer("Focus");
                foreach (Transform trans in hit.collider.gameObject.GetComponentsInChildren <Transform>(true))
                {
                    trans.gameObject.layer = LayerMask.NameToLayer("Focus");
                }
            }
        }
//        foreach (GameObject obj in objects)
//        {
//            distances.Add(1/Vector3.Magnitude(obj.transform.position - camPos.transform.position));
//        }
    }
Ejemplo n.º 8
0
 public Resource(int min, int max)
 // Used for first initialization of this object
 {
     amount = Mathf.FloorToInt(max * Random.value);
 }
Ejemplo n.º 9
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            WDown = true;
        }
        else if (Input.GetKeyUp(KeyCode.W))
        {
            WDown = false;
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            SDown = true;
        }
        else if (Input.GetKeyUp(KeyCode.S))
        {
            SDown = false;
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            ADown = true;
        }
        else if (Input.GetKeyUp(KeyCode.A))
        {
            ADown = false;
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            DDown = true;
        }
        else if (Input.GetKeyUp(KeyCode.D))
        {
            DDown = false;
        }

        if (accCount == 0)
        {
            if (WDown)
            {
                if (acc <= 0.1)
                {
                    acc     += 0.01f;
                    accCount = waitTime;
                }
            }
            else
            {
                if (acc > 0)
                {
                    acc      = Mathf.Max(acc - 0.03f, 0);
                    accCount = waitTime;
                }
            }
            if (SDown)
            {
                if (acc >= -0.1)
                {
                    acc     += -0.01f;
                    accCount = waitTime;
                }
            }
            else
            {
                if (acc < 0)
                {
                    acc      = Mathf.Max(acc + 0.03f, 0);
                    accCount = waitTime;
                }
            }
        }
        else
        {
            accCount--;
        }

        if (rotCount == 0)
        {
            if (DDown)
            {
                if (rot <= 5)
                {
                    rot     += 1;
                    rotCount = waitTime;
                }
            }
            else
            {
                if (rot > 0)
                {
                    rot      = Mathf.Max(rot - 3, 0);
                    rotCount = waitTime;
                }
            }
            if (ADown)
            {
                if (rot >= -5)
                {
                    rot     += -1;
                    rotCount = waitTime;
                }
            }
            else
            {
                if (rot < 0)
                {
                    rot      = Mathf.Min(rot + 3, 0);
                    rotCount = waitTime;
                }
            }
        }
        else
        {
            rotCount--;
        }

        this.gameObject.transform.Translate(new Vector3(0, 0, acc));
        this.gameObject.transform.Rotate(new Vector3(0, rot, 0));
    }
Ejemplo n.º 10
0
 // Update is called once per frame
 void Update()
 {
     transform.position = new Vector3(Mathf.Clamp(character.transform.position.x, -250f,250f),Mathf.Clamp(character.transform.position.y,9f,15f),transform.position.z);
 }
Ejemplo n.º 11
0
        public static bool EQ(float a, float b)
        {
            bool equal = Mathf.Abs(b - a) < Epsilon;

            return(equal);
        }
Ejemplo n.º 12
0
        private void FixedUpdate()
        {
            if (m_Target == null || !m_Driving)
            {
                // Car should not be moving,
                // use handbrake to stop
                m_CarController.Move(0, 0, -1f, 1f);
            }
            else
            {
                Vector3 fwd = transform.forward;
                if (m_Rigidbody.velocity.magnitude > m_CarController.MaxSpeed * 0.1f)
                {
                    fwd = m_Rigidbody.velocity;
                }
                float desiredSpeed = m_CarController.MaxSpeed;
                // now it's time to decide if we should be slowing down...
                switch (m_BrakeCondition)
                {
                case BrakeCondition.TargetDirectionDifference:
                {
                    // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.

                    // check out the angle of our target compared to the current direction of the car
                    float approachingCornerAngle = Vector3.Angle(m_Target.forward, fwd);

                    // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
                    float spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;

                    // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
                    float cautiousnessRequired = Mathf.InverseLerp(0, m_CautiousMaxAngle,
                                                                   Mathf.Max(spinningAngle,
                                                                             approachingCornerAngle));
                    desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed * m_CautiousSpeedFactor,
                                              cautiousnessRequired);
                    break;
                }

                case BrakeCondition.TargetDistance:
                {
                    // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
                    // head for a stationary target and come to rest when it arrives there.

                    // check out the distance to target
                    Vector3 delta = m_Target.position - transform.position;
                    float   distanceCautiousFactor = Mathf.InverseLerp(m_CautiousMaxDistance, 0, delta.magnitude);

                    // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
                    float spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;

                    // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
                    float cautiousnessRequired = Mathf.Max(
                        Mathf.InverseLerp(0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor);
                    desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed * m_CautiousSpeedFactor,
                                              cautiousnessRequired);
                    break;
                }

                case BrakeCondition.NeverBrake:
                    break;
                }

                // Evasive action due to collision with other cars:

                // our target position starts off as the 'real' target position
                Vector3 offsetTargetPos = m_Target.position;

                // if are we currently taking evasive action to prevent being stuck against another car:
                if (Time.time < m_AvoidOtherCarTime)
                {
                    // slow down if necessary (if we were behind the other car when collision occured)
                    desiredSpeed *= m_AvoidOtherCarSlowdown;

                    // and veer towards the side of our path-to-target that is away from the other car
                    //          offsetTargetPos += m_Target.right*m_AvoidPathOffset;
                }
                else
                {
                    // no need for evasive action, we can just wander across the path-to-target in a random way,
                    // which can help prevent AI from seeming too uniform and robotic in their driving
                    //              offsetTargetPos += m_Target.right*
                    //                               (Mathf.PerlinNoise(Time.time*m_LateralWanderSpeed, m_RandomPerlin)*2 - 1)*
                    //                             m_LateralWanderDistance;
                }

                // use different sensitivity depending on whether accelerating or braking:
                float accelBrakeSensitivity = (desiredSpeed < m_CarController.CurrentSpeed)
                                                  ? m_BrakeSensitivity
                                                  : m_AccelSensitivity;

                // decide the actual amount of accel/brake input to achieve desired speed.
                float accel = Mathf.Clamp((desiredSpeed - m_CarController.CurrentSpeed) * accelBrakeSensitivity, -1, 1);

                // add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
                // i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
                accel *= (1 - m_AccelWanderAmount) +
                         (Mathf.PerlinNoise(Time.time * m_AccelWanderSpeed, m_RandomPerlin) * m_AccelWanderAmount);

                // calculate the local-relative position of the target, to steer towards
                Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos);

                // work out the local angle towards the target
                float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;

                // get the amount of steering needed to aim the car towards the target
                float steer = Mathf.Clamp(targetAngle * m_SteerSensitivity, -1, 1) * Mathf.Sign(m_CarController.CurrentSpeed);

                // feed input to the car controller.
                m_CarController.Move(steer, accel, accel, 0f);

                // if appropriate, stop driving when we're close enough to the target.
                if (m_StopWhenTargetReached && localTarget.magnitude < m_ReachTargetThreshold)
                {
                    m_Driving = false;
                }
            }
        }
Ejemplo n.º 13
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (Vector2.Distance(transform.position, player.transform.position) < range)
        {
            Vector2 delta = new Vector2(transform.position.x - player.transform.position.x,
                                        transform.position.y - player.transform.position.y);
            targetAimAngle = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg + 180;
            targetAimAngle = To360Angle(targetAimAngle);
            if ((targetAimAngle > transform.eulerAngles.z && targetAimAngle < transform.eulerAngles.z + 180) ||
                (transform.eulerAngles.z >= 270 && (targetAimAngle > transform.eulerAngles.z || targetAimAngle < To360Angle(transform.eulerAngles.z + 180))))
            {
                aimAngle = Mathf.LerpAngle(aimAngle, targetAimAngle - transform.eulerAngles.z, 0.1f);
                canon.transform.localPosition    = new Vector3(Mathf.Cos(aimAngle * Mathf.Deg2Rad) * 0.5f, Mathf.Sin(aimAngle * Mathf.Deg2Rad) * 0.5f, 0);
                canon.transform.localEulerAngles = new Vector3(0, 0, aimAngle - 90);

                if (count < 0)
                {
                    count = Mathf.RoundToInt(fireRate / Time.fixedDeltaTime);

                    GameObject a      = Instantiate(bulletPrefab);
                    Vector3    offset = new Vector3(Mathf.Cos((targetAimAngle) * Mathf.Deg2Rad), Mathf.Sin((targetAimAngle) * Mathf.Deg2Rad), 0);
                    a.transform.position    = canon.transform.position + offset * 1;
                    a.transform.eulerAngles = new Vector3(0, 0, targetAimAngle - 90 + Random.Range(-10, 10));
                }
                count--;
            }
        }
    }
Ejemplo n.º 14
0
        private void Update()
        {
            if (!_canvas.enabled)
            {
                return;
            }

            _loadingBar.fillAmount = Loader.LoadingProgress;

            _loadingBar.color = _jokeTime ? Color.red : HSBColor.ToColor(new HSBColor(Mathf.PingPong(Time.time * 0.35f, 1), 1, 1));
            _headerText.color = _jokeTime ? Color.red : HSBColor.ToColor(new HSBColor(Mathf.PingPong(Time.time * 0.35f, 1), 1, 1));
        }
Ejemplo n.º 15
0
Archivo: WCR.cs Proyecto: Keyansn/FYP
    void WCR_function()
    {
        GameObject[] nodelist;
        int          node_length;

        nodelist    = GameObject.FindGameObjectsWithTag("Node");
        node_length = nodelist.Length;

        foreach (GameObject item in nodelist)
        {
            if (debug)
            {
                print(item.transform.position);
                //item.transform.position = new Vector3(Random.value, Random.value, Random.value);
            }
        }



        for (int n = 0; n < 20; n++)
        {
            if (!debug)
            {
                print("n: " + n);
            }

            for (int i = 0; i < node_length; i++)
            {
                for (int j = 0; j < node_length; j++)
                {
                    if (j < i)
                    {
                        Dijkstra eScript = GameObject.FindGameObjectWithTag("GameController").GetComponent <Dijkstra>();
                        dist_ij = 5 * eScript.Calculate(nodelist[i], nodelist[j], false);

                        if (debug)
                        {
                            print("dist_ij: " + dist_ij);
                        }

                        weight_ij = (float)Mathf.Pow(dist_ij, -2);
                        weight    = weight_ij * c;

                        if (weight > 2)
                        {
                            weight = 2;
                        }

                        if (debug)
                        {
                            print("weight: " + weight);
                        }

                        if (debug)
                        {
                            print("weight_ij: " + weight_ij);
                        }

                        //        dist_ij - ||Xi-Xj||    Xi-Xj
                        // move = -------------------   -------
                        //                 2           ||Xi-Xj||

                        // Separate out x,y and z
                        xi = nodelist[i].transform.position.x;
                        xj = nodelist[j].transform.position.x;
                        yi = nodelist[i].transform.position.y;
                        yj = nodelist[j].transform.position.y;
                        zi = nodelist[i].transform.position.z;
                        zj = nodelist[j].transform.position.z;

                        if (!debug)
                        {
                            print("xi: " + xi);
                        }

                        //moveX = (float)((0.5)*(dist_ij - Mathf.Abs(xi-xj)) * ((xi-xj)/Mathf.Abs(xi-xj)));
                        //could use vector3.Distance

                        moveX = move(dist_ij, xi, xj);
                        moveY = move(dist_ij, yi, yj);
                        moveZ = move(dist_ij, zi, zj);

                        if (!debug)
                        {
                            print("moveX: " + moveX);
                            print("moveY: " + moveY);
                            print("moveZ: " + moveZ);
                        }

                        currentPositioni.Set(nodelist[i].transform.position.x, nodelist[i].transform.position.y, nodelist[i].transform.position.z);
                        currentPositionj.Set(nodelist[j].transform.position.x, nodelist[j].transform.position.y, nodelist[j].transform.position.z);

                        nodelist[i].transform.position = new Vector3(currentPositioni.x + (weight * moveX), currentPositioni.y + (weight * moveY), currentPositioni.z + (weight * moveZ));
                        //print("Test:");
                        //print(currentPositioni.x + (weight * moveX));

                        nodelist[j].transform.position = new Vector3(currentPositionj.x - (weight * moveX), currentPositionj.y - (weight * moveY), currentPositionj.z - (weight * moveZ));

                        c = c / 2;
                    }
                }
            }
        }
    }
Ejemplo n.º 16
0
    private void OnGUI()
    {
        GUILayout.Label("Nom de l'objet");
        nameObject = EditorGUILayout.TextArea(nameObject);
        if (nameObject == "")
        {
            nameObject = "J'ai laissé un nom vide , shame on me";
        }

        GUILayout.Label("Vitesse du bandeau (multiplicateur)");
        vitesseBandeauMultipler = Mathf.Max(0.001f,EditorGUILayout.FloatField("", vitesseBandeauMultipler));

        GUILayout.Label("Texte de victoire");
        textVictory = EditorGUILayout.TextArea(textVictory);

        GUILayout.Label("Texte de defaite");
        textDefeat= EditorGUILayout.TextArea(textDefeat);

        GUILayout.Label("Taille de police (Victoire)");
        textSizeVictory = Mathf.Max(10, EditorGUILayout.IntField(textSizeVictory));

        GUILayout.Label("Taille de police (Defaite)");
        textSizeDefeat = Mathf.Max(10, EditorGUILayout.IntField(textSizeDefeat));

        GUILayout.Label("Delai du bandeau (temps en secondes)");
        delaiBandeau = Mathf.Max(0.001f, EditorGUILayout.FloatField("", delaiBandeau));


        GUILayout.Label("Vitesse de transition (multiplicateur) ");
        vitesseInsertion = Mathf.Max(0.001f, EditorGUILayout.FloatField("", vitesseInsertion));

        GUILayout.Label("Quel animation ?");
        anim = (animHero)EditorGUILayout.EnumPopup(anim);

        sprt = (Sprite)EditorGUILayout.ObjectField("Quel sprite de fond ? ", sprt, typeof(Sprite), true);

        GUILayout.Label("IMPORTANT SINON CA MARCHE PAS ");
        model = (GameObject)EditorGUILayout.ObjectField("Modele de base", model, typeof(GameObject), true);

        GUILayout.Label("Code ? (une seule lettre et en majuscule)");
        code = GUILayout.TextField(code);

        GUILayout.Label("Position x ");
        x = EditorGUILayout.FloatField(x);

        GUILayout.Label("Position y");
        y = EditorGUILayout.FloatField(y);

        if (GUILayout.Button("Ajouter la frappe dans la liste actuelle"))
        {
            if (sequence >= sequences.Count)
            {
                sequences.Add(new SequenceInput());
            }

            KeyCode c = KeyCode.A;
            for(int i = 97; i <= 122; i++)
            {
                if (((KeyCode)i).ToString() == code.ToUpper())
                {
                    c = (KeyCode)i;
                }
            }

            DataInput sI = new DataInput(c, new Vector2(x, y));
            sequences[sequence].dI.Add(sI);
        }

        if (GUILayout.Button("Supprimer la derniere frappe de la liste actuelle"))
        {
            if (sequences[sequence].dI.Count > 0)
            {
                sequences[sequence].dI.RemoveAt(sequences[sequence].dI.Count - 1);
            }
        }

        if (GUILayout.Button("Liste de frappe suivante"))
        {
            sequence++;
            if (sequence >= sequences.Count)
            {
                sequences.Add(new SequenceInput());
            }
        }

        if (GUILayout.Button("Liste de frappe precedente"))
        {
            sequence = Mathf.Max(0, sequence - 1);
        }

        EditorGUILayout.LabelField("Index : " + sequence.ToString());
        foreach(SequenceInput sI in sequences)
        {
            foreach(string s in sI.ToStringAlt())
            {
                EditorGUILayout.LabelField(s);
            }
        }

        GUILayout.Label("Sons Optionnels (en prendra un par defaut si aucun n'est choisi)");
        clpFail = (AudioClip)EditorGUILayout.ObjectField("Mauvaise touche ", clpFail, typeof(AudioClip), true);
        clpSuccess = (AudioClip)EditorGUILayout.ObjectField("Bonne touche ", clpSuccess, typeof(AudioClip), true);
        clpSuccessScenette = (AudioClip)EditorGUILayout.ObjectField("Fin scenette positive ", clpSuccessScenette, typeof(AudioClip), true);


        if (GUILayout.Button("Créer"))
        {
            GameObject instance;
            instance = Instantiate(model);
            instance.name = nameObject;
            Scenette scn = instance.GetComponent<Scenette>();
            scn.sequencesToDo = new List<SequenceInput>(sequences);
            scn.speedBandeauMultipler = vitesseBandeauMultipler;
            scn.timeBeforeNext = delaiBandeau;
            scn.mutliplerSpeedEnter = vitesseInsertion;
            scn.failClic = clpFail;
            scn.successClic = clpSuccess;
            scn.successScenette = clpSuccessScenette;
            scn.animPourHero = anim;
            scn.backgroundSprite = sprt;
            scn.textSizeDefeat = textSizeDefeat;
            scn.textSizeVictory = textSizeVictory;
            scn.textVictory = textVictory;
            scn.textDefeat = textDefeat;
            scn.init();

            sequences = new List<SequenceInput>();
        }
    }
Ejemplo n.º 17
0
    public float RaycastHorizontal(float distance)
    {
        RaycastHit hit = new RaycastHit();

        Vector3 actualSize = new Vector3(selfCollider.size.x * selfTr.lossyScale.x * skinWidthMultiplier, selfCollider.size.y * selfTr.lossyScale.y, selfCollider.size.z * selfTr.lossyScale.z);

        if (Physics.BoxCast(selfTr.position + selfCollider.center, actualSize * 0.5f, Vector3.right * Mathf.Sign(distance), out hit, selfTr.rotation, Mathf.Abs(distance), checkMask))
        {
            float startPoint = selfTr.position.x + selfCollider.center.x + selfCollider.size.x * 0.5f * Mathf.Sign(distance);
            float newDistance = Mathf.Sign(distance) * Mathf.Abs(hit.point.x - startPoint);

            if (distance < 0) flags.left = true;
            if (distance > 0) flags.right = true;

            lastHorizontalHitResult = hit;

            return newDistance;
        }

        lastHorizontalHitResult = hit;

        if (distance < 0) flags.left = false;
        if (distance > 0) flags.right = false;

        return distance;
    }
Ejemplo n.º 18
0
 void Update()
 {
     chargeCounter.fillAmount = Mathf.Lerp(chargeCounter.fillAmount, (float)Plugin.charges / Plugin.Config.maxCharges, .03f);
     chargeCountText.text     = Plugin.charges.ToString();
 }
Ejemplo n.º 19
0
    // Update is called once per frame
    void Update()
    {
        if (!dead)
        {
            if (!hurt)
            {
                //movement
                if (!playerTracking)
                {
                    if (!delay)
                    {
                        if (isRight)//walking right
                        {
                            sr.flipX = false;
                            switchBox();
                            myAnim.SetBool("WALK", true);
                            if (transform.position.x - tether.x > distance)
                            {
                                delay = true;
                                myBod.velocity = new Vector2(0, myBod.velocity.y);
                            }
                            else
                            {
                                myBod.velocity = new Vector2(speed, myBod.velocity.y);
                            }
                        }
                        else//walking left
                        {
                            sr.flipX = true;
                            switchBox();
                            myAnim.SetBool("WALK", true);

                            if (transform.position.x - tether.x < (distance * -1))
                            {
                                delay = true;
                                myBod.velocity = new Vector2(0, myBod.velocity.y);
                            }
                            else
                            {
                                myBod.velocity = new Vector2((speed * -1), myBod.velocity.y);
                            }
                        }

                        stopTimer += Time.deltaTime;
                        if (stopTimer > 0.1)
                        {
                            stopTimer = 0;
                            if (stopCheck == transform.position.x)
                            {
                                delay = true;
                            }
                            stopCheck = transform.position.x;
                        }
                    }
                    else
                    {
                        myAnim.SetBool("WALK", false);
                        walkDelay += Time.deltaTime;

                        if (walkDelay >= 1.5)
                        {
                            isRight = !isRight;
                            delay = false;
                            walkDelay = 0;
                        }
                    }
                }
                else//track player
                {
                    if (playDistanceX < 0)
                    {
                        sr.flipX = true;
                    }
                    else
                    {
                        sr.flipX = false;
                    }
                    switchBox();

                    if (Mathf.Abs(playDistanceX) > 1.5)
                    {
                        myAnim.SetBool("WALK", true);
                        if (playDistanceX < 0)
                        {
                            myBod.velocity = new Vector2(-speed, myBod.velocity.y);
                        }
                        else
                        {
                            myBod.velocity = new Vector2(speed, myBod.velocity.y);
                        }
                        atkTimer = 0;
                    }
                    else//call attack
                    {
                        myAnim.SetBool("WALK", false);
                        atkTimer += Time.deltaTime;
                        myBod.velocity = new Vector2(0, myBod.velocity.y);
                        myAnim.SetBool("ATK1", false);
                        myAnim.SetBool("ATK2", false);
                        if (atkTimer >= 0.75)
                        {
                            attack();
                            atkTimer = -1;
                        }
                    }
                }

                //check to track player
                playDistanceX = playTrack.transform.position.x - transform.position.x;
                playDistanceY = playTrack.transform.position.y - transform.position.y;
                //print(playDistanceX);
                if ((Mathf.Abs(playDistanceX) < 5 && Mathf.Abs(playDistanceY) < 5) && !playTrack.GetComponent<playercontroller>().getDead())
                {
                    playerTracking = true;
                }
                else if ((Mathf.Abs(playDistanceX) < 15 && Mathf.Abs(playDistanceY) < 15) && !playTrack.GetComponent<playercontroller>().getDead() && playerTracking)
                {
                    playerTracking = true;
                }
                else
                {
                    playerTracking = false;
                }


                //dying
                if (health <= 0)
                {
                    myAnim.SetBool("DIE", true);
                    dead = true;
                }
            }

            //getting hit
            if (hurt)
            {
                if (myAnim.GetBool("HURT") == false)
                {
                    health--;
                }

                myAnim.SetBool("HURT", true);
            }
            else
            {
                myAnim.SetBool("HURT", false);
            }
        }
        else
        {
            //myBox.size = new Vector2(0.57f, 0.83f);
            //myBox.offset = new Vector2(myBox.offset.x, -0.45f);
            myBox.enabled = false;
            myBod.constraints = RigidbodyConstraints2D.FreezePosition;
            sr.material.color = new Color(1.0f, 1.0f, 1.0f, alph);
            alph -= 0.01f;
            if (alph <= 0)
            {
                playTrack.GetComponent<playercontroller>().monstersKilled++;
                Destroy(gameObject);
            }
        }
    }
Ejemplo n.º 20
0
        private void Update()
        {
            for (int i = 0; i < _currentObjects.Count; i++)
            {
                keep(i, false);
            }

            if (_hasTarget)
            {
                var vector = _targetPosition - transform.position;

                for (int i = 0; i < Physics.RaycastNonAlloc(transform.position, vector, _hits, vector.magnitude); i++)
                {
                    var hit = _hits[i];
                    var obj = hit.collider.gameObject;

                    if (!hit.collider.isTrigger && (_target == null || !Util.InHiearchyOf(obj, _target)))
                    {
                        // Check if already fading
                        int oldIndex = indexOf(_currentObjects, obj);
                        if (oldIndex >= 0)
                        {
                            keep(oldIndex, true);
                            continue;
                        }

                        // Check if was being removed
                        oldIndex = indexOf(_oldObjects, obj);
                        if (oldIndex >= 0)
                        {
                            _currentObjects.Add(_oldObjects[oldIndex]);
                            keep(_currentObjects.Count - 1, true);
                            _oldObjects.RemoveAt(oldIndex);
                            continue;
                        }

                        // Create and add
                        {
                            FadedObject faded;
                            faded.Fade          = 0;
                            faded.Object        = obj;
                            faded.KeepThisFrame = true;

                            var gotRenderers = obj.GetComponentsInChildren <MeshRenderer>();
                            faded.Renderers = new FadedRenderer[gotRenderers.Length];

                            for (int k = 0; k < gotRenderers.Length; k++)
                            {
                                FadedRenderer renderer;
                                renderer.Renderer          = gotRenderers[k];
                                renderer.OriginalMaterial  = Material.Instantiate(renderer.Renderer.material);
                                renderer.NewMaterial       = Material.Instantiate(renderer.Renderer.material);
                                renderer.OriginalColor     = renderer.OriginalMaterial.color;
                                renderer.Renderer.material = renderer.NewMaterial;
                                renderer.Renderer.gameObject.SendMessage("OnFade", SendMessageOptions.DontRequireReceiver);

                                faded.Renderers[k] = renderer;
                            }

                            _currentObjects.Add(faded);
                        }
                    }
                }
            }

            for (int i = _currentObjects.Count - 1; i >= 0; i--)
            {
                if (!_currentObjects[i].KeepThisFrame)
                {
                    _oldObjects.Add(_currentObjects[i]);
                    _currentObjects.RemoveAt(i);
                }
            }

            for (int i = 0; i < _currentObjects.Count; i++)
            {
                var value = _currentObjects[i];
                value.Fade = Mathf.Lerp(value.Fade, 1.0f, Time.deltaTime * Speed);
                fade(value.Renderers, value.Fade);

                _currentObjects[i] = value;
            }

            for (int i = _oldObjects.Count - 1; i >= 0; i--)
            {
                var value = _oldObjects[i];
                value.Fade = Mathf.Lerp(value.Fade, 0, Time.deltaTime * Speed);
                fade(value.Renderers, value.Fade);

                if (value.Fade > float.Epsilon)
                {
                    _oldObjects[i] = value;
                }
                else
                {
                    foreach (var renderer in _oldObjects[i].Renderers)
                    {
                        renderer.Renderer.material = renderer.OriginalMaterial;
                        renderer.Renderer.gameObject.SendMessage("OnUnfade", SendMessageOptions.DontRequireReceiver);
                    }

                    _oldObjects.RemoveAt(i);
                }
            }
        }
    void Update()
    {
        if (PauseMenu.IsOn)
        {
            if (Cursor.lockState != CursorLockMode.None)
            {
                Cursor.lockState = CursorLockMode.None;
            }

            motor.Move(Vector3.zero);
            motor.Rotate(Vector3.zero);
            motor.RotateCamera(0f);

            return;
        }


        if (Cursor.lockState != CursorLockMode.Locked)
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

        //Calculate how high the player should float above ground
        RaycastHit _hit;

        if (Physics.Raycast(transform.position, Vector3.down, out _hit, 100f, environmentMask))
        {
            joint.targetPosition = new Vector3(0f, -_hit.point.y, 0f);
        }
        else
        {
            joint.targetPosition = new Vector3(0f, 0f, 0f);
        }

        //calculate movement velocity as a 3D vector
        float xMov = Input.GetAxisRaw("Horizontal");
        float zMov = Input.GetAxisRaw("Vertical");

        Vector3 movHorizontal = transform.right * xMov;
        Vector3 movVertical   = transform.forward * zMov;

        //Final Movement Vector
        Vector3 _velocity = (movHorizontal + movVertical).normalized * speed;

        //Apply movement
        //Takes our velocity above and sends it to motor script
        motor.Move(_velocity);

        //Calculate rotation as a 3D vector
        //Lets us turn the player with the mouse
        float yRot = Input.GetAxisRaw("Mouse X");

        Vector3 _rotation = new Vector3(0f, yRot, 0f) * horizontalSensitivity;

        //Apply rotation
        motor.Rotate(_rotation);

        //Calculate camera rotation as a 3D vector
        //Lets us turn the camera with the mouse
        float xRot = Input.GetAxisRaw("Mouse Y");

        float _cameraRotationX = xRot * verticalSensitivity;

        //Apply rotation
        motor.RotateCamera(_cameraRotationX);

        //Calculate thruster force based on input
        Vector3 _thrusterForce = Vector3.zero;

        if (Input.GetButton("Jump") && thrusterFuelAmount > 0f)
        {
            thrusterFuelAmount -= thrusterFuelBurnSpeed * Time.deltaTime;

            if (thrusterFuelAmount >= 0.02f)
            {
                _thrusterForce = Vector3.up * thrusterForce;
                SetJointSettings(0f);
            }
        }
        else
        {
            thrusterFuelAmount += thrsuterFuelRegenSpeed * Time.deltaTime;

            SetJointSettings(jointSpring);
        }

        thrusterFuelAmount = Mathf.Clamp(thrusterFuelAmount, 0f, 1f);

        //Apply Thruster Force
        motor.ApplyThruster(_thrusterForce);
    }
Ejemplo n.º 22
0
 public float CalculateWeight(float strength, float currentTime)
 {
     if (time == 0) return 0;
     var coeff = Mathf.Lerp(80.0f, 16.0f, strength);
     return Mathf.Exp((time - currentTime) * coeff);
 }
Ejemplo n.º 23
0
    // Update is called once per frame
    void Update()
    {
        if (PlayerPrefs.GetInt("invertgravity", 0) == 0)
        {
            Physics.gravity = new Vector3(-Mathf.Abs(Physics.gravity.x), -Mathf.Abs(Physics.gravity.y), -Mathf.Abs(Physics.gravity.z));
        }
        if (PlayerPrefs.GetInt("invertgravity", 0) == 1)
        {
            Physics.gravity = new Vector3(Mathf.Abs(Physics.gravity.x), Mathf.Abs(Physics.gravity.y), Mathf.Abs(Physics.gravity.z));
        }
        if (active == true)
        {
            if (PlayerPrefs.GetInt("invertgravity", 0) == 0)
            {
                GameObject.Find("Toggle").GetComponent <Toggle>().isOn = false;
            }
            if (PlayerPrefs.GetInt("invertgravity", 0) == 1)
            {
                GameObject.Find("Toggle").GetComponent <Toggle>().isOn = true;
            }

            GameObject.Find("SpeedSlider").GetComponent <Slider>().value =
                GameObject.Find("birdy").GetComponent <MoveBird>().speed / .75f;
            exists = false;
            GameObject.Find("SpeedSlider").GetComponent <Slider>().onValueChanged.AddListener(new_speed);
            GameObject.Find("ReturnButton").GetComponent <Button>().onClick.AddListener(go_back);
            GameObject.Find("DefualtsButton").GetComponent <Button>().onClick.AddListener(defaults);
            GameObject.Find("Toggle").GetComponent <Toggle>().onValueChanged.AddListener(invert);
        }
    }
Ejemplo n.º 24
0
    // Returns true if the target is being attacked from the rear.
    // Doesn't include attacks from the left or right.
    private bool IsBackstab(ObjectMechanics target)
    {
        float rotation1 = target.transform.eulerAngles.y;
        float rotation2 = transform.eulerAngles.y;

        return(VeryApproximateMatch(Mathf.Abs(rotation1 - rotation2), 0.0f) || VeryApproximateMatch(Mathf.Abs(rotation1 - rotation2), 360.0f));
    }
Ejemplo n.º 25
0
    public static void ProcessInboundStream(ulong _uiLatency, CNetworkStream _cStream)
    {
		List<INetworkVar> cSyncedNetworkVars = new List<INetworkVar>();
		float fSyncedTick = 0.0f;

		if (CNetwork.IsServer)
		{
			fSyncedTick  = ((float)RakNet.RakNet.GetTimeMS()) / 1000.0f;
			fSyncedTick -= Mathf.Floor(fSyncedTick);
			fSyncedTick *= CNetworkServer.k_fSendRate;
		}
		else
		{
			fSyncedTick = CNetwork.Connection.Tick - ((float)_uiLatency / 1000.0f);

			if (fSyncedTick < 0.0f)
			{
				fSyncedTick = CNetworkServer.k_fSendRate - fSyncedTick;
				//Debug.Log(fSyncedTick);
			}
		}

        while (_cStream.HasUnreadData)
        {
            // Extract owner network view id
            CNetworkViewId cNetworkViewId = _cStream.ReadNetworkViewId();

            // Extract procedure type
            EProdecure eProcedure = (EProdecure)_cStream.ReadByte();

            // Retrieve network view instance
            CNetworkView cNetworkView = CNetworkView.FindUsingViewId(cNetworkViewId);
			
            // Process network var sync procedure
            if (eProcedure == EProdecure.SyncNetworkVar)
            {
                // Extract network var identifier
                byte bNetworkVarIdentifier = _cStream.ReadByte();

                // Retrieve network var instance
                INetworkVar cNetworkVar = cNetworkView.m_mNetworkVars[bNetworkVarIdentifier];

                // Retrieve network var type
                Type cVarType = cNetworkVar.GetValueType();

                // Extract value serialized
                object cNewVarValue = _cStream.ReadType(cVarType);

                // Sync with new value
				cNetworkVar.SyncValue(cNewVarValue, fSyncedTick);

				// Add to callback list
				cSyncedNetworkVars.Add(cNetworkVar);
            }

            // Process network rpc procedure
            else if (eProcedure == EProdecure.InvokeNetworkRpc)
            {
                // Extract rpc method identifier
                byte bMethodIdentifier = _cStream.ReadByte();

                // Retrieve method owner instance
                Component cParentComponent = cNetworkView.m_mNetworkRpcs[bMethodIdentifier].cUnityComponent;

                // Retrieve method info
                MethodInfo cMethodInfo = cNetworkView.m_mNetworkRpcs[bMethodIdentifier].cMethodInfo;

                // Extract method parameters
                object[] caParameterValues = _cStream.ReadMethodParameters(cMethodInfo);

                // Invoke the rpc method
                cMethodInfo.Invoke(cParentComponent, caParameterValues);
            }
        }

		// Invoke callbacks for synced network vars
		foreach (INetworkVar cSyncedNetworkVar in cSyncedNetworkVars)
		{
			cSyncedNetworkVar.InvokeSyncCallback();
		}
    }
Ejemplo n.º 26
0
	void Update ()
    {
        isActive = bossArea.GetComponent<Boss2Area>().playerIsInside;
        if(isActive)
        {
            rend.flipY = false;

            if (this.gameObject.GetComponent<Rigidbody2D>().velocity.x == 0)
            {
                animator.SetBool("FrontFly", true);
                animator.SetBool("LeftFly", false);
                animator.SetBool("RightFly", false);
            }
            else if (this.gameObject.GetComponent<Rigidbody2D>().velocity.x > 0)
            {
                animator.SetBool("FrontFly", false);
                animator.SetBool("LeftFly", false);
                animator.SetBool("RightFly", true);
            }
            else if (this.gameObject.GetComponent<Rigidbody2D>().velocity.x < 0)
            {
                animator.SetBool("FrontFly", false);
                animator.SetBool("LeftFly", true);
                animator.SetBool("RightFly", false);
            }

            if (state == 0)
            {
                float dist = this.GetComponent<Transform>().position.y - state0Position.transform.position.y;
                dist = Mathf.Abs(dist);
                this.gameObject.tag = "Deadly";

                if (dist > 0.01)
                {
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;

                    if (randomSpeedDirState0 == 0)
                        randomSpeedDirState0 = Random.Range(50, 150);

                    if (randomSpeedDirState0 > 100)
                        state0SpeedDir = 1;
                    else
                        state0SpeedDir = -1;

                    Vector2 moveToPos = new Vector2(1, state0Position.position.y - this.gameObject.transform.position.y);
                    moveToPos.Normalize();

                    this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(moveToPos.x * state0SpeedDir * 5, moveToPos.y * 5);
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();
                }
                else
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePositionY;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                    this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(maxSpeed * speedDir, 0);

                    if (health <= 0 && !state0Phase3)
                    {
                        state0Phase3 = true;
                        stalactites3.gameObject.SetActive(false);
                        state = 1;
                    }

                    if (health <= maxHealth * 1 / 3 && !state0Phase2)
                    {
                        state0Phase2 = true;
                        stalactites2.gameObject.SetActive(false);
                        state = 1;
                    }

                    if (health <= maxHealth * 2 / 3 && !state0Phase1)
                    {
                        state0Phase1 = true;
                        stalactites1.gameObject.SetActive(false);
                        state = 1;
                    }
                }

            }
            if (state == 1)
            {
                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;

                distanceToSpawn = this.GetComponent<Transform>().position.x - state1position.transform.position.x;
                distanceToSpawn = Mathf.Abs(distanceToSpawn);

                this.gameObject.tag = "Deadly";

                if (distanceToSpawn >= 0.1)
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();
                    rend.flipY = false;
                    Vector2 moveToPos = new Vector2(state1position.position.x - this.gameObject.transform.position.x, state1position.position.y - this.gameObject.transform.position.y);
                    moveToPos.Normalize();

                    this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPos * 5;
                }
                else
                {
                    rend.flipY = true;
                    animator.SetTrigger("Summon");
                    this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;

                    //Spawn enemies
                    if (state0Phase1 && !state0Phase2 && !state0Phase3)
                        maxEnemies = maxEnemiesCopy;
                    else if (state0Phase1 && state0Phase2 && !state0Phase3)
                        maxEnemies = maxEnemiesCopy * 1.5f;
                    else if (state0Phase1 && state0Phase2 && state0Phase3)
                    {
                        maxEnemies = maxEnemiesCopy * 2f;
                        lastState1 = true;
                    }

                    if (GameObject.Find("Player").GetComponent<Death>().dead)
                    {
                        counter = 0;
                        time = Time.time;
                        spawned = false;
                    }


                    if (counter < maxEnemies && Time.time > time + timeToSpawn)
                    {
                        if (!spawned)
                        {
                            GameObject newEnemy;

                            position = Random.Range(0.0f, distance) + batSpawnLeft.position.x;
                            batSpawn.position = new Vector2(position, batSpawn.transform.position.y);

                            Transform newPosition;
                            newPosition = Instantiate<Transform>(newBat, batSpawn);

                            newEnemy = Instantiate<GameObject>(enemies, newPosition);
                            newEnemy.GetComponent<Transform>().localScale = new Vector3(0.4f, 0.4f, 1);
                            newEnemy.GetComponent<bat>().maxSpeed = Random.Range(1.3f, 2f);
                            enemyCopy = newEnemy;
                            spawned = true;
                        }
                        else
                        {
                            collided = enemyCopy.GetComponent<bat>().collided;
                            if (collided)
                            {
                                counter++;
                                time = Time.time;
                                spawned = false;
                            }
                        }
                    }
                    else if (counter >= maxEnemies)
                    {
                        counter = 0;
                        if (!lastState1)
                        {
                            state = 0;
                            randomSpeedDirState0 = 0;

                            if (state0Phase2)
                                stalactites3.SetActive(true);
                            else if (state0Phase1)
                                stalactites2.SetActive(true);
                        }
                        else
                            state = 2;
                    }
                }

            }
            else if (state == 2)
            {
                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                animator.SetBool("Knocked", false);
                float distThis = this.GetComponent<Transform>().position.x - state1position.transform.position.x;
                distThis = Mathf.Abs(distThis);
                this.gameObject.tag = "Deadly";

                if (distThis > 0.1)
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();
                    SFXManager.GetComponent<SFXControllerLevel2>().stopBatScream();
                    rend.flipY = false;
                    Vector2 moveToPos = new Vector2(state1position.position.x - this.gameObject.transform.position.x, state1position.position.y - this.gameObject.transform.position.y);
                    moveToPos.Normalize();

                    this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPos * 5;
                }
                else
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().stopBatFly();
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatScream();
                    rend.flipY = true;
                    animator.SetTrigger("Summon");
                    if (timeForShake == 0)
                        timeForShake = Time.time;

                    else if (timeForShake + timeShaking > Time.time)
                    {
                        this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
                        CameraShake.Shake(timeShaking, shakeMag);
                        GameObject.Find("Player").GetComponent<PlayerController>().enabled = false;
                        GameObject.Find("Player").GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
                    }
                    else
                    {
                        state = 3;
                        timeForShake = 0;
                        fallTime = Time.time;
                        attackOnceAfterState2 = true;
                        GameObject.Find("Player").GetComponent<PlayerController>().enabled = true;
                    }

                    if (batHit)
                    {
                        batHit = false;
                        this.gameObject.tag = "Enemy";
                        resistance--;
                    }

                }
            }
            else if (state == 3)
            {
                if (fallTime == 0)
                    fallTime = Time.time;

                dist = this.GetComponent<Transform>().position.y - state3Position.transform.position.y;
                dist = Mathf.Abs(dist);

                if (Time.time > fallTime + nextFall)
                    startFall = true;

                this.gameObject.tag = "Deadly";

                if (startFall)
                {
                    moveToPlayer = new Vector2(GameObject.Find("Player").GetComponent<Transform>().position.x - this.GetComponent<Transform>().position.x, GameObject.Find("Player").GetComponent<Transform>().position.y - this.GetComponent<Transform>().position.y);
                    moveToPlayer.Normalize();

                    this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPlayer * fallSpeed;

                    falling = true;

                    initFallPos = this.GetComponent<Transform>().position.x;

                    distanceToPlayerX = GameObject.Find("Player").GetComponent<Transform>().position.x - this.GetComponent<Transform>().position.x;
                    distanceToPlayerX = Mathf.Abs(distanceToPlayerX);
                    startFall = false;

                    fallTime = 50 * Time.time;
                    falls++;
                }


                if (falling)
                {
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                    this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPlayer * fallSpeed;

                    if (groundCol)
                    {
                        if (falls == 4)
                        {
                            this.gameObject.tag = "Enemy";
                            if (Time.time < timeOnGround + timeGround)
                            {
                                animator.SetBool("Knocked", true);
                                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
                            }
                            else
                            {
                                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                                this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                                falls = 0;
                                falling = false;
                                fallTime = Time.time;
                                nextFall = Random.Range(2f, 3f);
                            }
                        }
                        else
                        {
                            this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                            this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                            falling = false;
                            groundCol = false;
                            fallTime = Time.time;
                            nextFall = Random.Range(2f, 3f);
                        }
                    }
                    else { SFXManager.GetComponent<SFXControllerLevel2>().playBatFly(); }
                }
                else if (dist > 0.01f && !falling)
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();
                    SFXManager.GetComponent<SFXControllerLevel2>().stopBatScream();
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                    animator.SetBool("Knocked", false);
                    if (initFallPos == 0)
                    {
                        Vector2 moveToPos = new Vector2(state3Position.position.x - this.gameObject.transform.position.x, state3Position.position.y - this.gameObject.transform.position.y);
                        moveToPos.Normalize();

                        this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPos * 10;
                    }
                    else
                    {
                        Vector2 moveToPos = new Vector2(initFallPos + 2 * speedDir * distanceToPlayerX - this.gameObject.transform.position.x, state3Position.position.y - this.gameObject.transform.position.y);
                        moveToPos.Normalize();

                        this.gameObject.GetComponent<Rigidbody2D>().velocity = moveToPos * 10;
                    }
                }
                else if (dist <= 0.01f && !falling)
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playBatFly();

                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePositionY;
                    this.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
                    this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(maxSpeed * speedDir, 0);
                }

                if (batHit)
                {
                    state = 2;
                    this.gameObject.tag = "Enemy";
                    SFXManager.GetComponent<SFXControllerLevel2>().stopBatFly();
                    timeForShake = 0;
                }
            }
            else if(state == 4)
            {
                activateCave = true;
                if (!sound)
                {
                    SFXManager.GetComponent<SFXControllerLevel2>().playFall();
                    sound = true;
                }
            }

            if (resistance == 2)
                exitRock.GetComponent<RockBoss>().health = 3;
            else if (resistance == 1)
                exitRock.GetComponent<RockBoss>().health = 2;
            else if (resistance == 0 && !updated)
            {
                exitRock.GetComponent<RockBoss>().health = 1;
                updated = true;
            }

            if (exitRock.GetComponent<RockBoss>().batDie && state != 4)
                state = 4;
        }    
        else
        {
            SFXManager.GetComponent<SFXControllerLevel2>().stopBatFly();
        }
    }
Ejemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        /*
         * this section is for debugging on PC
         */
        isJumping = Input.GetKeyDown(jumpPressed);
        jumpedLeft = Input.GetKeyDown(left);
        jumpedRight = Input.GetKey(right);

        debugText.text = "jumpedRight: " + jumpedRight + " jumpedLeft: " + jumpedLeft + " isJumping: " + isJumping;

        controller.Move(runSpeed * Time.fixedDeltaTime, (jumpedRight || jumpedLeft), isJumping);


        if (Input.touchCount == 1) // user is touching the screen with a single touch
        {
            Touch touch = Input.GetTouch(0); // get the touch
            if (touch.phase == TouchPhase.Began) //check for the first touch
            {
                fp = touch.position;
                lp = touch.position;
            }
            else if (touch.phase == TouchPhase.Moved) // update the last position based on where they moved
            {
                lp = touch.position;
            }
            else if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
            {
                lp = touch.position;  //last touch position. Ommitted if you use list

                //Check if drag distance is greater than 20% of the screen height
                if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
                {//It's a drag
                 //check if the drag is vertical or horizontal
                    if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
                    {   //If the horizontal movement is greater than the vertical movement...
                        if ((lp.x > fp.x))  //If the movement was to the right)
                        {   //Right swipe
                            Debug.Log("Right Swipe");
                            debugText.text = "Swipe right";
                            controller.Move((runSpeed * 1.2f) * Time.fixedDeltaTime, true, false);
                        }
                        else
                        {   //Left swipe
                            debugText.text = "Swipe left";
                            controller.Move((runSpeed * 1.2f) * Time.fixedDeltaTime, true, false);
                        }
                    }
                    else
                    {   //the vertical movement is greater than the horizontal movement
                        if (lp.y > fp.y)  //If the movement was up
                        {   //Up swipe
                            debugText.text = "Swipe up";
                            controller.Move(0, false, true);
                        }
                        else
                        {   //Down swipe
                            debugText.text = "swipe down";
                            // Maybe implement something on down swipe if needed
                            //controller.Move(0 * Time.fixedDeltaTime, true, isJumping);
                        }
                    }
                }
                else
                {   //It's a tap as the drag distance is less than 20% of the screen height
                    Debug.Log("Tap");
                    controller.Move((runSpeed * 1.05f) * Time.fixedDeltaTime, true, false);
                }
            }
        }
    }
Ejemplo n.º 28
0
Archivo: WCR.cs Proyecto: Keyansn/FYP
    float move(float dist, float i, float j)
    {
        float abs = (float)Mathf.Abs(i - j);

        return((0.5f) * (dist - abs) * ((i - j) / abs));
    }
        private void DoCacheServerSettings()
        {
            GUILayout.Space(10);
            GUILayout.Label(Content.cacheServer, EditorStyles.boldLabel);

            var overrideAddress = CacheServerPreferences.GetCommandLineRemoteAddressOverride();
            if (overrideAddress != null)
            {
                EditorGUILayout.HelpBox("Cache Server remote address forced via command line argument. To use the cache server address specified here please restart Unity without the -CacheServerIPAddress command line argument.", MessageType.Info, true);
            }

            int index = Mathf.Clamp((int)m_CacheServerMode.intValue, 0, cacheServerModePopupList.Length - 1);
            CreatePopupMenu(Content.mode.text, cacheServerModePopupList, index, SetCacheServerMode);

            if (index != (int)CacheServerMode.Disabled)
            {
                bool isCacheServerEnabled = true;

                if (index == (int)CacheServerMode.AsPreferences)
                {
                    if (CacheServerPreferences.IsCacheServerV2Enabled)
                    {
                        var cacheServerIP = CacheServerPreferences.CachesServerV2Address;
                        cacheServerIP = string.IsNullOrEmpty(cacheServerIP) ? "Not set in preferences" : cacheServerIP;
                        EditorGUILayout.HelpBox(cacheServerIP, MessageType.None, false);
                    }
                    else
                    {
                        isCacheServerEnabled = false;
                        EditorGUILayout.HelpBox("Disabled", MessageType.None, false);
                    }
                }

                if (isCacheServerEnabled)
                {
                    m_CacheServerList.DoLayoutList();

                    EditorGUILayout.BeginHorizontal();

                    if (GUILayout.Button("Check Connection", GUILayout.Width(150)))
                    {
                        if (InternalEditorUtility.CanConnectToCacheServer())
                            m_CacheServerConnectionState = CacheServerConnectionState.Success;
                        else
                            m_CacheServerConnectionState = CacheServerConnectionState.Failure;
                    }

                    GUILayout.Space(25);

                    switch (m_CacheServerConnectionState)
                    {
                        case CacheServerConnectionState.Success:
                            EditorGUILayout.HelpBox("Connection successful.", MessageType.Info, true);
                            break;

                        case CacheServerConnectionState.Failure:
                            EditorGUILayout.HelpBox("Connection failed.", MessageType.Warning, true);
                            break;

                        case CacheServerConnectionState.Unknown:
                            GUILayout.Space(44);
                            break;
                    }

                    EditorGUILayout.EndHorizontal();
                }
            }
        }
Ejemplo n.º 30
0
 bool CheckYMargin()
 {
     return(Mathf.Abs(transform.position.y - cameraTarget.position.y) > YMargin);
 }