Beispiel #1
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (!isServer)
        {
            NetworkLerp();
            return;
        }
        else if (state == (int)State.Unavailable)  //servidor so faz lerp se pickedup sheeps (unica situacao em que cliente tem autoridade sobre elas)
        {
            NetworkLerp();
            return;
        }

        GameObject closestPlayer = getClosestPlayer();

        if (closestPlayer != null)
        {
            if (canBeScared())
            {
                var opposite_direction = transform.position - closestPlayer.transform.position;
                scare(opposite_direction);
            }
        }
        else if (state == (int)State.Scared)
        {
            unscare();
        }

        switch (state)
        {
        case (int)State.Rotating:
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, ROTATION_SPEED * Time.fixedDeltaTime);
            float angle = Quaternion.Angle(transform.rotation, targetRotation);
            if (angle == 0)
            {
                state = (int)State.Moving;
            }

            break;

        case (int)State.Moving:

            transform.position = Vector3.MoveTowards(transform.position, targetDestination, MOVING_SPEED * Time.fixedDeltaTime);
            if (Vector3.Distance(transform.position, targetDestination) < 0.01f)
            {
                state = (int)State.Waiting;
            }

            break;

        case (int)State.Scared:
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, SCARED_ROTATION_SPEED * Time.fixedDeltaTime);
            transform.position = Vector3.MoveTowards(transform.position, targetDestination, SCARED_MOVING_SPEED * Time.fixedDeltaTime);

            break;

        case (int)State.Flying:
            // TO DO: change to detect collision with ground and then check if sheep is immobile for a few frames
            // so that sheep is not available immediatly as it touches the ground)
            // (other alternative is to immediatly stop the sheep as it touches the ground - this eliminates the sheep's sliding,
            // and would be more coherent with the UI trajectory and target)
            Debug.Log("Flying: " + transform.position.y);
            if (transform.position.y < 0.51)
            {
                Debug.Log("JUST LANDED :D");
                state = (int)State.Available;
                // IAnimState animState = new Iddle(ref m_animator);
                // SetAnimState(animState);
                // sheepCollideWithBases(transform.gameObject, true);
                ignoreCollisionWithPlayers(transform.gameObject, true);
                // SendLandSheepMessage(transform.gameObject.name);
            }

            /*
             *
             * if ((int)(transform.position.y*10) <= (int)(getHeightOfTerrainAt() + sheepFeetFromFloor) * 10)
             * {
             *  Debug.Log("SHEEP: " + (transform.position.y) + " TERRAIN: " + ((getHeightOfTerrainAt() + sheepFeetFromFloor)));
             *  Debug.Log("TODO: DEBUG THIS");
             *  state = (int)State.Available;
             * }
             */
            break;
        }

        animState = animState.next(state);

        if (!canSendNetworkMovement)
        {
            canSendNetworkMovement = true;
            StartCoroutine(StartNetworkSendCooldown());
        }
    }
Beispiel #2
0
        /// <summary>
        /// Called every frame from Robot.update() if it's the current state (top of the stack)
        /// </summary>
        /// <param name="r">The robot to update</param>
        public override void update(Robot r)
        {
            bool finished = false;

            ////////////////////////////////////////////////////////////////////////////////////////
            // Initialize variables if necessary when first enter state
            ////////////////////////////////////////////////////////////////////////////////////////
            if (!initialized)
            {
                initialized = true;
                resume      = true; // Turn state requires same behavior when initializing and resuming
            }

            ////////////////////////////////////////////////////////////////////////////////////////
            // Reset variables if robot is returning from another state
            ////////////////////////////////////////////////////////////////////////////////////////
            if (resume)
            {
                resume = false;

                initialRotation = r.body.transform.rotation;

                Vector3 target = new Vector3(targetPosition.x, r.body.transform.position.y, targetPosition.y);

                if (target - r.body.transform.position != Vector3.zero)
                {
                    targetRotation = Quaternion.LookRotation(target - r.body.transform.position, Vector3.up);

                    float angle = Quaternion.Angle(initialRotation, targetRotation);

                    while (angle < 0)
                    {
                        angle += 360;
                    }

                    if (angle > 180)
                    {
                        angle = 360 - 180;
                    }

                    timeToTurn = angle / angularSpeed;
                }
                else
                {
                    timeTaken = timeToTurn;
                }
            }

            ////////////////////////////////////////////////////////////////////////////////////////
            // Update
            ////////////////////////////////////////////////////////////////////////////////////////
            if (timeTaken < timeToTurn)
            {
                timeTaken += Time.deltaTime;
                float progress          = timeTaken / timeToTurn;
                float sphericalProgress = progress - Mathf.Sin(2 * Mathf.PI * progress) / (2 * Mathf.PI);// Mathf.Atan(10 * (progress - 0.5f)) / 2.8f + 0.5f;// (Mathf.Cos(2 * Mathf.PI * progress + Mathf.PI) + 1) / 2.0f;
                r.body.transform.rotation = Quaternion.Lerp(initialRotation, targetRotation, sphericalProgress);
            }
            else
            {
                finished = true;
            }

            ////////////////////////////////////////////////////////////////////////////////////////
            // Process messages: no, should happen in another state
            ////////////////////////////////////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////////////////////////////////////
            // "Clean up" robot state
            ////////////////////////////////////////////////////////////////////////////////////////
            if (finished)
            {
                // Pop state off the stack
                r.popState();
            }
        }
        private void UpdateControlTransform()
        {
            // On a new touch, record the start position.
            if (GvrControllerInput.TouchDown)
            {
                // Threshold and remap input to be -1 to 1.
                touchDownPositionY = GvrControllerInput.TouchPosCentered.y;
                // While touching, calculate the touchpad drag distance.
            }
            else if (GvrControllerInput.IsTouching)
            {
                ZDistanceFromSwipe();
                if (rotationOnTouch && !swiping)
                {
                    RotationFromTouch();
                }
            }

            // Compute orientation delta from selection.
            targetOrientationDelta = ControlRotation * InverseControllerOrientation;

            // If we are smoothing orientation, do it!
            if (orientationSmoothingTime > 0)
            {
                // Adjust speed of smoothing based on the distance between the target offset, and current offset.
                float speed = Quaternion.Angle(orientationDelta, targetOrientationDelta);
                speed = Mathf.Clamp01(speed / MAX_ANGULAR_DELTA);
                float smoothedDeltaTime = (speed * Time.deltaTime) / orientationSmoothingTime;
                // Apply the delta.
                orientationDelta = Quaternion.Slerp(orientationDelta,
                                                    targetOrientationDelta,
                                                    smoothedDeltaTime);
                // Otherwise assign it directly.
            }
            else
            {
                orientationDelta = targetOrientationDelta;
            }

            // Assign the rotation of the control transform.
            if (maintainFacing)
            {
                controlTransformRotation = orientationDelta * objectStartRotation * targetRotationDelta;
            }
            else
            {
                controlTransformRotation = orientationDelta * targetRotationDelta;
            }

            // Assign the position of the control transform.
            controlTransformPosition = controlZDistance *
                                       (orientationDelta * normalizedForward) +
                                       ControlPosition;

            // Get the distance between the control transform and the controller transform.
            Vector3 targetToControl = ControlPosition - controlTransformPosition;

            // Increase tension when the control transform is closer to the controller transform.
            controlTension = Mathf.Clamp01((distanceFromControllerMax - distanceFromControllerMin) /
                                           (targetToControl.magnitude - distanceFromControllerMin + 0.0001f));

            // Modifies movement responsiveness based on the mass of the rigidbody.
            weightScale = Mathf.Clamp((MAX_MASS / rigidbodyCmp.mass), MIN_MASS, MAX_MASS);
        }
Beispiel #4
0
    public static Quaternion ConstantSlerp(Quaternion from, Quaternion to, float angle)
    {
        float t = Mathf.Min(1f, angle / Quaternion.Angle(from, to));

        return(Quaternion.Slerp(from, to, t));
    }
        void FixedUpdate()
        {
            // If you pick the thing up, remove joint to the other thing
            if (isHeld() && !wasHeld)
            {
                if (transform.parent.gameObject.GetComponent <FixedJoint>() != null)
                {
                    DestroyImmediate(transform.parent.gameObject.GetComponent <FixedJoint>());
                    ObjectProperties boom = gameObject.GetComponentInParent <ObjectProperties>();
                    if (boom != null)
                    {
                        boom.enabled = true;
                    }
                    else
                    {
                        Debug.Log("No boom");
                    }
                    contact = null;
                }
                wasHeld = true;
            }

            // Snap to the thing if magnets are touching
            if (wasHeld && !isHeld() && contact != null)
            {
                float angle = Quaternion.Angle(transform.parent.rotation, contact.transform.rotation);
                if (angle > 15f)
                {
                    //GameObject.Find("Nope").GetComponent<AudioSource>().Play();
                    Debug.Log("Angle too high! " + angle);
                }
                else
                {
                    transform.parent.rotation = Quaternion.Euler(contact.transform.rotation.eulerAngles);
                    transform.parent.gameObject.AddComponent <FixedJoint>();
                    GetComponentInParent <FixedJoint>().connectedBody = contact.GetComponentInParent <Rigidbody>();
                    ObjectProperties boom = gameObject.GetComponentInParent <ObjectProperties>();
                    if (boom != null)
                    {
                        boom.enabled = false;
                    }
                    else
                    {
                        Debug.Log("No boom");
                    }

                    // Do explosion or something here (Depending on if first word of name matches magnet name [eg: "*POE* Variant" -> "*POE*Magnet"] )
                    if (contact.transform.name.Contains(transform.parent.name.Split(' ')[0]))
                    {
                        GameObject.Find("Ding").GetComponent <AudioSource>().Play();
                    }
                    else
                    {
                        GameObject.Find("Crash").GetComponent <AudioSource>().Play();
                        explosionsSystem.Play(true);
                        smokeSystem.Play(true);
                    }
                }
            }

            if (!isHeld() && wasHeld)
            {
                wasHeld = false;
            }
        }
Beispiel #6
0
 private bool HasMoved()
 {
     return((double)(this.m_Target.localPosition - this.m_PrevPosition).sqrMagnitude > 9.99999974737875E-06 || (double)Quaternion.Angle(this.m_Target.localRotation, this.m_PrevRotation) > 9.99999974737875E-06);
 }
Beispiel #7
0
    // Update is called once per frame
    void Update()
    {
        if (!GameManager.cutscenePlaying)
        {
            // IF THE PLAYER IS DANCING, LOOK AT PLAYER BUT WAIT FIRST
            // IF THE PLAYER DANCES WHILE RETURNING, COMMIT TO LOOK (LOOK WITHOUT WAITING)
            if ((GameManager.dancing || player.gameObject.GetComponent <PlayerBehavior>().cheating) &&
                !player.gameObject.GetComponent <PlayerBehavior>().canThrown&&
                ((player.gameObject.transform.position.x >= this.gameObject.transform.position.x && !isThirdPassenger) ||
                 (player.gameObject.transform.position.z >= this.gameObject.transform.position.z && isThirdPassenger)))
            {
                decideToLook = true;
                actualTarget = player.gameObject.transform.position;
                if (returning)
                {
                    commitToLook = true;
                }
            }
            else
            {
                decideToLook = false;
            }

            // IF DECIDED TO LOOK, DO THIS STUFF
            if (decideToLook || commitToLook)
            {
                distance = Vector3.Distance(transform.position, actualTarget);
                if (!commitToLook)
                {
                    waitBeforeLook += Time.deltaTime;
                }
                if (waitBeforeLook >= (distance / 9f))
                {
                    waitBeforeLook = 0;
                    commitToLook   = true;
                }
                if (commitToLook)
                {
                    Quaternion q = Quaternion.LookRotation(actualTarget - transform.position);
                    transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);
                    if (Quaternion.Angle(transform.rotation, q) <= 1)
                    {
                        waitBeforeReturn += Time.deltaTime;
                        if (waitBeforeReturn >= 2f)
                        {
                            commitToLook = false;
                            returning    = true;
                        }
                    }
                }
            }
            // RETURN TO REGULAR LOOKING POSITION
            else if (!player.gameObject.GetComponent <PlayerBehavior>().canThrown)
            {
                waitBeforeReturn = 0;
                Quaternion q = Quaternion.LookRotation(neutralLook - transform.position);
                transform.rotation = Quaternion.RotateTowards(transform.rotation, q, returnRotateSpeed * Time.deltaTime);
                if (Quaternion.Angle(transform.rotation, q) <= 1f)
                {
                    returning      = false;
                    waitBeforeLook = 0f;
                }
            }

            if (player.gameObject.GetComponent <PlayerBehavior>().canThrown /*&& !player.gameObject.GetComponent<PlayerBehavior>().pickedUp*/ && !commitToLook)
            {
                if (!decideToLookAtCan)
                {
                    waitBeforeLook += Time.deltaTime;
                }
                if (waitBeforeLook >= 0.5f)
                {
                    waitBeforeLook    = 0;
                    decideToLookAtCan = true;
                }

                if (decideToLookAtCan)
                {
                    canTarget = can.gameObject.transform;
                    Quaternion q = Quaternion.LookRotation((canTarget.position /*+ new Vector3(0, 2.8f, 0)*/) - transform.position);
                    transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);
                    if (Quaternion.Angle(transform.rotation, q) <= 1)
                    {
                        waitBeforeReturn += Time.deltaTime;
                        if (waitBeforeReturn >= 4f)
                        {
                            player.gameObject.GetComponent <PlayerBehavior>().canThrown = false;
                            decideToLookAtCan = false;
                            waitBeforeLook    = 0f;
                        }
                    }
                }
            }
        }
    }
Beispiel #8
0
    virtual protected void Update()
    {
        switch (state)
        {
        case TreeState.InSeed:
            break;

        case TreeState.Growing:
            _timer += Time.deltaTime;
            graphicalModel.localScale = Vector3.Lerp(startScale, originScale, _timer);
            if (graphicalModel.localScale == originScale)
            {
                state = TreeState.Grown;
            }
            break;

        case TreeState.Grown:
            break;

        case TreeState.WaitDomino:
            if (dominoDelayTime < 0)
            {
                _timer = 0;
                state  = TreeState.Falling;
            }
            else
            {
                dominoDelayTime -= Time.deltaTime;
            }
            break;

        case TreeState.Falling:
            if (Quaternion.Angle(graphicalModel.rotation, fallingQuat) < 1f)
            {
                gameObject.SetActive(false);
                graphicalModel.rotation = Quaternion.identity;
                p3Scene.Instance.treesInScene.Remove(this);
                cell.RemoveTree();
                cell.HighLightOn(false);
                cell.SelectedOn(false);
                cell.AuraOn(false);
                ActivateOnFall(choper);

                if (dealDmg)
                {
                    var c = cell.Get(fx, fz);
                    if (c != null)
                    {
                        if (c.player != null)
                        {
                            c.player.OnBeingChoped(choper, 0);
                        }
                    }
                }
                break;
            }
            _timer += Time.deltaTime;
            graphicalModel.rotation = Quaternion.Lerp(Quaternion.identity, fallingQuat, _timer);

            break;
        }
    }
Beispiel #9
0
        public static float InverseSlerp(Quaternion a, Quaternion b, Quaternion value)
        {
            float angle = Quaternion.Angle(a, b);

            return(angle < float.Epsilon ? 0.0f : Quaternion.Angle(a, value) / angle);
        }
    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            if (this.m_SynchronizePosition)
            {
                this.m_Direction      = transform.position - this.m_StoredPosition;
                this.m_StoredPosition = transform.position;

                stream.SendNext(transform.position);
                stream.SendNext(this.m_Direction);
            }

            if (this.m_SynchronizeRotation)
            {
                stream.SendNext(transform.rotation);
            }

            if (this.m_SynchronizeScale)
            {
                stream.SendNext(transform.localScale);
            }
        }
        else
        {
            if (this.m_SynchronizePosition)
            {
                this.m_NetworkPosition = (Vector3)stream.ReceiveNext();
                this.m_Direction       = (Vector3)stream.ReceiveNext();

                if (m_firstTake)
                {
                    transform.position = this.m_NetworkPosition;
                    this.m_Distance    = 0f;
                }
                else
                {
                    float lag = Mathf.Abs((float)(PhotonNetwork.Time - info.SentServerTime));
                    this.m_NetworkPosition += this.m_Direction * lag;
                    this.m_Distance         = Vector3.Distance(transform.position, this.m_NetworkPosition);
                }
            }

            if (this.m_SynchronizeRotation)
            {
                this.m_NetworkRotation = (Quaternion)stream.ReceiveNext();

                if (m_firstTake)
                {
                    this.m_Angle       = 0f;
                    transform.rotation = this.m_NetworkRotation;
                }
                else
                {
                    this.m_Angle = Quaternion.Angle(transform.rotation, this.m_NetworkRotation);
                }
            }

            if (this.m_SynchronizeScale)
            {
                transform.localScale = (Vector3)stream.ReceiveNext();
            }

            if (m_firstTake)
            {
                m_firstTake = false;
            }
        }
    }
    void move(Monster target)
    {
        if (GameManager.me.stageManager.playTime - _infoShowTime > 0.5f)
        {
            _m = (int)(VectorUtil.Distance(GameManager.me.player.cTransformPosition.x, mon.cTransformPosition.x) * 0.01f);

            if (_m != _infoValue)
            {
                GameManager.me.uiManager.uiPlay.lbChaser.text = "-" + _m + "m";
                _infoValue    = _m;
                _infoShowTime = GameManager.me.stageManager.playTime;
            }
        }


        _target = target;

        mon.attackPosition = Util.getPositionByAngleAndDistanceXZ(0, mon.stat.atkRange + _target.damageRange + mon.damageRange);          // hitrange
        //mon.action.delay = 0.3f;

        _v = _target.cTransformPosition + mon.attackPosition;

        if (VectorUtil.DistanceXZ(_target.cTransformPosition, mon.cTransformPosition) <= mon.stat.atkRange + _target.damageRange + mon.damageRange)          // hitrange
        {
            _v = _target.cTransformPosition - mon.cTransformPosition;

            _q = Util.getLookRotationQuaternion(_v);
            // 자리를 다 잡았으면 공격...
            mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime);

            if ((mon.action.delay > 0 || Xfloat.greaterThan(Quaternion.Angle(_q, mon.tf.rotation), 5)) || _target.isEnabled == false)
            {
                mon.state         = Monster.NORMAL;
                mon.action.delay -= GameManager.globalDeltaTime;
            }
            else
            {
                mon.action.state = CharacterAction.STATE_ACTION;
            }
        }
        else if (mon.cTransformPosition.x + mon.attackPosition.x >= _target.cTransformPosition.x && VectorUtil.Distance(_v.z, mon.cTransformPosition.z) < 5)
        {
            //Debug.Log("1");

            _v = _target.cTransformPosition - mon.cTransformPosition;

            _q = Util.getLookRotationQuaternion(_v);
            // 자리를 다 잡았으면 공격...
            mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime);

            if ((mon.action.delay > 0 || Xfloat.greaterThan(Quaternion.Angle(_q, mon.tf.rotation), 5)) || _target.isEnabled == false)
            {
                mon.state         = Monster.NORMAL;
                mon.action.delay -= GameManager.globalDeltaTime;
            }
            else
            {
                mon.action.state = CharacterAction.STATE_ACTION;
            }
        }
        else
        {
            _v = _target.cTransformPosition + mon.attackPosition;
            _q = Util.getLookRotationQuaternion(_v - mon.cTransformPosition);
            mon.tf.rotation = Util.getFixedQuaternionSlerp(mon.tf.rotation, _q, CharacterAction.rotationSpeed * GameManager.globalDeltaTime);

            _v   = mon.cTransformPosition + mon.tf.forward * mon.stat.speed * GameManager.globalDeltaTime;
            _v.y = 0;

            mon.setPlayAniRightNow(Monster.WALK);
            mon.animation[Monster.WALK].speed = 0.3f;
            mon.setPosition(_v);
        }
    }
        protected override void Awake()
        {
            base.Awake();

            Transform[] childTransforms = gameObject.GetComponentsInChildren <Transform>();
            doorHandles  = new List <Transform>();
            myHitHelpers = new FPEDoorAndDrawerHitHelper[2];

            foreach (Transform t in childTransforms)
            {
                if (t.name == "SwingingPart")
                {
                    swingingPart = t;
                }
                else if (t.name.Contains("DoorHandle") && t.gameObject.GetComponent <FPEInteractableActivateScript>())
                {
                    doorHandles.Add(t);
                }
                else if (t.name == "SwingInSide")
                {
                    swingInSide = t;
                }
                else if (t.name == "SwingOutSide")
                {
                    swingOutSide = t;
                }
                else if (t.name == "SafeZoneSwingIn")
                {
                    safeZoneSwingIn = t;
                }
                else if (t.name == "SafeZoneSwingOut")
                {
                    safeZoneSwingOut = t;
                }
                else if (t.name == "DoorActionLookTarget")
                {
                    doorActionLookTarget = t;
                }
                else if (t.name == "HitHelperOpen" && t.gameObject.GetComponent <FPEDoorAndDrawerHitHelper>())
                {
                    myHitHelpers[(int)eDoorActionType.OPEN] = t.gameObject.GetComponent <FPEDoorAndDrawerHitHelper>();
                }
                else if (t.name == "HitHelperClose" && t.gameObject.GetComponent <FPEDoorAndDrawerHitHelper>())
                {
                    myHitHelpers[(int)eDoorActionType.CLOSE] = t.gameObject.GetComponent <FPEDoorAndDrawerHitHelper>();
                }
            }

            maxSwingDegreesPerSecond = Mathf.Abs(swingAngle / swingOpenTimeInSeconds);
            closedRotation           = Quaternion.identity;
            openRotation             = closedRotation * Quaternion.Euler(new Vector3(0f, swingAngle, 0f));

            if (startOpened)
            {
                currentDoorState = eDoorState.OPEN;
                setDoorHandleInteractionStrings(closeDoorString);
            }
            else
            {
                setDoorHandleInteractionStrings(openDoorString);
            }

            doorSpeaker = gameObject.GetComponent <AudioSource>();

            // Error Checking //

            // Doors must have swinging parts and at least one door handle
            if (!swingingPart || doorHandles.Count == 0)
            {
                Debug.Log("FPESwingingDoor:: Door '" + gameObject.name + "' is missing a required part. Attempting to fix.", gameObject);

                // Attempt some automatic fixes
#if UNITY_EDITOR
                if (swingingPart == null)
                {
                    GameObject swingingPartFix = new GameObject("SwingingPart");
                    swingingPartFix.transform.parent        = gameObject.transform;
                    swingingPartFix.transform.localPosition = new Vector3(-1.0f, 1.5f, -0.251f);
                    swingingPart = swingingPartFix.transform;
                }

                if (doorHandles.Count == 0)
                {
                    GameObject doorHandleFix = new GameObject("DoorHandle");
                    doorHandleFix.AddComponent <BoxCollider>();
                    doorHandleFix.AddComponent <FPEInteractableActivateScript>();
                    doorHandleFix.transform.parent        = swingingPart;
                    doorHandleFix.transform.localPosition = Vector3.zero;
                    doorHandles.Add(doorHandleFix.transform);
                    Debug.LogWarning("FPEDoor:: Door '" + gameObject.name + "' DoorHandle child has no Activation Event assigned. Door Handle interaction will do nothing until it is assigned. Also remember to make the Event Fire Type be 'EVERYTIME'.", gameObject);
                }
#endif
            }

            // Some angles are not valid and will result in weird first time swings
            if (swingAngle == 0f)
            {
                Debug.LogWarning("FPESwingingDoor:: Door '" + gameObject.name + "' has a swingAngle of zero. This door will not work.", gameObject);
            }
            else
            {
                float deltaA = Quaternion.Angle(swingingPart.localRotation, openRotation);
                float deltaB = Quaternion.Angle(swingingPart.localRotation, closedRotation);

                if (Mathf.Abs(deltaA) > Mathf.Abs(swingAngle) || Mathf.Abs(deltaB) > Mathf.Abs(swingAngle))
                {
                    Debug.LogWarning("FPESwingingDoor:: Door '" + gameObject.name + "''s 'SwingingPart' starting rotation is outside defined swingAngle's range. First open/close actions will not behave as expected.", gameObject);
                }
            }

            if (stopIfDoorHitsSomething && (myHitHelpers[(int)eDoorActionType.OPEN] == null || myHitHelpers[(int)eDoorActionType.CLOSE] == null))
            {
                Debug.LogWarning("FPESwingingDoor:: Door '" + gameObject.name + "' is configured to stop if door hits something, but it is missing child FPEDoorAndDrawerHitHelper objects 'HitHelperOpen' and/or 'HitHelperClose'. Door will not stop when it hits something.", gameObject);
            }

            // Safe zones are optional, but are required if you've set the flag to auto move the player
            if (autoMovePlayerToSafeZones && (!swingInSide || !swingOutSide || !safeZoneSwingIn || !safeZoneSwingOut || !doorActionLookTarget))
            {
                Debug.Log("FPESwingingDoor:: Door '" + gameObject.name + "' is configured to automatically move the player into safe zones, but has no safe zones defined. Attempting to fix");

                // Attempt some automatic fixes (these assume swingAngle is 135, which is the default, which is likely
                // the value since these fixes really only happen if you just add this script to an empty game object)
#if UNITY_EDITOR
                GameObject interactionZoneFix = new GameObject("PlayerInteractionZones");
                interactionZoneFix.transform.parent        = gameObject.transform;
                interactionZoneFix.transform.localPosition = Vector3.zero;

                if (swingInSide == null)
                {
                    GameObject swingInsideFix = new GameObject("SwingInSide");
                    swingInsideFix.transform.parent        = interactionZoneFix.transform;
                    swingInsideFix.transform.localPosition = new Vector3(0.345f, 0.474f, 0.054f);
                    swingInSide = swingInsideFix.transform;
                }

                if (swingOutSide == null)
                {
                    GameObject swingOutSideFix = new GameObject("SwingOutSide");
                    swingOutSideFix.transform.parent        = interactionZoneFix.transform;
                    swingOutSideFix.transform.localPosition = new Vector3(0.345f, 0.474f, -1.219f);
                    swingOutSide = swingOutSideFix.transform;
                }

                if (safeZoneSwingIn == null)
                {
                    GameObject safeZoneSwingInFix = new GameObject("SafeZoneSwingIn");
                    safeZoneSwingInFix.transform.parent        = interactionZoneFix.transform;
                    safeZoneSwingInFix.transform.localPosition = new Vector3(-0.07f, 0.98f, 0.92f);
                    safeZoneSwingIn = safeZoneSwingInFix.transform;
                }

                if (safeZoneSwingOut == null)
                {
                    GameObject safeZoneSwingOutFix = new GameObject("SafeZoneSwingOut");
                    safeZoneSwingOutFix.transform.parent        = interactionZoneFix.transform;
                    safeZoneSwingOutFix.transform.localPosition = new Vector3(1.0f, 0.98f, -1.66f);
                    safeZoneSwingOut = safeZoneSwingOutFix.transform;
                }

                if (doorActionLookTarget == null)
                {
                    GameObject lookTargetFix = new GameObject("DoorActionLookTarget");
                    lookTargetFix.transform.parent        = interactionZoneFix.transform;
                    lookTargetFix.transform.localPosition = new Vector3(0.741f, 1.568f, -0.161f);
                    doorActionLookTarget = lookTargetFix.transform;
                }
#endif
            }

            if (playSounds && doorSpeaker == null)
            {
                Debug.Log("FPESwingingDoor:: Door '" + gameObject.name + "' is configured to play sounds but has no AudioSource. Attempting to fix.", gameObject);

                // Attempt some automatic fixes
#if UNITY_EDITOR
                gameObject.AddComponent <AudioSource>();
                doorSpeaker = gameObject.GetComponent <AudioSource>();
#endif
            }
        }
        protected override void Update()
        {
            base.Update();

            if (currentDoorState == eDoorState.CLOSED)
            {
                // Do nothing
            }
            else if (currentDoorState == eDoorState.CLOSING)
            {
                if ((stopIfDoorHitsSomething == true && doorHitSomething() == false) || stopIfDoorHitsSomething == false)
                {
                    swingingPart.localRotation = Quaternion.RotateTowards(swingingPart.localRotation, closedRotation, maxSwingDegreesPerSecond * Time.deltaTime);
                    movePlayerCloserToSafeZone();

                    if (Mathf.Abs(Quaternion.Angle(swingingPart.localRotation, closedRotation)) <= doorSwingSnapAngle)
                    {
                        swingingPart.localRotation = closedRotation;

                        if (playSounds && doorLatchSounds)
                        {
                            doorLatchSounds.Play(doorSpeaker);
                        }

                        setDoorHandleInteractionStrings(openDoorString);
                        currentDoorState = eDoorState.CLOSED;
                        releasePlayerFromSafeZone();
                    }
                }
                else
                {
                    if (playSounds && doorBlockedSounds)
                    {
                        doorBlockedSounds.Play(doorSpeaker);
                    }

                    currentDoorState = eDoorState.BLOCKED_PARTLY_CLOSED;
                    setDoorHandleInteractionStrings(openDoorString);
                    releasePlayerFromSafeZone();
                }
            }
            else if (currentDoorState == eDoorState.OPENING)
            {
                if ((stopIfDoorHitsSomething == true && doorHitSomething() == false) || stopIfDoorHitsSomething == false)
                {
                    swingingPart.localRotation = Quaternion.RotateTowards(swingingPart.localRotation, openRotation, maxSwingDegreesPerSecond * Time.deltaTime);
                    movePlayerCloserToSafeZone();

                    if (Mathf.Abs(Quaternion.Angle(swingingPart.localRotation, openRotation)) <= doorSwingSnapAngle)
                    {
                        swingingPart.localRotation = openRotation;
                        setDoorHandleInteractionStrings(closeDoorString);
                        currentDoorState = eDoorState.OPEN;
                        releasePlayerFromSafeZone();
                    }
                }
                else
                {
                    if (playSounds && doorBlockedSounds)
                    {
                        doorBlockedSounds.Play(doorSpeaker);
                    }

                    currentDoorState = eDoorState.BLOCKED_PARTLY_OPEN;
                    setDoorHandleInteractionStrings(closeDoorString);
                    releasePlayerFromSafeZone();
                }
            }
            else if (currentDoorState == eDoorState.OPEN)
            {
                // Do nothing
            }
            else if (currentDoorState == eDoorState.BLOCKED_PARTLY_OPEN)
            {
                // Do nothing
            }
            else if (currentDoorState == eDoorState.BLOCKED_PARTLY_CLOSED)
            {
                // Do nothing
            }
        }
    void OnGUI()
    {
        var speed = 0.1f;

        GUI.skin.button.fontSize = 20;
        if (!isRotate)
        {
            if (GUI.Button(new Rect(30 * m_fScaleWidth, 735 * m_fScaleHeight, 80 * m_fScaleWidth, 30 * m_fScaleHeight), "正视图"))
            {
                isRotate           = true;
                to                 = Quaternion.Euler(90, -90, -90);
                transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.time * speed);

                //  this.transform.eulerAngles = new Vector3(0,90,0);
                // this.transform.rotation = Quaternion.Euler(0, 0, 0);
            }
        }
        else
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.deltaTime * 5);
            if (Quaternion.Angle(to, transform.rotation) < 1)
            {
                transform.rotation = to;
                isRotate           = false;
                //   Debug.Log(isRotate);
            }
        }



        if (!isRotate)
        {
            if (GUI.Button(new Rect(130 * m_fScaleWidth, 735 * m_fScaleHeight, 80 * m_fScaleWidth, 30 * m_fScaleHeight), "左视图"))
            {
                isRotate = true;
                to       = Quaternion.Euler(0, -90, -90);
                //   this.transform.rotation = Quaternion.Euler(0, 270, 0);
                transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.time * speed);
            }
        }
        else
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.deltaTime * 5);
            if (Quaternion.Angle(to, transform.rotation) < 1)
            {
                transform.rotation = to;
                isRotate           = false;
            }
        }



        if (!isRotate)
        {
            if (GUI.Button(new Rect(230 * m_fScaleWidth, 735 * m_fScaleHeight, 80 * m_fScaleWidth, 30 * m_fScaleHeight), "俯视图"))
            {
                isRotate           = true;
                to                 = Quaternion.Euler(180, -180, -180);
                transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.time * speed);
                // this.transform.rotation = Quaternion.Euler(270, 0, 0);
            }
        }
        else
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, to, Time.deltaTime * 5);
            if (Quaternion.Angle(to, transform.rotation) < 1)
            {
                transform.rotation = to;
                isRotate           = false;
            }
        }
    }
Beispiel #15
0
    void Move()
    {
        Vector3 direction = new Vector3(joyStick.Horizontal, 0f, joyStick.Vertical).normalized;

        #region Xu Ly Trong Luc
        if (controller.isGrounded && gravityY < 0)
        {
            isJump    = false;
            CanAttack = true;
            gravityY  = gravity;
        }
        if (!controller.isGrounded)
        {
            CanAttack = false;
            gravityY += gravity * Time.deltaTime;
        }
        #endregion
        #region Animation
        stepOffsetGround = Physics.CheckCapsule(transform.position, transform.position + Vector3.down * controller.stepOffset, groundDistance, groundMask);
        if (isJump || !stepOffsetGround && !controller.isGrounded)//Nhay
        {
            isGrounded            = false;
            controller.stepOffset = 0.05f;
        }
        else
        {
            isGrounded            = true; //Khong Nhay
            controller.stepOffset = 0.5f;
        }
        //3. Thiet Lap Animation
        anim.SetBool("Grounded", isGrounded);
        anim.SetBool("isJump", isJump);
        anim.SetBool("Attack", isAttack);
        if (direction == Vector3.zero)
        {
            Idle();
        }
        else if (!isAttack && isGrounded)
        {
            Run();
        }
        #endregion
        #region Tinh Toan Di Chuyen Theo Cam & Xoay
        //4. Tinh Toan Di Chuyen
        moveDir = Vector3.zero;
        if (direction.magnitude > 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            angle    = Quaternion.Euler(0f, targetAngle, 0f);
            moveDir  = (Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward);
            moveDir *= speed * SpeedDownAngleRotate(Quaternion.Angle(transform.rotation, angle));
        }
        //5. Xoay Player
        if (Quaternion.Angle(transform.rotation, angle) != 0 && CanRotation)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, angle, RotationSpeed * Time.deltaTime);
        }
        moveDir.y = gravityY;
        if (CanMove)
        {
            controller.Move(moveDir * Time.deltaTime);
        }
        #endregion
    }
Beispiel #16
0
        //Main extrude method
        private void Extrude(Vector3[] path)
        {
            extrudePoints = new Matrix4x4[path.Length];
            primitives    = new Primitive[path.Length];
            openClosed    = new int[path.Length];
            float currentLength = 0;

            extrudePoints[0] = new Matrix4x4();
            Vector3 pathDiff = (path[1] - path[0]);

            defaultRotateAngle           = 0;
            arrowTail.defaultRotateAngle = 0;
            //Calculate first point
            //First point rotation depends on first path point direction
            Quaternion lastDirectionX = calculateUpDownQuaternion(pathDiff);
            Quaternion lastDirectionY = calculateLeftRightQuaternion(pathDiff);

            extrudePoints[0].SetTRS(path[0], Quaternion.AngleAxis(rotateFunction.Evaluate(currentLength / pathLength * rotationFunctionLength) * 360, lastDirectionY * lastDirectionX * Vector2.up) * lastDirectionY * lastDirectionX, new Vector3(widthFunction.Evaluate(currentLength / pathLength * widthFunctionLength), 1, heightFunction.Evaluate(currentLength / pathLength * heightFunctionLength)));
            //choose shape to extrude
            int primitiveIndex = (int)(shapeFunction.Evaluate(0));

            if (primitiveIndex < 0)
            {
                primitiveIndex = 0;
            }
            if (primitiveIndex >= templatePrimitives.primitivesList.Count)
            {
                primitiveIndex = templatePrimitives.primitivesList.Count - 1;
            }
            primitives[0] = templatePrimitives.primitivesList[primitiveIndex];
            pathLength   -= arrowHead.getLength() + arrowTail.getLength();
            //Calculate next extrude matrixes
            for (int i = 1; i < path.Length; i++)
            {
                currentLength   += (path[i] - path[i - 1]).magnitude;
                extrudePoints[i] = new Matrix4x4();
                Quaternion nextDirectionX;
                Quaternion nextDirectionY;
                Quaternion extrudeDirectionX;
                Quaternion extrudeDirectionY;
                float      scaleWidthByAngle  = 1f;
                float      scaleHeightByAngle = 1f;
                if (i < path.Length - 1)
                {
                    pathDiff       = path[i + 1] - path[i];
                    nextDirectionX = calculateUpDownQuaternion(pathDiff);
                    nextDirectionY = calculateLeftRightQuaternion(pathDiff);
                    if (Quaternion.Angle(lastDirectionX, nextDirectionX) < 0.1f)
                    {
                        extrudeDirectionX = nextDirectionX;
                    }
                    else
                    {
                        extrudeDirectionX = Quaternion.Lerp(lastDirectionX, nextDirectionX, 0.5f);
                    }
                    if (Quaternion.Angle(lastDirectionY, nextDirectionY) < 0.1f)
                    {
                        extrudeDirectionY = nextDirectionY;
                    }
                    else
                    {
                        extrudeDirectionY = Quaternion.Lerp(lastDirectionY, nextDirectionY, 0.5f);
                    }
                    scaleWidthByAngle  = Mathf.Abs(Mathf.Cos(Mathf.Deg2Rad * Vector3.Angle(lastDirectionY * Vector3.forward, nextDirectionY * Vector3.forward) / 2));
                    scaleWidthByAngle  = (scaleWidthByAngle < 0.5f) ? 1 : 1 / scaleWidthByAngle;
                    scaleHeightByAngle = Mathf.Abs(Mathf.Cos(Mathf.Deg2Rad * Vector3.Angle(lastDirectionX * Vector3.up, lastDirectionX * Vector3.up) / 2));
                    scaleHeightByAngle = (scaleHeightByAngle < 0.5f) ? 1 : 1 / scaleHeightByAngle;
                }
                else
                {
                    pathDiff          = path[i] - path[i - 1];
                    nextDirectionX    = calculateUpDownQuaternion(pathDiff);
                    nextDirectionY    = calculateLeftRightQuaternion(pathDiff);
                    extrudeDirectionX = nextDirectionX;
                    extrudeDirectionY = nextDirectionY;
                }
                extrudePoints[i].SetTRS(path[i], Quaternion.AngleAxis(rotateFunction.Evaluate(currentLength / pathLength * rotationFunctionLength) * 360, extrudeDirectionY * extrudeDirectionX * Vector3.up) * extrudeDirectionY * extrudeDirectionX, new Vector3(scaleWidthByAngle * widthFunction.Evaluate(currentLength / pathLength * widthFunctionLength), 1, scaleHeightByAngle * heightFunction.Evaluate(currentLength / pathLength * heightFunctionLength)));
                primitiveIndex = (int)(shapeFunction.Evaluate(currentLength / pathLength * shapeFunctionLength));
                if (primitiveIndex < 0)
                {
                    primitiveIndex = 0;
                }
                if (primitiveIndex >= templatePrimitives.primitivesList.Count)
                {
                    primitiveIndex = templatePrimitives.primitivesList.Count - 1;
                }
                primitives[i]  = templatePrimitives.primitivesList[primitiveIndex];
                lastDirectionX = nextDirectionX;
                lastDirectionY = nextDirectionY;
            }
            arrowHead.defaultRotateAngle = defaultRotateAngle;
        }
Beispiel #17
0
 private void FixedUpdateServer()
 {
     if ((int)this.syncVarDirtyBits != 0 || !NetworkServer.active || (!this.isServer || (double)this.GetNetworkSendInterval() == 0.0) || (double)(this.m_Target.localPosition - this.m_PrevPosition).sqrMagnitude < (double)this.movementThreshold && (double)Quaternion.Angle(this.m_PrevRotation, this.m_Target.localRotation) < (double)this.movementThreshold)
     {
         return;
     }
     this.SetDirtyBit(1U);
 }
    // Head tracking
    private void HeadTrackingUpdate()
    {
        Vector3    lookPos        = target.position - headBone.position;
        Quaternion rotation       = Quaternion.LookRotation(lookPos);
        Quaternion targetRotation = headBone.rotation;

        if (Quaternion.Angle(rotation, headStartRotation * transform.rotation) <= headMaxTurnAngle || Quaternion.Angle(headBone.rotation, headStartRotation * transform.rotation) <= headMaxTurnAngle)
        {
            targetRotation = rotation;
        }
        headBone.rotation = Quaternion.Slerp(headBone.rotation, targetRotation, 1 - Mathf.Exp(-headTrackingTargetSpeed * Time.deltaTime));
    }
Beispiel #19
0
        protected override void Update()
        {
            base.Update();
            Ship[] ships = player.board.placementInfo.allShips.ToArray();

            foreach (Ship ship in ships)
            {
                if (ship.placementInfo.waypoints != null)
                {
                    ship.transform.position = Vector3.SmoothDamp(ship.transform.position, ship.placementInfo.waypoints[0], ref ship.placementInfo.animationVelocity, shipAnimationTravelTime, shipAnimationMaxSpeed);

                    if (Vector3.Distance(ship.transform.position, ship.placementInfo.waypoints[0]) < 0.1f)
                    {
                        ship.placementInfo.waypoints.RemoveAt(0);
                    }

                    if (ship.placementInfo.waypoints.Count == 0)
                    {
                        ship.placementInfo.waypoints = null;
                    }
                }

                Quaternion targetRotation = ship.tiles == null ? ship.placementInfo.localShipboxRotation : ship.placementInfo.boardRotation;
                ship.transform.rotation = Quaternion.RotateTowards(ship.transform.rotation, targetRotation, Mathf.Pow(Quaternion.Angle(ship.transform.rotation, targetRotation) * Time.deltaTime * 10.0f, 0.5f));
            }
        }
    private void Update()
    {
        // Remove expired points
        while (_pointCount > 0)
        {
            if (_points[_oldestPoint].TimeAlive > _segmentLifetime)
            {
                _oldestPoint++;
                _pointCount--;
                continue;
            }
            break;
        }

        // Do we add any new points?
        if (_emit)
        {
            // Make sure there are always at least 2 points when emitting
            if (_pointCount < 2)
            {
                if (_pointCount < 1)
                {
                    InsertPoint();
                }
                InsertPoint();
            }
        }

        var newestPointIndex = _oldestPoint + _pointCount;

        // wrap around to the beginning
        if (newestPointIndex >= _points.Length)
        {
            newestPointIndex -= _points.Length;
        }

        var secondNewestPointIndex = newestPointIndex + 1;

        if (secondNewestPointIndex >= _points.Length)
        {
            secondNewestPointIndex -= _points.Length;
        }

        if (_emit)
        {
            var add         = false;
            var sqrDistance = (_points[secondNewestPointIndex].Position - _source.transform.position).sqrMagnitude;
            if (sqrDistance > _minVertexDistance * _minVertexDistance)
            {
                if (sqrDistance > _maxVertexDistance * _maxVertexDistance)
                {
                    add = true;
                }
                else if (Quaternion.Angle(_source.transform.rotation, _points[secondNewestPointIndex].Rotation) > _maxAngle)
                {
                    add = true;
                }
            }
            if (add)
            {
                InsertPoint();
            }
            if (!add)
            {
                _points[newestPointIndex].Update(_source.transform);
            }
        }

        // Do we render this?
        if (_pointCount < 2)
        {
            _renderer.enabled = false;
            return;
        }
        _renderer.enabled = true;

        _lifeTimeRatio = 1 / _segmentLifetime;

        // Do we fade it out?
        if (!_emit)
        {
            if (_pointCount == 0)
            {
                return;
            }
            var color = _instanceMaterial.GetColor("_TintColor");
            color.a -= _fadeOutRatio * _lifeTimeRatio * Time.deltaTime;
            if (color.a > 0)
            {
                _instanceMaterial.SetColor("_TintColor", color);
            }
            return;
        }

        // Rebuild it
        _triangleBuffer.Clear();

        var uvMultiplier = 1 / (_points[_oldestPoint].TimeAlive - _points[newestPointIndex].TimeAlive);

        for (var i = 0; i < _pointCount; i++)
        {
            var v1 = i * 2;
            var v2 = i * 2 + 1;

            var wrappedIndex = i + _oldestPoint;
            if (wrappedIndex >= _points.Length)
            {
                wrappedIndex -= _points.Length;
            }

            var point = _points[wrappedIndex];
            var ratio = point.TimeAlive * _lifeTimeRatio;
            // Color
            Color32 color;
            if (_colors.Length == 0)
            {
                color = Color32.Lerp(new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 0), ratio);
            }
            else if (_colors.Length == 1)
            {
                color = Color32.Lerp(_colors[0], new Color32(255, 255, 255, 0), ratio);
            }
            else if (_colors.Length == 2)
            {
                color = Color32.Lerp(_colors[0], _colors[1], ratio);
            }
            else
            {
                var colorRatio = ratio * (_colors.Length - 1);
                var min        = (int)Mathf.Floor(colorRatio);
                var lerp       = Mathf.InverseLerp(min, min + 1, colorRatio);
                color = Color32.Lerp(_colors[min], _colors[min + 1], lerp);
            }
            _colorBuffer[v1] = color;
            _colorBuffer[v2] = color;

            // Width
            float width;
            if (_widths.Length == 0)
            {
                width = 1;
            }
            else if (_widths.Length == 1)
            {
                width = _widths[0];
            }
            else if (_widths.Length == 2)
            {
                width = Mathf.Lerp(_widths[0], _widths[1], ratio);
            }
            else
            {
                var widthRatio = ratio * (_widths.Length - 1);
                var min        = (int)Mathf.Floor(widthRatio);
                var lerp       = Mathf.InverseLerp(min, min + 1, widthRatio);
                width = Mathf.Lerp(_widths[min], _widths[min + 1], lerp);
            }
            transform.position = point.Position;
            transform.rotation = point.Rotation;
            _vertexBuffer[v1]  = transform.TransformPoint(0, width * 0.5f, 0);
            _vertexBuffer[v2]  = transform.TransformPoint(0, -width * 0.5f, 0);

            // UVs
            var uvRatio = (point.TimeAlive - _points[newestPointIndex].TimeAlive) * uvMultiplier;
            _uvBuffer[v1] = new Vector2(uvRatio, 0);
            _uvBuffer[v2] = new Vector2(uvRatio, 1);

            if (i > 0)
            {
                // Triangles
                var vertIndex = i * 2;
                _triangleBuffer.Add(vertIndex - 2);
                _triangleBuffer.Add(vertIndex - 1);
                _triangleBuffer.Add(vertIndex - 0);

                _triangleBuffer.Add(vertIndex + 1);
                _triangleBuffer.Add(vertIndex + 0);
                _triangleBuffer.Add(vertIndex - 1);
            }
        }
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;
        _mesh.Clear();
        _mesh.vertices = _vertexBuffer;
        _mesh.colors32 = _colorBuffer;
        _mesh.uv       = _uvBuffer;
        _mesh.SetTriangles(_triangleBuffer, 0);
    }
    //0 = No side
    //1 = Left
    //2 = Right
    //3 = Dual

    public void Attack(int attackSide)
    {
        if (canAction)
        {
            // Lock on to nearby enemy
            // We can move this to a separate method
            Collider[] combatants = Physics.OverlapSphere(transform.position, lockOnRadius, combatantMask);
            if (combatants.Length > 0)
            {
                foreach (Collider combatant in combatants)
                {
                    Vector3 playerToCombatant = combatant.transform.position - transform.position;
                    playerToCombatant.y = 0f;
                    Quaternion rotationToCombatant = Quaternion.LookRotation(playerToCombatant);
                    if (Quaternion.Angle(transform.rotation, rotationToCombatant) < lockOnAngle)
                    {
                        transform.rotation = rotationToCombatant;
                        Debug.Log(gameObject.name + ": Locked onto " + combatant.name);
                        break;
                    }
                }
            }

            if (attackSide == 1)
            {
                // Left Punch
                animator.SetTrigger("Attack" + (3).ToString() + "Trigger");
                leftPunch.Attack(stats.attackPower, attackDuration, attackDelay);
            }
            else
            {
                // Right Punch
                animator.SetTrigger("Attack" + (6).ToString() + "Trigger");
                leftPunch.Attack(stats.attackPower, attackDuration, attackDelay);
            }


            StartCoroutine(_LockMovementAndAttack(0, .6f));

            //if (weapon == Weapon.UNARMED)
            //{
            //int maxAttacks = 3;
            //int attackNumber = 0;

            //if (attackSide == 1 || attackSide == 3)
            //{
            //    attackNumber = Random.Range(3, maxAttacks); // Left Hook
            //}
            //else if (attackSide == 2)
            //{
            //    attackNumber = Random.Range(6, maxAttacks + 3); // Right Hook
            //}
            //if (attackSide != 3)
            //{
            //    animator.SetTrigger("Attack" + (attackNumber).ToString() + "Trigger");

            //    StartCoroutine(_LockMovementAndAttack(0, .6f));
            //}
            //else
            //{
            //    // 2 Hand Attack
            //    animator.SetTrigger("AttackDual" + (attackNumber).ToString() + "Trigger");
            //    StartCoroutine(_LockMovementAndAttack(0, .75f));
            //}
            //}
            //else
            //{
            //    //  Armed Attack
            //    animator.SetTrigger("Attack" + (6).ToString() + "Trigger");
            //    StartCoroutine(_LockMovementAndAttack(0, .85f));
            //}
        }
    }
        public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
        {
            if (stream.IsWriting)
            {
                #region
                stream.SendNext(this.m_Body.position);
                stream.SendNext(this.m_Body.rotation);

                //m_SynchronizeVelocity)
                stream.SendNext(this.m_Body.velocity);

                //m_SynchronizeAngularVelocity
                stream.SendNext(this.m_Body.angularVelocity);

                //if(MImpact)stream.SendNext(MImpact.carControl.b_AccelerationImpact);


                #endregion
            }
            else
            {
                this.m_NetworkPosition = (Vector3)stream.ReceiveNext();
                this.m_NetworkRotation = (Quaternion)stream.ReceiveNext();

                this.m_NetworkWantedPos = this.m_NetworkPosition;
                this.m_NetworkWantedRot = this.m_NetworkRotation;

                if (this.m_TeleportEnabled)
                {
                    if (Vector3.Distance(this.m_Body.position, this.m_NetworkPosition) > this.m_TeleportIfDistanceGreaterThan)
                    {
                        this.m_Body.position = this.m_NetworkPosition;
                    }
                }


                float lag = Mathf.Abs((float)(PhotonNetwork.Time - info.SentServerTime));

                //m_SynchronizeVelocity
                this.m_Body.velocity    = (Vector3)stream.ReceiveNext();
                this.m_NetworkPosition += this.m_Body.velocity * lag /* fOffset*/;
                //this.m_Distance = Vector3.Distance(this.m_Body.position, this.m_NetworkPosition);


                //m_SynchronizeAngularVelocity)
                this.m_Body.angularVelocity = (Vector3)stream.ReceiveNext();
                this.m_NetworkRotation      = Quaternion.Euler(this.m_Body.angularVelocity * lag /* fOffset*/) * this.m_NetworkRotation;
                //this.m_Angle = Quaternion.Angle(this.m_Body.rotation, this.m_NetworkRotation);


                //Debug.Log(this.m_NetworkPosition);
                if (Ghost)
                {
                    Ghost.transform.position = this.m_NetworkPosition;
                }
                if (Ghost)
                {
                    Ghost.transform.rotation = this.m_NetworkRotation;
                }


                this.m_NetworkWantedPos += this.m_Body.velocity * lag /* * fOffset * fWantedPos*/;

                this.m_NetworkWantedPos += this.m_Body.velocity * .07f;


                this.m_Distance = Vector3.Distance(this.m_Body.position, this.m_NetworkWantedPos);


                /*
                 *  float distanceToLastPos = Vector3.Distance(this.m_Body.position, lastPosition);
                 *
                 *
                 *  lastPosition = this.m_Body.position;
                 *  lastDistance = this.m_Distance;
                 *
                 *
                 *  this.nextPos = this.m_NetworkWantedPos;
                 *  this.nextDistance = this.m_Distance;
                 */

                this.m_NetworkWantedRot = Quaternion.Euler(this.m_Body.angularVelocity * lag /* fOffset * fWantedPos*/) * this.m_NetworkWantedRot;
                this.m_Angle            = Quaternion.Angle(this.m_Body.rotation, this.m_NetworkWantedRot);

                if (CubeWantedPoos)
                {
                    CubeWantedPoos.transform.position = this.m_NetworkWantedPos;
                }
                if (CubeWantedPoos)
                {
                    CubeWantedPoos.transform.rotation = this.m_NetworkWantedRot;
                }

                //b_AccelerationImpact = (bool)stream.ReceiveNext();
            }
        }
        private void Update()
        {
            if (controls.IsControlsEnabled.Value && controls.IsPlayerControlsEnabled.Value)
            {
                if (isMoving)
                {
                    movementLerpValue += Time.deltaTime / fixedTimestep;

                    if (movementLerpValue >= 1)
                    {
                        movementLerpValue            -= 1;
                        isMoving                      = false;
                        avatar.RootTransform.position = targetPosition;
                    }
                    else
                    {
                        avatar.RootTransform.position = Vector3.Lerp(lastPosition, targetPosition, movementLerpValue);
                    }
                }

                if (isTurning)
                {
                    rotationLerpValue += Time.deltaTime / fixedTimestep;

                    if (rotationLerpValue >= 1)
                    {
                        rotationLerpValue -= 1;
                        isTurning          = false;
                        avatar.CharacterTransform.rotation = targetRotation;
                        DirectionArrowTransform.rotation   = avatar.CharacterTransform.rotation;
                        tabletControls.TabletFirstPersonCameraRoation.Value = avatar.CharacterTransform.rotation;
                    }
                    else
                    {
                        avatar.CharacterTransform.rotation = Quaternion.Lerp(lastRotation, targetRotation, rotationLerpValue);
                        DirectionArrowTransform.rotation   = avatar.CharacterTransform.rotation;
                        tabletControls.TabletFirstPersonCameraRoation.Value = avatar.CharacterTransform.rotation;
                    }
                }

                if (!isMoving && positionQueue.Count > 0)
                {
                    if ((avatar.RootTransform.position - positionQueue.Peek()).magnitude > maxMovementDistance)
                    {
                        avatar.RootTransform.position = positionQueue.Dequeue();
                    }
                    else
                    {
                        lastPosition   = avatar.RootTransform.position;
                        targetPosition = positionQueue.Dequeue();
                        isMoving       = true;
                    }
                }
                else if (!isMoving)
                {
                    movementLerpValue = 0;
                }

                if (!isTurning && rotationQueue.Count > 0)
                {
                    if (Quaternion.Angle(avatar.CharacterTransform.rotation, rotationQueue.Peek()) > maxRotationAngle)
                    {
                        avatar.CharacterTransform.rotation = rotationQueue.Dequeue();
                        DirectionArrowTransform.rotation   = avatar.CharacterTransform.rotation;
                        tabletControls.TabletFirstPersonCameraRoation.Value = avatar.CharacterTransform.rotation;
                    }
                    else
                    {
                        lastRotation = avatar.CharacterTransform.rotation;
                        DirectionArrowTransform.rotation = avatar.CharacterTransform.rotation;
                        tabletControls.TabletFirstPersonCameraRoation.Value = avatar.CharacterTransform.rotation;

                        targetRotation = rotationQueue.Dequeue();
                        isTurning      = true;
                    }
                }
                else if (!isTurning)
                {
                    rotationLerpValue = 0;
                }
            }
        }
Beispiel #24
0
    // Update is called once per frame
    void Update()
    {
        if (startingSlow < 1f)
        {
            startingSlow += Time.deltaTime / 4f;
        }

        Vector3 averagePosition = Vector3.zero;

        int   numDead     = 0;
        float maxDistance = 0f;

        for (int i = 0; i < targets.Length; i++)
        {
            for (int j = 0; j < targets.Length; j++)
            {
                if (targets[i].GetComponent <PlayerLife>().Alive&& targets[j].GetComponent <PlayerLife>().Alive)
                {
                    if (Vector3.Distance(targets[i].position, targets[j].position) > maxDistance)
                    {
                        maxDistance = Vector3.Distance(targets[i].position, targets[j].position);
                    }
                }
            }
        }

        maxDistance = Mathf.Max(maxDistance, 10f);

        foreach (Transform t in targets)
        {
            if (t.gameObject.activeSelf && t.GetComponent <PlayerLife>().Alive)
            {
                averagePosition += t.position;
            }
            else
            {
                numDead++;
            }
        }

        if (targets.Length <= numDead)
        {
            return;
        }

        averagePosition /= (targets.Length - numDead);

        GetComponent <Camera>().fieldOfView = LevelManager.instance.BeatValue(0f) / 2f + initialFOV;
        transform.GetChild(0).GetComponent <Camera>().fieldOfView = LevelManager.instance.BeatValue(0f) / 2f + initialFOV;

        transform.localPosition = Vector3.MoveTowards(transform.localPosition, averagePosition + offset * (maxDistance / 35f), Time.deltaTime * Vector3.Distance(transform.localPosition, averagePosition + offset * (maxDistance / 35f)) / 2f);
        lookPosition            = Vector3.MoveTowards(lookPosition, averagePosition, Time.deltaTime * Vector3.Distance(lookPosition, averagePosition));
        transform.rotation      = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(lookPosition - transform.position), Time.deltaTime * Quaternion.Angle(transform.rotation, Quaternion.LookRotation(lookPosition - transform.position)) * startingSlow);
    }
    public bool compareRot()
    {
        var angle = Quaternion.Angle(spawnRot, gameObject.transform.rotation);

        return(false);
    }
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }

        UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer);

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        if (cam == null || !cam.cachedCamera.isOrthoGraphic)
        {
            return;
        }
#else
        if (cam == null || !cam.cachedCamera.orthographic)
        {
            return;
        }
#endif

        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);
        Transform t    = mPanel.cachedTransform;

        Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);

        // Time to figure out what kind of action is underneath the mouse
        UIWidgetInspector.Action actionUnderMouse = mAction;

        Color handlesColor = new Color(0.5f, 0f, 0.5f);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        if (mPanel.isAnchored)
        {
            UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mPanel) && mPanel.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
            }
        }

        bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);

        // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
        if (canResize && mPanel.isAnchored)
        {
            Quaternion rot = mPanel.cachedTransform.localRotation;
            if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f)
            {
                canResize = false;
            }
        }

        bool[] resizable = new bool[8];

        resizable[4] = canResize;                    // left
        resizable[5] = canResize;                    // top
        resizable[6] = canResize;                    // right
        resizable[7] = canResize;                    // bottom

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], id, resizable[i]);
                    }

                    if (Mathf.Abs(v1.y - v0.y) > 80f)
                    {
                        if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], id, resizable[4]);
                        }

                        if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], id, resizable[6]);
                        }
                    }

                    if (Mathf.Abs(v3.x - v0.x) > 80f)
                    {
                        if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], id, resizable[5]);
                        }

                        if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], id, resizable[7]);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != UIWidgetInspector.Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
                         UIWidgetInspector.Raycast(handles, out mStartDrag))
                {
                    mWorldPos             = t.position;
                    mLocalPos             = t.localPosition;
                    mStartRot             = t.localRotation.eulerAngles;
                    mStartDir             = mStartDrag - t.position;
                    mStartCR              = mPanel.baseClipRegion;
                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == UIWidgetInspector.Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = UIWidgetInspector.Action.None;
                mAction           = UIWidgetInspector.Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
                {
                    Vector3 pos;

                    if (UIWidgetInspector.Raycast(handles, out pos))
                    {
                        if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == UIWidgetInspector.Action.Move)
                                {
                                    NGUISnap.Recalculate(mPanel);
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
                                {
                                    mStartCR   = mPanel.baseClipRegion;
                                    mDragPivot = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != UIWidgetInspector.Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mPanel);

                            if (mAction == UIWidgetInspector.Action.Move)
                            {
                                Vector3 before      = t.position;
                                Vector3 beforeLocal = t.localPosition;
                                t.position = mWorldPos + (pos - mStartDrag);
                                pos        = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
                                                           e.modifiers != EventModifiers.Control) - beforeLocal;
                                t.position = before;

                                NGUIMath.MoveRect(mPanel, pos.x, pos.y);
                            }
                            else if (mAction == UIWidgetInspector.Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == UIWidgetInspector.Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != UIWidgetInspector.Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = UIWidgetInspector.Action.None;
                    mAction           = UIWidgetInspector.Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Beispiel #27
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var minClosingDistance = WorldBounds.Bounds.height / 4;
        var screenTopY         = WorldBounds.Bounds.yMax;
        var query = GetEntityQuery(typeof(PlayerTag), typeof(Translation));
        var playerTranslations = query.ToComponentDataArray <Translation>(Allocator.TempJob);
        var playerPosition     = (Vector3)playerTranslations[0].Value;

        playerTranslations.Dispose();

        var playerComponents = query.ToComponentDataArray <PlayerTag>(Allocator.TempJob);
        var playerFlySpeed   = playerComponents[0].FlySpeed;

        playerComponents.Dispose();

        var jobHandle = Entities.ForEach((
                                             ref EnemyAIComponent ai,
                                             ref Translation translation,
                                             ref RotationTargetComponent rotationTarget,
                                             ref LocalToWorld localToWorld,
                                             ref WeaponsControlComponent weaponsControl) =>
        {
            var t             = translation.Value;
            t.y              -= playerFlySpeed;
            translation.Value = t;

            switch (ai.State)
            {
            case EnemyAIComponent.States.SimpleFly:
                if (translation.Value.y < screenTopY)
                {
                    ai.State = EnemyAIComponent.States.MovingIn;
                }
                break;

            case EnemyAIComponent.States.MovingIn:
                if (translation.Value.y > playerPosition.y + minClosingDistance)
                {
                    var direction = playerPosition - (Vector3)translation.Value;
                    rotationTarget.RotationTarget = Quaternion.LookRotation(direction, localToWorld.Up);
                }
                else
                {
                    var directionOut = (Vector3)translation.Value - playerPosition;
                    directionOut.y   = -Math.Abs(directionOut.y);
                    rotationTarget.RotationTarget = Quaternion.LookRotation(directionOut, localToWorld.Up);
                    ai.State = EnemyAIComponent.States.MovingOut;
                }
                break;

            case EnemyAIComponent.States.MovingOut:
                break;
            }

            weaponsControl.IsFiring = false;
            if (translation.Value.y < screenTopY)
            {
                var lookDirection = playerPosition - (Vector3)translation.Value;
                var angle         = Quaternion.Angle(Quaternion.LookRotation(lookDirection, localToWorld.Up), localToWorld.Rotation);
                if (Math.Abs(angle) < 25)
                {
                    //weaponsControl.IsFiring = true;
                }
            }
        })
                        .Schedule(inputDeps);

        return(jobHandle);
    }
 /// <summary>compares the angle between target and second to given float value</summary>
 public static bool AlmostEquals(this Quaternion target, Quaternion second, float maxAngle)
 {
     return(Quaternion.Angle(target, second) < maxAngle);
 }
Beispiel #29
0
        private void Update()
        {
            float deltaTime = useUnscaledTime
                ? Time.unscaledDeltaTime
                : Time.deltaTime;

            bool interpOccuredThisFrame = false;

            if (AnimatingPosition)
            {
                Vector3 lerpTargetPosition = targetPosition;
                if (SmoothLerpToTarget)
                {
                    lerpTargetPosition = Vector3.Lerp(transform.position, lerpTargetPosition, SmoothPositionLerpRatio);
                }

                Vector3 newPosition = NonLinearInterpolateTo(transform.position, lerpTargetPosition, deltaTime, positionPerSecond);
                if ((targetPosition - newPosition).sqrMagnitude <= Tolerance)
                {
                    // Snap to final position
                    newPosition       = targetPosition;
                    AnimatingPosition = false;
                }
                else
                {
                    interpOccuredThisFrame = true;
                }

                transform.position = newPosition;

                //calculate interpolatedVelocity and store position for next frame
                PositionVelocity = oldPosition - newPosition;
                oldPosition      = newPosition;
            }

            // Determine how far we need to rotate
            if (AnimatingRotation)
            {
                Quaternion lerpTargetRotation = targetRotation;
                if (SmoothLerpToTarget)
                {
                    lerpTargetRotation = Quaternion.Lerp(transform.rotation, lerpTargetRotation, SmoothRotationLerpRatio);
                }

                float angleDiff  = Quaternion.Angle(transform.rotation, lerpTargetRotation);
                float speedScale = 1.0f + (Mathf.Pow(angleDiff, rotationSpeedScaler) / 180.0f);
                float ratio      = Mathf.Clamp01((speedScale * rotationDegreesPerSecond * deltaTime) / angleDiff);

                if (angleDiff < Mathf.Epsilon)
                {
                    AnimatingRotation  = false;
                    transform.rotation = targetRotation;
                }
                else
                {
                    // Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
                    transform.rotation     = Quaternion.Slerp(transform.rotation, lerpTargetRotation, ratio);
                    interpOccuredThisFrame = true;
                }
            }

            // Determine how far we need to rotate
            if (AnimatingLocalRotation)
            {
                Quaternion lerpTargetLocalRotation = targetLocalRotation;
                if (SmoothLerpToTarget)
                {
                    lerpTargetLocalRotation = Quaternion.Lerp(transform.localRotation, lerpTargetLocalRotation, SmoothRotationLerpRatio);
                }

                float angleDiff  = Quaternion.Angle(transform.localRotation, lerpTargetLocalRotation);
                float speedScale = 1.0f + (Mathf.Pow(angleDiff, rotationSpeedScaler) / 180.0f);
                float ratio      = Mathf.Clamp01((speedScale * rotationDegreesPerSecond * deltaTime) / angleDiff);

                if (angleDiff < Mathf.Epsilon)
                {
                    AnimatingLocalRotation  = false;
                    transform.localRotation = targetLocalRotation;
                }
                else
                {
                    // Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
                    transform.localRotation = Quaternion.Slerp(transform.localRotation, lerpTargetLocalRotation, ratio);
                    interpOccuredThisFrame  = true;
                }
            }

            if (AnimatingLocalScale)
            {
                Vector3 lerpTargetLocalScale = targetLocalScale;
                if (SmoothLerpToTarget)
                {
                    lerpTargetLocalScale = Vector3.Lerp(transform.localScale, lerpTargetLocalScale, SmoothScaleLerpRatio);
                }

                Vector3 newScale = NonLinearInterpolateTo(transform.localScale, lerpTargetLocalScale, deltaTime, scalePerSecond);
                if ((targetLocalScale - newScale).sqrMagnitude <= Tolerance)
                {
                    // Snap to final scale
                    newScale            = targetLocalScale;
                    AnimatingLocalScale = false;
                }
                else
                {
                    interpOccuredThisFrame = true;
                }

                transform.localScale = newScale;
            }

            // If all interpolations have completed, stop updating
            if (!interpOccuredThisFrame)
            {
                InterpolationDone?.Invoke();
                enabled = false;
            }
        }
Beispiel #30
0
        public override void UpdateValue(SteamVR_Input_Sources inputSource, bool skipStateAndEventUpdates)
        {
            if (skipStateAndEventUpdates == false)
            {
                base.ResetLastStates(inputSource);
            }

            base.UpdateValue(inputSource, true);
            var poseChanged = base.changed[inputSource];

            var inputSourceInt = (int)inputSource;

            if (skipStateAndEventUpdates == false)
            {
                changed[inputSource] = false;

                for (var boneIndex = 0; boneIndex < numBones; boneIndex++)
                {
                    lastBonePositions[inputSourceInt][boneIndex] = bonePositions[inputSourceInt][boneIndex];
                    lastBoneRotations[inputSourceInt][boneIndex] = boneRotations[inputSourceInt][boneIndex];
                }
            }

            var err = OpenVR.Input.GetSkeletalActionData(handle, ref tempSkeletonActionData, skeletonActionData_size, SteamVR_Input_Source.GetHandle(inputSource));

            if (err != EVRInputError.None)
            {
                Debug.LogError("GetSkeletalActionData error (" + fullPath + "): " + err.ToString() + " handle: " + handle.ToString());
                active[inputSource] = false;
                return;
            }

            active[inputSource]       = active[inputSource] && tempSkeletonActionData.bActive; //anding from the pose active state
            activeOrigin[inputSource] = tempSkeletonActionData.activeOrigin;

            if (active[inputSource])
            {
                err = OpenVR.Input.GetSkeletalBoneData(handle, skeletalTransformSpace[inputSource], rangeOfMotion[inputSource], tempBoneTransforms, SteamVR_Input_Source.GetHandle(inputSource));
                if (err != EVRInputError.None)
                {
                    Debug.LogError("GetSkeletalBoneData error (" + fullPath + "): " + err.ToString() + " handle: " + handle.ToString());
                }

                for (var boneIndex = 0; boneIndex < tempBoneTransforms.Length; boneIndex++)
                {
                    // SteamVR's coordinate system is right handed, and Unity's is left handed.  The FBX data has its
                    // X axis flipped when Unity imports it, so here we need to flip the X axis as well
                    bonePositions[inputSourceInt][boneIndex].x = -tempBoneTransforms[boneIndex].position.v0;
                    bonePositions[inputSourceInt][boneIndex].y = tempBoneTransforms[boneIndex].position.v1;
                    bonePositions[inputSourceInt][boneIndex].z = tempBoneTransforms[boneIndex].position.v2;

                    boneRotations[inputSourceInt][boneIndex].x = tempBoneTransforms[boneIndex].orientation.x;
                    boneRotations[inputSourceInt][boneIndex].y = -tempBoneTransforms[boneIndex].orientation.y;
                    boneRotations[inputSourceInt][boneIndex].z = -tempBoneTransforms[boneIndex].orientation.z;
                    boneRotations[inputSourceInt][boneIndex].w = tempBoneTransforms[boneIndex].orientation.w;
                }

                // Now that we're in the same handedness as Unity, rotate the root bone around the Y axis
                // so that forward is facing down +Z
                var qFixUpRot = Quaternion.AngleAxis(Mathf.PI * Mathf.Rad2Deg, Vector3.up);

                boneRotations[inputSourceInt][0] = qFixUpRot * boneRotations[inputSourceInt][0];
            }

            changed[inputSource] = changed[inputSource] || poseChanged;

            if (skipStateAndEventUpdates == false)
            {
                for (var boneIndex = 0; boneIndex < tempBoneTransforms.Length; boneIndex++)
                {
                    if (Vector3.Distance(lastBonePositions[inputSourceInt][boneIndex], bonePositions[inputSourceInt][boneIndex]) > changeTolerance)
                    {
                        changed[inputSource] |= true;
                        break;
                    }

                    if (Mathf.Abs(Quaternion.Angle(lastBoneRotations[inputSourceInt][boneIndex], boneRotations[inputSourceInt][boneIndex])) > changeTolerance)
                    {
                        changed[inputSource] |= true;
                        break;
                    }
                }

                base.CheckAndSendEvents(inputSource);
            }

            if (changed[inputSource])
            {
                lastChanged[inputSource] = Time.time;
            }

            if (skipStateAndEventUpdates == false)
            {
                lastRecordedActive[inputSource]         = active[inputSource];
                lastRecordedPoseActionData[inputSource] = poseActionData[inputSource];
            }
        }