Example #1
0
        // Calculate where the enemy should move based on player position and nearby enemies
        private void CalculateMovement()
        {
            var selfPosition   = transform.position;
            var selfVector     = new Vector2(selfPosition.x, selfPosition.y);
            var playerPosition = _player.transform.position;
            var targetVector   = new Vector2(playerPosition.x, playerPosition.y) - selfVector;

            targetVector.Normalize();
            targetVector *= DefaultSpeed * Time.fixedDeltaTime;

            // Distance self from other enemies
            var enemies = GameObject.FindGameObjectsWithTag("Enemy");
            var force   = Vector2.zero;

            foreach (var enemy in enemies)
            {
                if (enemy == this.gameObject)
                {
                    continue;
                }

                var position    = enemy.transform.position;
                var enemyVector = new Vector2(position.x, position.y);
                var deltaVector = selfVector - enemyVector;

                if (deltaVector.magnitude > 10f)
                {
                    continue;
                }

                // Avoid 0 issues by adding random offset
                if (Math.Abs(deltaVector.magnitude) < 0.001)
                {
                    enemy.transform.position += new Vector3(
                        UnityEngine.Random.Range(1, 2) / 1000f,
                        UnityEngine.Random.Range(1, 2) / 1000f,
                        0);
                    deltaVector = selfVector - enemyVector;
                }
                force += 0.1f / (deltaVector.magnitude * deltaVector.magnitude) * deltaVector;
            }

            targetVector += force;

            var topSpeed = TopSpeed;
            var speed    = Math.Min(targetVector.magnitude, topSpeed);

            targetVector.Normalize();
            targetVector.Scale(new Vector2(speed, speed));

            if (float.IsNaN(targetVector.x) || float.IsNaN(targetVector.y))
            {
                return;
            }

            transform.position += new Vector3(targetVector.x, targetVector.y, 0);
        }
    void FixedUpdate()
    {
        float   moveHorz = Input.GetAxis("Horizontal");             //Gets "A" or "D" inputs
        float   moveVert = Input.GetAxis("Vertical");               //Gets "W" or "S" inputs
        Vector2 movement = new Vector2(moveHorz, moveVert);

        movement.Normalize();
        rb2d.AddForce(movement * speed);                            //Pushes the play object
        if (Input.GetMouseButtonDown(0))                            //Checks to see if mouse is being clicked and if it hasn't been thrown
        {
            if (currWeapon.Equals(boomerangPrefab) && !thrown)
            {
                throwBoomerang();
            }
            else if (currWeapon.Equals(swordPrefab) && !swung)
            {
                swordAttack();
            }
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            currWeapon = boomerangPrefab;
        }
        else if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            currWeapon = swordPrefab;
        }
    }
Example #3
0
        void FixedUpdate()
        {
            //if (PushOnce)
            //{
            //    Vector2 randomDir = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
            //    randomDir.Normalize();
            //    _rb2D.AddForce(randomDir * Time.fixedDeltaTime * 100.0f, ForceMode2D.Impulse);
            //    pushOnce = false;
            //}

            Vector2 normVel = _rb2D.velocity.normalized;
            if ((Mathf.Abs(normVel.x) != 1.0f && Mathf.Abs(normVel.y) != 1.0f))
            {
                if (normVel.magnitude == 0.0f && _initiallyHit)
                {
                    Vector2 newDir = new Vector2(14.5f - transform.position.x, 10.5f - transform.position.y);
                    newDir.Normalize();
                    _rb2D.AddForce(newDir * Time.fixedDeltaTime * 50.0f, ForceMode2D.Impulse);
                }
                _lastDirectionChangeTime = Time.time;
            }

            //cap the velocity magnitude
            _rb2D.velocity = Vector2.ClampMagnitude(_rb2D.velocity, MaxSpeed);
        }
Example #4
0
 public void CmdSpawnBullet(Vector3 finalSpawnPosition, Vector2 dir)
 {
     GameObject go = Instantiate(bulletPrefab, finalSpawnPosition, bulletPrefab.transform.rotation) as GameObject;
     var bul = go.GetComponent<Net>();
     dir.Normalize();
     bul.Initialize(dir, firePower);
     NetworkServer.Spawn(go);
 }
Example #5
0
 private void run()
 {
     if (checkDistance() <= _control.Settings.DistanceToRun)
     {
         _direction = _control.transform.position - _control.Settings.Monster.transform.position;
         _direction.Normalize();
     }
 }
Example #6
0
    public static Vector2 Truncate(Vector2 v, float magnitude)
    {
        if (v.sqrMagnitude > magnitude * magnitude)
        {
            v.Normalize();
            v *= magnitude;
        }

        return(v);
    }
        private void SetTrajectory(Vector2 startPosition, Vector3 targetPosition)
        {
            _transform.position = new Vector3(startPosition.x, startPosition.y + Gate_To_Player_Vertical_Offset, _transform.position.z);
            _targetPosition = new Vector3(targetPosition.x, targetPosition.y + Gate_To_Player_Vertical_Offset);

            Vector2 trajectory = new Vector2(targetPosition.x - startPosition.x, targetPosition.y - startPosition.y);
            trajectory.Normalize();

            _rigidBody2D.velocity = trajectory * Movement_Speed;
        }
Example #8
0
    private void UpdateMovementOnKeyboardInput()
    {
        Vector2 movementInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        movementInput.Normalize();

        Vector3 velocity = (transform.forward * movementInput.y + transform.right * movementInput.x) * _movementSpeed;

        _characterController.Move(velocity * Time.deltaTime);
    }
 // Start is called before the first frame update
 void Start()
 {
     state = MovementState.IDLE;
     rb    = GetComponent <Rigidbody2D>();
     //anim = GetComponent<Animator>();
     sprite = GetComponent <SpriteRenderer>();
     wallJumpDirection.Normalize();
     gravityScale       = rb.gravityScale;
     dashChargeHoldMax += dashChargeTimeMax;
 }
Example #10
0
 void AttackOnPlayer()
 {
     if (Time.time >= nextShoot) {
         nextShoot = Time.time + fireRate;
         GameObject go = Instantiate (EnemyBullet, transform.position, transform.rotation) as GameObject;
         //go.transform.SetParent(gameObject.transform);
         Vector2 toTarget = new Vector2 (target.position.x - transform.position.x, target.position.y - transform.position.y);
         toTarget.Normalize ();
         go.GetComponent<Rigidbody2D> ().AddForce (toTarget * 20000, ForceMode2D.Force);
     }
 }
Example #11
0
        /** Reads public properties and stores them in internal fields.
         * This is required because multithreading is used and if another script
         * updated the fields at the same time as this class used them in another thread
         * weird things could happen.
         *
         * Will also set CalculatedTargetPoint and CalculatedSpeed to the result
         * which was last calculated.
         */
        public void BufferSwitch()
        {
            // <== Read public properties
            radius              = Radius;
            height              = Height;
            maxSpeed            = nextMaxSpeed;
            desiredSpeed        = nextDesiredSpeed;
            agentTimeHorizon    = AgentTimeHorizon;
            obstacleTimeHorizon = ObstacleTimeHorizon;
            maxNeighbours       = MaxNeighbours;
            // Manually controlled overrides the agent being locked
            // (if one for some reason uses them at the same time)
            locked              = Locked && !manuallyControlled;
            position            = Position;
            elevationCoordinate = ElevationCoordinate;
            collidesWith        = CollidesWith;
            layer = Layer;

            if (locked)
            {
                // Locked agents do not move at all
                desiredTargetPointInVelocitySpace = position;
                desiredVelocity = currentVelocity = Vector2.zero;
            }
            else
            {
                desiredTargetPointInVelocitySpace = nextTargetPoint - position;

                // Estimate our current velocity
                // This is necessary because other agents need to know
                // how this agent is moving to be able to avoid it
                currentVelocity = (CalculatedTargetPoint - position).normalized * CalculatedSpeed;

                // Calculate the desired velocity from the point we want to reach
                desiredVelocity = desiredTargetPointInVelocitySpace.normalized * desiredSpeed;

                if (collisionNormal != Vector2.zero)
                {
                    collisionNormal.Normalize();
                    var dot = Vector2.Dot(currentVelocity, collisionNormal);

                    // Check if the velocity is going into the wall
                    if (dot < 0)
                    {
                        // If so: remove that component from the velocity
                        currentVelocity -= collisionNormal * dot;
                    }

                    // Clear the normal
                    collisionNormal = Vector2.zero;
                }
            }
        }
Example #12
0
    static bool Vector2_Normalize(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 0)
        {
            UnityEngine.Vector2 argThis = (UnityEngine.Vector2)vc.csObj;        argThis.Normalize();
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Example #13
0
 static public int Normalize(IntPtr l)
 {
     try{
         UnityEngine.Vector2 self = (UnityEngine.Vector2)checkSelf(l);
         self.Normalize();
         setBack(l, self);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Example #14
0
 static int Normalize(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         UnityEngine.Vector2 obj = (UnityEngine.Vector2)ToLua.CheckObject(L, 1, typeof(UnityEngine.Vector2));
         obj.Normalize();
         ToLua.SetBack(L, 1, obj);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Example #15
0
    /// <summary>
    /// Finds the direction to get from currentVector to nextVector.
    /// </summary>
    /// <param name="currentVector">The current position.</param>
    /// <param name="nextVector">The position to get to.</param>
    /// <param name="normalized">Whether or not the return result should be normalized.</param>
    /// <returns>The normalized vector2 pointing where to go to get to nextVector from currentVector, or "Vector2.zero" if the two points are equal..</returns>
    static public Vector2 FindDirection(Vector2 currentVector, Vector2 nextVector)
    {
        if (currentVector == nextVector)
        {
            return(Vector2.zero);
        }

        Vector2 returnVector = nextVector - currentVector;

        if (true && returnVector != Vector2.zero)
        {
            returnVector.Normalize();
        }
        return(returnVector);
    }
        public void PlayerMovesAtNormalizedSpeedWhenMovingDiagonal()
        {
            //Arrange
            inputHelper.mockAxisRaw = new Vector2 (1, 1);
            //Act
            testHelper.Update(testObject);

            //Assert
            Vector2 expectedResult = new Vector2 (1, 1);
            expectedResult.Normalize ();
            expectedResult = expectedResult * testObject.movementSpeed;

            var rb = testObject.GetComponent<Rigidbody2D> ();
            Assert.AreEqual (expectedResult, rb.velocity);
        }
        public void PlayerMovesAtNormalizedSpeedWhenMovingDiagonal()
        {
            //Arrange
            inputHelper.mockAxisRaw = new Vector2 (1, 1);
            inputHelper.customDeltaTime = 1.0f;
            //Act
            testHelper.Update(testObject);

            //Assert
            Vector2 expectedResult = new Vector2 (1, 1);
            expectedResult.Normalize ();
            expectedResult = expectedResult * testObject.movementSpeed;

            Assert.AreEqual (new Vector3(expectedResult.x, expectedResult.y, 0), testObject.transform.position);
        }
Example #18
0
    public void CastSkill()
    {
        castingSkill = true;
        //cast skill with target is player
        Vector3 difference = player.position - base.transform.position;
        float   distance   = difference.magnitude;
        Vector2 direction  = difference / distance;

        direction.Normalize();
        GameObject skill = Instantiate(skillPrefab) as GameObject;

        skill.transform.position = skillStart.transform.position;
        skill.GetComponent <Rigidbody2D>().velocity = direction * skillSpeed;

        canCastSkill = false;
    }
Example #19
0
    private void Move(float horizontalSpeed, float verticalSpeed)
    {
        _horizontalSpeed = horizontalSpeed;
        _verticalSpeed   = verticalSpeed;

        var move = new Vector2(_horizontalSpeed, _verticalSpeed);

        if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
        {
            _lookDirection.Set(move.x, move.y);
            _lookDirection.Normalize();
        }

        _animator.SetFloat(AnimationPropertyLookX, _lookDirection.x);
        _animator.SetFloat(AnimationPropertyLookY, _lookDirection.y);
        _animator.SetFloat(AnimationPropertySpeed, move.magnitude);
    }
Example #20
0
    public static Vector2 Clamp(Vector2 v, float minValue, float maxValue)
    {
        if (v.sqrMagnitude > maxValue * maxValue)
        {
            v.Normalize();
            v *= maxValue;
            return(v);
        }

        if (v.sqrMagnitude < minValue * minValue)
        {
            v.Normalize();
            v *= minValue;
            return(v);
        }

        return(v);
    }
Example #21
0
        public float getAngleOfVector(Vector2 vector)
        {
            Vector2 newVector = new Vector2(vector.x, -vector.y);
            newVector.Normalize();

            float angle = (float)Math.Acos(newVector.y);
            if (newVector.x < 0.0f)
            {
                angle = -angle;
                angle += Angles.DEG_360;
            }

            if (float.IsNaN(angle))
            {
                return 0.0f;
            }

            return angle;
        }
        public void OnCollisionStay2D()
        {
            var enemyPosition = new Vector3 (10, 10, 0);
            collider2D.transform.position = enemyPosition;
            var damageToDeal = 20.0f;
            testObject.damageToDeal = damageToDeal;
            var yourPosition = new Vector3(9, 9, 0);
            testObject.transform.position = yourPosition;

            //Act
            testHelper.OnCollisionStay2D (testObject, collider2D);

            //Assert
            var expectedKnockbackDir = (enemyPosition - yourPosition);
            var expectedKnockbackDir2D = new Vector2 (expectedKnockbackDir.x, expectedKnockbackDir.y);
            expectedKnockbackDir2D.Normalize ();
            Assert.AreEqual (expectedKnockbackDir2D, playerMovement.KnockedBackDirection);
            Assert.AreEqual (damageToDeal, playerStatus.DamageDelt);
        }
Example #23
0
    /// <summary>
    /// tests if ray intersects AABB
    /// </summary>
    /// <param name="aabb"></param>
    /// <returns></returns>
    public static bool RayCastAABB(AABB aabb, Vector2 p1, Vector2 p2)
    {
        AABB segmentAABB = new AABB();

        {
            VectorMath.Min(ref p1, ref p2, out segmentAABB.LowerBound);
            VectorMath.Max(ref p1, ref p2, out segmentAABB.UpperBound);
        }
        if (!AABB.TestOverlap(aabb, segmentAABB))
        {
            return(false);
        }

        Vector2 rayDir = p2 - p1;
        Vector2 rayPos = p1;

        Vector2 norm = new Vector2(-rayDir.y, rayDir.x); //normal to ray

        if (norm.magnitude == 0.0)
        {
            return(true); //if ray is just a point, return true (iff point is within aabb, as tested earlier)
        }
        norm.Normalize();

        float dPos = Vector2.Dot(rayPos, norm);

        Vector2[] verts = aabb.GetVertices();
        float     d0    = Vector2.Dot(verts[0], norm) - dPos;

        for (int i = 1; i < 4; i++)
        {
            float d = Vector2.Dot(verts[i], norm) - dPos;
            if (Math.Sign(d) != Math.Sign(d0))
            {
                //return true if the ray splits the vertices (ie: sign of dot products with normal are not all same)
                return(true);
            }
        }

        return(false);
    }
Example #24
0
        public bool MovingInSameDirection(float tolerance)
        {
            if (Count < 2)
            {
                return(true);
            }
            float minDOT = UnityEngine.Mathf.Max(0.1f, 1.0f - tolerance);

            UnityEngine.Vector2 refDir = this[0].Position - this[0].StartPosition;
            refDir.Normalize();
            for (int i = 1; i < Count; ++i)
            {
                UnityEngine.Vector2 dir = this[i].Position - this[i].StartPosition;
                dir.Normalize();
                if (UnityEngine.Vector2.Dot(refDir, dir) < minDOT)
                {
                    return(false);
                }
            }
            return(true);
        }
        public Vector2 TransformToPosition(Vector2 position)
        {
            position.x = Mathf.Clamp(position.x, _paddedZone.xMin, _paddedZone.xMax) - _paddedZone.xMin - (_paddedZone.width / 2.0f);
            position.y = Mathf.Clamp(position.y, _paddedZone.yMin, _paddedZone.yMax) - _paddedZone.yMin - (_paddedZone.height / 2.0f);

            position.x = (2.0f * position.x) / _paddedZone.width;
            position.y = (2.0f * position.y) / _paddedZone.height;

            if (normalize && position.magnitude > 1.0f)
                position.Normalize();

            if (useMotionCurve) {
                position.x *= motionCurve.Evaluate(Mathf.Abs(position.x));
                position.y *= motionCurve.Evaluate(Mathf.Abs(position.y));
            }

            if (Mathf.Abs(position.x) < 0.01f)
                position.x = 0.0f;
            if (Mathf.Abs(position.y) < 0.01f)
                position.y = 0.0f;

            return position;
        }
Example #26
0
        public override Vector2 Compute()
        {
            //The jitter is time dependent
            float jitter = wanderJitter * Time.deltaTime;
            wanderTarget += Random.insideUnitCircle * jitter;
            wanderTarget.Normalize();
            wanderTarget *= wanderRadius;
            Vector3 localTarget = wanderTarget + new Vector2(0.0f, wanderDistance);

            //Gets the world position of the target
            trick.transform.localPosition = localTarget;
            Vector3 worldTarget = trick.transform.position;

            //Trying to build a transformation matrix from local to world
            //Matrix4x4 transform = Matrix4x4.TRS(
            //    agent.transform.position,
            //    Quaternion.LookRotation(agent.transform.up, agent.transform.right),
            //    Vector3.one);
            //target = transform.MultiplyVector(target);

            Debug.DrawLine(Vector2.zero, worldTarget);

            return worldTarget - agent.transform.position;
        }
Example #27
0
        void Start()
        {
            waterTiles.Clear ();
            Nplus1 = N+1;

            waterTilesMax = (m_numGridsX * m_numGridsZ);

            m_fourier = new FourierCPU(N);

            m_windDirection = new Vector2(m_windSpeed.x, m_windSpeed.y);
            m_windDirection.Normalize();

            m_dispersionTable = new float[Nplus1*Nplus1];

            for (int m_prime = 0; m_prime < Nplus1; m_prime++)
            {
                for (int n_prime = 0; n_prime < Nplus1; n_prime++)
                {
                    int index = m_prime * Nplus1 + n_prime;
                    m_dispersionTable[index] = Dispersion(n_prime,m_prime);
                }
            }

            m_heightBuffer = new Vector2[2,N*N];
            m_slopeBuffer = new Vector4[2,N*N];
            m_displacementBuffer = new Vector4[2,N*N];

            m_spectrum = new Vector2[Nplus1*Nplus1];
            m_spectrum_conj = new Vector2[Nplus1*Nplus1];

            m_position = new Vector3[Nplus1*Nplus1];
            m_vertices = new Vector3[Nplus1*Nplus1];
            m_normals = new Vector3[Nplus1*Nplus1];

            m_mesh = MakeMesh(Nplus1);
            //m_mesh.Optimize();

            m_oceanGrid = new GameObject[m_numGridsX*m_numGridsZ];

            if (waterTiles.Count < (m_numGridsX * m_numGridsZ)) {
                for (int x = 0; x < m_numGridsX; x++) {
                    for (int z = 0; z < m_numGridsZ; z++) {
                        int idx = x + z * m_numGridsX;

                        m_oceanGrid [idx] = new GameObject ("Ocean grid " + idx.ToString ());
                        m_oceanGrid [idx].AddComponent<MeshFilter> ();
                        m_oceanGrid [idx].AddComponent<MeshRenderer> ();
                        m_oceanGrid [idx].GetComponent<Renderer> ().material = m_mat;
                        m_oceanGrid [idx].GetComponent<MeshFilter> ().mesh = m_mesh;
                        m_oceanGrid [idx].transform.Translate (new Vector3 (x * m_length - m_numGridsX * m_length / 2, 0.0f, z * m_length - m_numGridsZ * m_length / 2));
                        m_oceanGrid [idx].transform.parent = this.transform;
                        waterTiles.Add (m_oceanGrid [idx]);
                        m_oceanGrid [idx].transform.position = new Vector3 (m_oceanGrid [idx].transform.position.x + m_oceanGrid [idx].transform.parent.position.x, m_oceanGrid [idx].transform.position.y + m_oceanGrid [idx].transform.parent.position.y, m_oceanGrid [idx].transform.position.z + m_oceanGrid [idx].transform.parent.position.z);
                        m_oceanGrid [idx].AddComponent<MeshCollider>();
                    }
                }
            }

            UnityEngine.Random.seed = 0;

            Vector3[] vertices = m_mesh.vertices;

            for (int m_prime = 0; m_prime < Nplus1; m_prime++)
            {
                for (int n_prime = 0; n_prime < Nplus1; n_prime++)
                {
                    int index = m_prime * Nplus1 + n_prime;

                    m_spectrum[index] = GetSpectrum( n_prime,  m_prime);

                    m_spectrum_conj[index] = GetSpectrum(-n_prime, -m_prime);
                    m_spectrum_conj[index].y *= -1.0f;

                    m_position[index].x = vertices[index].x =  n_prime * m_length/N;
                    m_position[index].y = vertices[index].y =  0.0f;
                    m_position[index].z = vertices[index].z =  m_prime * m_length/N;

                }
            }

            m_mesh.vertices = vertices;
            m_mesh.RecalculateBounds();

            CreateFresnelLookUp();
        }
Example #28
0
        /// <summary>
        /// Gets the spectrum vaule for grid position n,m.
        /// </summary>
        float PhillipsSpectrum(int n_prime, int m_prime)
        {
            Vector2 k = new Vector2(Mathf.PI * (2 * n_prime - N) / m_length, Mathf.PI * (2 * m_prime - N) / m_length);
            float k_length  = k.magnitude;
            if (k_length < 0.000001f) return 0.0f;

            float k_length2 = k_length  * k_length;
            float k_length4 = k_length2 * k_length2;

            k.Normalize();

            float k_dot_w   = Vector2.Dot(k, m_windDirection);
            float k_dot_w2  = k_dot_w * k_dot_w * k_dot_w * k_dot_w * k_dot_w * k_dot_w;

            float w_length  = m_windSpeed.magnitude;
            float L         = w_length * w_length / GRAVITY;
            float L2        = L * L;

            float damping   = 0.001f;
            float l2        = L2 * damping * damping;

            return m_waveAmp * Mathf.Exp(-1.0f / (k_length2 * L2)) / k_length4 * k_dot_w2 * Mathf.Exp(-k_length2 * l2);
        }
Example #29
0
        public virtual void OnDrag(PointerEventData eventData)
        {
            // Unity remote multitouch related thing
            // When we feed fake PointerEventData we can't really provide a camera, 
            // it has a lot of private setters via not created objects, so even the Reflection magic won't help a lot here
            // Instead, we just provide an actual event camera as a public property so we can easily set it in the Input Helper class
            CurrentEventCamera = eventData.pressEventCamera ?? CurrentEventCamera;

            // We get the local position of the joystick
            Vector3 worldJoystickPosition;
            RectTransformUtility.ScreenPointToWorldPointInRectangle(_stickTransform, eventData.position,
                CurrentEventCamera, out worldJoystickPosition);

            // Then we change it's actual position so it snaps to the user's finger
            _stickTransform.position = worldJoystickPosition;
            // We then query it's anchored position. It's calculated internally and quite tricky to do from scratch here in C#
            var stickAnchoredPosition = _stickTransform.anchoredPosition;

            // Some bitwise logic for constraining the joystick along one of the axis
            // If the "Both" option was selected, non of these two checks will yield "true"
            if ((JoystickMoveAxis & ControlMovementDirection.Horizontal) == 0)
            {
                stickAnchoredPosition.x = _intermediateStickPosition.x;
            }
            if ((JoystickMoveAxis & ControlMovementDirection.Vertical) == 0)
            {
                stickAnchoredPosition.y = _intermediateStickPosition.y;
            }

            _stickTransform.anchoredPosition = stickAnchoredPosition;

            // Find current difference between the previous central point of the joystick and it's current position
            Vector2 difference = new Vector2(stickAnchoredPosition.x, stickAnchoredPosition.y) - _intermediateStickPosition;

            // Normalisation stuff
            var diffMagnitude = difference.magnitude;
            var normalizedDifference = difference / diffMagnitude;

            // If the joystick is being dragged outside of it's range
            if (diffMagnitude > MovementRange)
            {
                if (MoveBase && SnapsToFinger)
                {
                    // We move the base so it maps the new joystick center position
                    var baseMovementDifference = difference.magnitude - MovementRange;
                    var addition = normalizedDifference * baseMovementDifference;
                    _baseTransform.anchoredPosition += addition;
                    _intermediateStickPosition += addition;
                }
                else
                {
                    _stickTransform.anchoredPosition = _intermediateStickPosition + normalizedDifference * MovementRange;
                }
            }

            // 这种做法会导致数值丢失,当x、y都大于1时无法区分大小。弃用!
            // We don't need any values that are greater than 1 or less than -1
            //var horizontalValue = Mathf.Clamp(difference.x * _oneOverMovementRange, -1f, 1f);
            //var verticalValue = Mathf.Clamp(difference.y * _oneOverMovementRange, -1f, 1f);

            // 将最终向量标准化,保留了xy和差异和方向性
            var axis = new Vector2(difference.x * _oneOverMovementRange, difference.y * _oneOverMovementRange);
            axis.Normalize();

            // Finally, we update our virtual axis
            HorizintalAxis.Value = axis.x;
            VerticalAxis.Value = axis.y;
        }
        private void WriteHull()
        {
            // Perpendicular vector
            float[] lengths = { (p1 - p0).magnitude, (p2 - p1).magnitude, (p3 - p2).magnitude };
            float sum = lengths.Sum();

            Vector2 norm = new Vector2(length, (bottomDiameter - topDiameter) / 2f);
            norm.Normalize();

            WriteMeshes(
                new ProfilePoint(p0.x, p0.y, 0f, Vector2.right),
                new ProfilePoint(p1.x, p1.y, lengths[0] / sum, Vector2.right),
                new ProfilePoint(p2.x, p2.y, (lengths[0] + lengths[1]) / sum, Vector2.right),
                new ProfilePoint(p3.x, p3.y, 1f, Vector2.right)
                );
        }
        public static Vector2 SetLengthOnAxis(this Vector2 v, Vector2 axis, float len)
        {
            //var n = new Vector2(-axis.y, axis.x);
            //n.Normalize();

            //var d = Vector2.Dot(v, n);
            //v -= n * d;
            //v = v.normalized * len;
            //v += n * d;
            //return v;

            axis.Normalize();
            var d = len - Vector2.Dot(v, axis);
            return v + axis * d;
        }
        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");

            bool waswalking = m_IsWalking;

            #if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            m_IsWalking = !CrossPlatformInputManager.GetButton("Course");
            //Si le joueur marche. Il reprend de l'énergie
            if(m_IsWalking && !Input.GetButton("StopRespire"))
            {
                m_Stamina += 5;
                if(m_Stamina >= 500)
                    canSprint=true;
                if(m_Stamina >= 1000)
                    m_Stamina = 1000;
            }
            //Sinon il court, mais il perd de l'énergie
            else if(!m_IsWalking || Input.GetButton("StopRespire"))
            {
                m_Stamina -= 10;
                if(m_Stamina < 0)
                {
                    canSprint=false;
                    m_Stamina=0;
                }
            }
            //Si il n'a pas d'energie il doit marcher
            if(!canSprint)
                m_IsWalking=true;
            #endif
            // set the desired speed to be walking or running
            speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
            }
        }
		public bool RenderHUD(RenderTexture screen, float cameraAspect)
		{
			if (screen == null || !startupComplete || HighLogic.LoadedSceneIsEditor)
				return false;

			// Clear the background, if configured.
			GL.Clear(true, true, backgroundColorValue);

			// Configure the camera, if configured.
			// MOARdV: Might be worthwhile to refactor the flying camera so
			// it is created in Start (like new FlyingCamera(part, cameraTransform)),
			// and pass the screen, FoV, and aspect ratio (or just screen and
			// FoV) as Render parameters, so there's no need to test if the
			// camera's been created every render call.
			if (cameraObject == null && !string.IsNullOrEmpty(cameraTransform)) {
				cameraObject = new FlyingCamera(part, screen, cameraAspect);
				cameraObject.PointCamera(cameraTransform, hudFov);
			}

			// Draw the camera's view, if configured.
			if (cameraObject != null) {
				cameraObject.Render();
			}

			// Configure the matrix so that the origin is the center of the screen.
			GL.PushMatrix();

			// Draw the HUD ladder
			// MOARdV note, 2014/03/19: swapping the y values, to invert the
			// coordinates so the prograde icon is right-side up.
			GL.LoadPixelMatrix(-horizonSize.x * 0.5f, horizonSize.x * 0.5f, horizonSize.y * 0.5f, -horizonSize.y * 0.5f);
			GL.Viewport(new Rect((screen.width - horizonSize.x) * 0.5f, (screen.height - horizonSize.y) * 0.5f, horizonSize.x, horizonSize.y));

			Vector3 coM = vessel.findWorldCenterOfMass();
			Vector3 up = (coM - vessel.mainBody.position).normalized;
			Vector3 forward = vessel.GetTransform().up;
			Vector3 right = vessel.GetTransform().right;
			Vector3 top = Vector3.Cross(right, forward);
			Vector3 north = Vector3.Exclude(up, (vessel.mainBody.position + (Vector3d)vessel.mainBody.transform.up * vessel.mainBody.Radius) - coM).normalized;

			Vector3d velocityVesselSurface = vessel.orbit.GetVel() - vessel.mainBody.getRFrmVel(coM);
			Vector3 velocityVesselSurfaceUnit = velocityVesselSurface.normalized;

			if (ladderMaterial) {
				// Figure out the texture coordinate scaling for the ladder.
				float ladderTextureOffset = horizonTextureSize.y / ladderMaterial.mainTexture.height;

				float cosUp = Vector3.Dot(forward, up);
				float cosRoll = Vector3.Dot(top, up);
				float sinRoll = Vector3.Dot(right, up);

				var normalizedRoll = new Vector2(cosRoll, sinRoll);
				normalizedRoll.Normalize();
				if (normalizedRoll.magnitude < 0.99f) {
					// If we're hitting +/- 90 nearly perfectly, the sin and cos will
					// be too far out of whack to normalize.  Arbitrarily pick
					// a roll of 0.0.
					normalizedRoll.x = 1.0f;
					normalizedRoll.y = 0.0f;
				}
				cosRoll = normalizedRoll.x;
				sinRoll = normalizedRoll.y;

				// Mihara: I'm pretty sure this was negative of what it should actually be, at least according to my mockup.
				float pitch = -(Mathf.Asin(cosUp) * Mathf.Rad2Deg);

				float ladderMidpointCoord;
				if (use360horizon) {
					// Straight up is texture coord 0.75;
					// Straight down is TC 0.25;
					ladderMidpointCoord = JUtil.DualLerp(0.25f, 0.75f, -90f, 90f, pitch);
				} else {
					// Straight up is texture coord 1.0;
					// Straight down is TC 0.0;
					ladderMidpointCoord = JUtil.DualLerp(0.0f, 1.0f, -90f, 90f, pitch);
				}

				ladderMaterial.SetPass(0);
				GL.Begin(GL.QUADS);

				// transform -x -y
				GL.TexCoord2(0.5f + horizonTextureSize.x, ladderMidpointCoord - ladderTextureOffset);
				GL.Vertex3(cosRoll * horizonSize.x + sinRoll * horizonSize.y, -sinRoll * horizonSize.x + cosRoll * horizonSize.y, 0.0f);

				// transform +x -y
				GL.TexCoord2(0.5f - horizonTextureSize.x, ladderMidpointCoord - ladderTextureOffset);
				GL.Vertex3(-cosRoll * horizonSize.x + sinRoll * horizonSize.y, sinRoll * horizonSize.x + cosRoll * horizonSize.y, 0.0f);

				// transform +x +y
				GL.TexCoord2(0.5f - horizonTextureSize.x, ladderMidpointCoord + ladderTextureOffset);
				GL.Vertex3(-cosRoll * horizonSize.x - sinRoll * horizonSize.y, sinRoll * horizonSize.x - cosRoll * horizonSize.y, 0.0f);

				// transform -x +y
				GL.TexCoord2(0.5f + horizonTextureSize.x, ladderMidpointCoord + ladderTextureOffset);
				GL.Vertex3(cosRoll * horizonSize.x - sinRoll * horizonSize.y, -sinRoll * horizonSize.x - cosRoll * horizonSize.y, 0.0f);
				GL.End();

				float AoA = velocityVesselSurfaceUnit.AngleInPlane(right, forward);
				float AoATC;
				if (use360horizon) {
					// Straight up is texture coord 0.75;
					// Straight down is TC 0.25;
					AoATC = JUtil.DualLerp(0.25f, 0.75f, -90f, 90f, pitch + AoA);
				} else {
					// Straight up is texture coord 1.0;
					// Straight down is TC 0.0;
					AoATC = JUtil.DualLerp(0.0f, 1.0f, -90f, 90f, pitch + AoA);
				}

				float Ypos = JUtil.DualLerp(
					             -horizonSize.y, horizonSize.y,
					             ladderMidpointCoord - ladderTextureOffset, ladderMidpointCoord + ladderTextureOffset, 
					             AoATC);

				// Placing the icon on the (0, Ypos) location, so simplify the transform.
				DrawIcon(-sinRoll * Ypos, -cosRoll * Ypos, GizmoIcons.GetIconLocation(GizmoIcons.IconType.PROGRADE), progradeColorValue);
			}

			// Draw the rest of the HUD stuff (0,0) is the top left corner of the screen.
			GL.LoadPixelMatrix(0, screen.width, screen.height, 0);
			GL.Viewport(new Rect(0, 0, screen.width, screen.height));

			if (headingMaterial != null) {
				Quaternion rotationSurface = Quaternion.LookRotation(north, up);
				Quaternion rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);
				float headingTexture = JUtil.DualLerp(0f, 1f, 0f, 360f, rotationVesselSurface.eulerAngles.y);
				float headingTextureOffset = (headingBarWidth / headingMaterial.mainTexture.width) / 2;

				headingMaterial.SetPass(0);
				GL.Begin(GL.QUADS);
				GL.TexCoord2(headingTexture - headingTextureOffset, 1.0f);
				GL.Vertex3(headingBarPosition.x, headingBarPosition.y, 0.0f);
				GL.TexCoord2(headingTexture + headingTextureOffset, 1.0f);
				GL.Vertex3(headingBarPosition.x + headingBarPosition.z, headingBarPosition.y, 0.0f);
				GL.TexCoord2(headingTexture + headingTextureOffset, 0.0f);
				GL.Vertex3(headingBarPosition.x + headingBarPosition.z, headingBarPosition.y + headingBarPosition.w, 0.0f);
				GL.TexCoord2(headingTexture - headingTextureOffset, 0.0f);
				GL.Vertex3(headingBarPosition.x, headingBarPosition.y + headingBarPosition.w, 0.0f);
				GL.End();

				if (showHeadingBarPrograde) {
					float slipAngle = velocityVesselSurfaceUnit.AngleInPlane(up, forward);
					float slipTC = JUtil.DualLerp(0f, 1f, 0f, 360f, rotationVesselSurface.eulerAngles.y + slipAngle);
					float slipIconX = JUtil.DualLerp(headingBarPosition.x, headingBarPosition.x + headingBarPosition.z, headingTexture - headingTextureOffset, headingTexture + headingTextureOffset, slipTC);
					DrawIcon(slipIconX, headingBarPosition.y + headingBarPosition.w * 0.5f, GizmoIcons.GetIconLocation(GizmoIcons.IconType.PROGRADE), progradeColorValue);
				}
			}

			if (vertBar1Material != null) {
				float value = comp.ProcessVariable(vertBar1Variable).MassageToFloat();
				if (float.IsNaN(value)) {
					value = 0.0f;
				}

				if (vertBar1UseLog10) {
					value = JUtil.PseudoLog10(value);
				}

				float vertBar1TexCoord = JUtil.DualLerp(vertBar1TextureLimit.x, vertBar1TextureLimit.y, vertBar1Limit.x, vertBar1Limit.y, value);

				vertBar1Material.SetPass(0);
				GL.Begin(GL.QUADS);
				GL.TexCoord2(0.0f, vertBar1TexCoord + vertBar1TextureSize);
				GL.Vertex3(vertBar1Position.x, vertBar1Position.y, 0.0f);
				GL.TexCoord2(1.0f, vertBar1TexCoord + vertBar1TextureSize);
				GL.Vertex3(vertBar1Position.x + vertBar1Position.z, vertBar1Position.y, 0.0f);
				GL.TexCoord2(1.0f, vertBar1TexCoord - vertBar1TextureSize);
				GL.Vertex3(vertBar1Position.x + vertBar1Position.z, vertBar1Position.y + vertBar1Position.w, 0.0f);
				GL.TexCoord2(0.0f, vertBar1TexCoord - vertBar1TextureSize);
				GL.Vertex3(vertBar1Position.x, vertBar1Position.y + vertBar1Position.w, 0.0f);
				GL.End();
			}

			if (vertBar2Material != null) {
				float value = comp.ProcessVariable(vertBar2Variable).MassageToFloat();
				if (float.IsNaN(value)) {
					value = 0.0f;
				}

				if (vertBar2UseLog10) {
					value = JUtil.PseudoLog10(value);
				}

				float vertBar2TexCoord = JUtil.DualLerp(vertBar2TextureLimit.x, vertBar2TextureLimit.y, vertBar2Limit.x, vertBar2Limit.y, value);

				vertBar2Material.SetPass(0);
				GL.Begin(GL.QUADS);
				GL.TexCoord2(0.0f, vertBar2TexCoord + vertBar2TextureSize);
				GL.Vertex3(vertBar2Position.x, vertBar2Position.y, 0.0f);
				GL.TexCoord2(1.0f, vertBar2TexCoord + vertBar2TextureSize);
				GL.Vertex3(vertBar2Position.x + vertBar2Position.z, vertBar2Position.y, 0.0f);
				GL.TexCoord2(1.0f, vertBar2TexCoord - vertBar2TextureSize);
				GL.Vertex3(vertBar2Position.x + vertBar2Position.z, vertBar2Position.y + vertBar2Position.w, 0.0f);
				GL.TexCoord2(0.0f, vertBar2TexCoord - vertBar2TextureSize);
				GL.Vertex3(vertBar2Position.x, vertBar2Position.y + vertBar2Position.w, 0.0f);
				GL.End();
			}

			if (overlayMaterial != null) {
				overlayMaterial.SetPass(0);
				GL.Begin(GL.QUADS);
				GL.TexCoord2(0.0f, 1.0f);
				GL.Vertex3(0.0f, 0.0f, 0.0f);
				GL.TexCoord2(1.0f, 1.0f);
				GL.Vertex3(screen.width, 0.0f, 0.0f);
				GL.TexCoord2(1.0f, 0.0f);
				GL.Vertex3(screen.width, screen.height, 0.0f);
				GL.TexCoord2(0.0f, 0.0f);
				GL.Vertex3(0.0f, screen.height, 0.0f);
				GL.End();
			}

			GL.PopMatrix();

			return true;
		}
        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");

            bool waswalking = m_IsWalking;

            #if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
            #endif
            // set the desired speed to be walking or running
            speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
            }
            if (Input.GetMouseButtonDown (0)) {
                gun.GetComponent<Animation> ().Play ("Shooting animation");
                RaycastHit hit;
                Ray ray = new Ray (transform.position, m_Camera.transform.forward);
                if (Physics.Raycast (ray, out hit, 100)) {
                    Debug.DrawLine (transform.position, hit.point, Color.white, 5f);
                    if (hit.collider.tag == "Enemy") {
                        GameObject e = hit.transform.gameObject;
                        e.GetComponent<ParticleSystem>().Emit(100);

                    }

                }
            }
            if (Input.GetKeyDown (KeyCode.Escape)) {
                Application.Quit();
            }
        }
 public static Matrix2D Look(Vector2 dir, Vector2 up)
 {
     up = com.spacepuppy.Utils.VectorUtil.RotateToward(dir, up, Mathf.PI / 2.0f, true).normalized;
     dir.Normalize();
     return new Matrix2D(dir.x, dir.y, up.x, up.y, 0f, 0f);
 }
Example #36
0
        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");
			bool doOnce = false;
			bool waswalking = _isWalking;

#if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            _isWalking = !Input.GetKey(KeyCode.LeftShift) || stamina <= staminaDrain;
           
			bool aim = false;
			if(_isWalking)
				aim = Input.GetButton("Fire2");
			_isCrouching = Input.GetKey(KeyCode.LeftControl);

            //Need this hear to set animations to proper weapon
            bool qSwapping = Input.GetKeyDown(KeyCode.Q);
            if (qSwapping) 
            {

                //SwapWeapons();
            }

            WeaponInput();

			//Slow mouse movement when aiming by 45 percent
			if(aim && !doOnce){
				_isWalking = true; 
				doOnce = true;
                if(GameObject.Find("Crosshair") != null)
                    GameObject.Find("Crosshair").GetComponent<RawImage>().enabled = false;
				_mouseLook.XSensitivity = mouseTempX - (mouseTempX * 0.45f);
				_mouseLook.YSensitivity = mouseTempY - (mouseTempY  * 0.45f);

				Debug.Log (_mouseLook.YSensitivity);
				
			}
            //Return Mouse movement values to default
            if (!aim)
            {
                doOnce = false;
                _mouseLook.XSensitivity = PlayerPrefs.GetFloat("xAxis");
                _mouseLook.YSensitivity = PlayerPrefs.GetFloat("yAxis");
                if (GameObject.Find("Crosshair") != null) { 
                    GameObject.Find("Crosshair").GetComponent<RawImage>().enabled = true;
                }
			}
			//Player Movement Animation Logic
			AnimationLogic(vertical, horizontal);

			//Weapon Animations
			anim.SetBool("Sprint", !_isWalking);
			anim.SetBool ("Aim", aim);

            //Drain Stamina if we are sprinting and moving
            if (!_isWalking && _characterController.velocity != Vector3.zero && stamina >= staminaDrain)
            {// && _characterController.velocity.x > 0.1f){
                stamina = stamina - staminaDrain;
                useHeadBob = true;
                
                //Debug.Log(stamina);
            }
            else if(_isWalking && useHeadBob) {
                //if sound not playing play it
                if (!gameObject.GetComponents<AudioSource>()[3].isPlaying)
                {
                    gameObject.GetComponents<AudioSource>()[3].Play();
                }
                useHeadBob = false;
                //gameObject.GetComponents<AudioSource>()[3].Stop();
            }
            //Stamina Regen conditions, regen only when they are not trying to run
            if (stamina <= 10  && !Input.GetKey(KeyCode.LeftShift) && !gameObject.GetComponents<AudioSource>()[3].isPlaying) {
                StaminaRegenCoroutine = StaminaRegen(3.0f);
                StartCoroutine(StaminaRegenCoroutine);
            }
            else if (stamina > 10 && stamina < 50 && !Input.GetKey(KeyCode.LeftShift))
            {
                StaminaRegenCoroutine = StaminaRegen(2.5f);
                StartCoroutine(StaminaRegenCoroutine);
            }
            else if (stamina >= 50 && stamina < 100 && !Input.GetKey(KeyCode.LeftShift))
            {
                StaminaRegenCoroutine = StaminaRegen(1.5f);
                StartCoroutine(StaminaRegenCoroutine);
            }
#endif
            // set the desired speed to be walking or running
            speed = walkSpeed;

			if (!_isWalking) {
			
				speed = runSpeed;
			}
			if (_isCrouching) {
				speed = crouchSpeed;			
			}
            //speed = _isWalking ? walkSpeed : runSpeed;
            _input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (_input.sqrMagnitude > 1) _input.Normalize();

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (_isWalking != waswalking && useFOVKick && _characterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!_isWalking ? _fovKick.FOVKickUp() : _fovKick.FOVKickDown());
            }
        }
 /// <summary>
 /// Find some projected angle measure off some forward around some axis.
 /// </summary>
 /// <param name="v"></param>
 /// <param name="forward"></param>
 /// <param name="axis"></param>
 /// <returns></returns>
 public static float AngleOffAroundAxis(Vector3 v, Vector3 forward, Vector3 axis)
 {
     v.Normalize();
     Vector3 right = Vector3.Cross(axis, forward).normalized;
     forward = Vector3.Cross(right, axis).normalized;
     Vector2 v2 = new Vector2(Vector3.Dot(v, forward), Vector3.Dot(v, right));
     v2.Normalize();
     return VectorUtil.Angle(v2);
 }
		//ドラッグによるログを記録
		void AddDragLog(Vector2 point)
		{
			const int dragPointMax = 10;
			dragPointNum = Mathf.Min(dragPointNum + 1, dragPointMax);
			for (int i = 0; i < dragPointNum - 1; ++i)
			{
				dragPointLogs[i + 1] = dragPointLogs[i];
			}
			dragPointLogs[0].point = startOffset + point;
			dragPointLogs[0].deltaTime = Time.deltaTime;

			if (dragPointNum > 1)
			{
				dragPointLogs[0].InitDirection(dragPointLogs[1].point);
			}
			else
			{
				dragPointLogs[0].ClearDirection();
			}

			dragDirection = Vector2.zero;
			dragSpeed = 0;
			int num = dragPointNum - 1;
			if (num > 0)
			{
				for (int i = 0; i < num; ++i)
				{
					dragDirection += dragPointLogs[i].direction * dragPointLogs[i].speed * dragPointLogs[i].deltaTime;
					dragSpeed += dragPointLogs[i].speed;
				}
				dragDirection.Normalize();
				dragSpeed /= num;
			}
		}
			/// <summary>
			/// 方向を初期化
			/// </summary>
			/// <param name="lastPoint"></param>
			public void InitDirection(Vector2 lastPoint)
			{
				direction = point - lastPoint;
				speed = direction.magnitude / deltaTime;
				direction.Normalize();
			}
        private void GetInput()
        {
            // Read input
            float horizontal = controlOverride.GetAxis("Horizontal");
            float vertical = controlOverride.GetAxis("Vertical");

#if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            //m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }
        }
 /// <summary>
 /// Angle in degrees off some axis in the counter-clockwise direction. Think of like 'Angle' or 'Atan2' where you get to control 
 /// which axis as opposed to only measuring off of <1,0>. 
 /// </summary>
 /// <param name="v"></param>
 /// <param name="axis"></param>
 /// <returns></returns>
 public static float AngleOff(Vector2 v, Vector2 axis)
 {
     if (axis.sqrMagnitude < 0.0001f) return float.NaN;
     axis.Normalize();
     var tang = new Vector2(-axis.y, axis.x);
     return AngleBetween(v, axis) * Mathf.Sign(Vector2.Dot(v, tang));
 }
    private void createVisionCone()
    {
        List <UnityEngine.Vector2> endPoints = new List <UnityEngine.Vector2>();

        endPoints.Add(this.transform.position);
        GameObject[] corners = GameObject.FindGameObjectsWithTag("verticies");

        SortedList <float, UnityEngine.Vector2> cornerList = new SortedList <float, UnityEngine.Vector2>();

        foreach (GameObject corner in corners)
        {
            float polarCoordinateTheta = (float)Math.Atan(System.Convert.ToDouble(corner.transform.position.y / corner.transform.position.x));
            try {
                cornerList.Add(polarCoordinateTheta, new UnityEngine.Vector2(corner.transform.position.x, corner.transform.position.y));
            } catch (ArgumentException exception) {
                cornerList.Add(polarCoordinateTheta + UnityEngine.Random.Range(0.0001f, 0.001f), new UnityEngine.Vector2(corner.transform.position.x, corner.transform.position.y));
            }
        }

        foreach (KeyValuePair <float, UnityEngine.Vector2> corner in cornerList)
        {
            UnityEngine.Vector2 raycastTarget = new UnityEngine.Vector2(corner.Value.x - this.transform.position.x, corner.Value.y - this.transform.position.y);
            raycastTarget.Normalize();
            RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, raycastTarget);
            if (endPoint.collider != null)
            {
                endPoints.Add(endPoint.point);
                Debug.DrawLine(this.transform.position, endPoint.point, Color.red);
            }
            else
            {
                Debug.DrawLine(this.transform.position, corner.Value, Color.green);
            }
        }

        UnityEngine.Vector2[] vertices2D = endPoints.ToArray();

        if (vertices2D.Length > 2)
        {
            for (int i = 1; i < vertices2D.Length; i++)
            {
                Debug.DrawLine(endPoints[i - 1], endPoints[i], Color.blue);
            }
        }

        UnityEngine.Vector3[] vertices3D = new UnityEngine.Vector3[vertices2D.Length];
        for (int i = 0; i < vertices3D.Length; i++)
        {
            vertices3D[i] = new UnityEngine.Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        Triangulator triangulator = new Triangulator(vertices2D);

        int[] indices = triangulator.Triangulate();

        MeshFilter visionCone     = this.GetComponentInChildren <MeshFilter>();
        var        visionConeMesh = visionCone.mesh;

        visionConeMesh.Clear();
        visionConeMesh.vertices  = vertices3D;
        visionConeMesh.uv        = vertices2D;
        visionConeMesh.triangles = indices;
    }
 public static Vector2 ClampToAxis(this Vector2 v, Vector2 axis)
 {
     var n = new Vector2(-axis.y, axis.x);
     n.Normalize();
     return v - n * Vector2.Dot(v, n);
 }
Example #44
0
        private void GetInput(out float speed)
        {
            float horizontal = CrossPlatformInputManager.GetAxis(SingletonNames.Input.HORIZONTAL);
            float vertical = CrossPlatformInputManager.GetAxis(SingletonNames.Input.VERTICAL);

            bool waswalking = isWalking;

            if (Input.GetMouseButton(0))
                attackController.startAttack();

            #if !MOBILE_INPUT

            isWalking = !Input.GetKey(KeyCode.LeftShift) && GamePlayer.states.energy > energyDec;

            if (!isWalking) {

                GamePlayer.states.energy -= energyDec;
                energyTimeStamp = Time.time;

            } else {

                if(Time.time-energyTimeStamp>1.5f && GamePlayer.states.energy!=GamePlayer.states.maxEnergy) // восстанавливаем энергию после простоя в 1,5 сек.
                    if(GamePlayer.states.energy<GamePlayer.states.maxEnergy)
                     GamePlayer.states.energy += energyInc;
                    else
                        GamePlayer.states.energy = GamePlayer.states.maxEnergy;

            }

            #endif

            speed = isWalking ? playerWalkSpeed : playerRunSpeed;
            speed *= isSitdown ? 0.5f : 1.0f;

            if (isWalking) {
                headBob.HorizontalBobRange = bobRangeWalk;
                headBob.VerticalBobRange   = bobRangeWalk;
            } else {
                headBob.HorizontalBobRange = bobRangeRun;
                headBob.VerticalBobRange   = bobRangeRun;
            }

            input = new Vector2(horizontal, vertical);

            if (input.sqrMagnitude > 1)
                input.Normalize();

            if (isWalking != waswalking && characterController.velocity.sqrMagnitude > 0) {
                StopAllCoroutines();
                StartCoroutine(!isWalking ? fovKick.FOVKickUp() : fovKick.FOVKickDown());
            }
        }
        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");

            bool waswalking = m_IsWalking;

#if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
            // set the desired speed to be walking or running
            speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
            }
        }
Example #46
0
        /// <summary>
        /// Collides and edge and a polygon, taking into account edge adjacency.
        /// </summary>
        /// <param name="manifold">The manifold.</param>
        /// <param name="edgeA">The edge A.</param>
        /// <param name="xfA">The xf A.</param>
        /// <param name="polygonB">The polygon B.</param>
        /// <param name="xfB">The xf B.</param>
        public static void CollideEdgeAndPolygon(ref Manifold manifold,
                                                 EdgeShape edgeA, ref Transform xfA,
                                                 PolygonShape polygonB, ref Transform xfB)
        {
            MathUtils.MultiplyT(ref xfA, ref xfB, out _xf);

            // Edge geometry
            _edgeA.V0 = edgeA.Vertex0;
            _edgeA.V1 = edgeA.Vertex1;
            _edgeA.V2 = edgeA.Vertex2;
            _edgeA.V3 = edgeA.Vertex3;
            Vector2 e = _edgeA.V2 - _edgeA.V1;

            // Normal points outwards in CCW order.
            _edgeA.Normal = new Vector2(e.y, -e.x);
            _edgeA.Normal.Normalize();
            _edgeA.HasVertex0 = edgeA.HasVertex0;
            _edgeA.HasVertex3 = edgeA.HasVertex3;

            // Proxy for edge
            _proxyA.Vertices[0] = _edgeA.V1;
            _proxyA.Vertices[1] = _edgeA.V2;
            _proxyA.Normals[0] = _edgeA.Normal;
            _proxyA.Normals[1] = -_edgeA.Normal;
            _proxyA.Centroid = 0.5f * (_edgeA.V1 + _edgeA.V2);
            _proxyA.Count = 2;

            // Proxy for polygon
            _proxyB.Count = polygonB.Vertices.Count;
            _proxyB.Centroid = MathUtils.Multiply(ref _xf, ref polygonB.MassData.Centroid);
            for (int i = 0; i < polygonB.Vertices.Count; ++i)
            {
                _proxyB.Vertices[i] = MathUtils.Multiply(ref _xf, polygonB.Vertices[i]);
                _proxyB.Normals[i] = MathUtils.Multiply(ref _xf.R, polygonB.Normals[i]);
            }

            _radius = 2.0f * Settings.PolygonRadius;

            _limit11 = Vector2.zero;
            _limit12 = Vector2.zero;
            _limit21 = Vector2.zero;
            _limit22 = Vector2.zero;

            //Collide(ref manifold); inline start
            manifold.PointCount = 0;

            //ComputeAdjacency(); inline start
            Vector2 v0 = _edgeA.V0;
            Vector2 v1 = _edgeA.V1;
            Vector2 v2 = _edgeA.V2;
            Vector2 v3 = _edgeA.V3;

            // Determine allowable the normal regions based on adjacency.
            // Note: it may be possible that no normal is admissable.
            Vector2 centerB = _proxyB.Centroid;
            if (_edgeA.HasVertex0)
            {
                Vector2 e0 = v1 - v0;
                Vector2 e1 = v2 - v1;
                Vector2 n0 = new Vector2(e0.y, -e0.x);
                Vector2 n1 = new Vector2(e1.y, -e1.x);
                n0.Normalize();
                n1.Normalize();

                bool convex = MathUtils.Cross(n0, n1) >= 0.0f;
                bool front0 = Vector2.Dot(n0, centerB - v0) >= 0.0f;
                bool front1 = Vector2.Dot(n1, centerB - v1) >= 0.0f;

                if (convex)
                {
                    if (front0 || front1)
                    {
                        _limit11 = n1;
                        _limit12 = n0;
                    }
                    else
                    {
                        _limit11 = -n1;
                        _limit12 = -n0;
                    }
                }
                else
                {
                    if (front0 && front1)
                    {
                        _limit11 = n0;
                        _limit12 = n1;
                    }
                    else
                    {
                        _limit11 = -n0;
                        _limit12 = -n1;
                    }
                }
            }
            else
            {
                _limit11 = Vector2.zero;
                _limit12 = Vector2.zero;
            }

            if (_edgeA.HasVertex3)
            {
                Vector2 e1 = v2 - v1;
                Vector2 e2 = v3 - v2;
                Vector2 n1 = new Vector2(e1.y, -e1.x);
                Vector2 n2 = new Vector2(e2.y, -e2.x);
                n1.Normalize();
                n2.Normalize();

                bool convex = MathUtils.Cross(n1, n2) >= 0.0f;
                bool front1 = Vector2.Dot(n1, centerB - v1) >= 0.0f;
                bool front2 = Vector2.Dot(n2, centerB - v2) >= 0.0f;

                if (convex)
                {
                    if (front1 || front2)
                    {
                        _limit21 = n2;
                        _limit22 = n1;
                    }
                    else
                    {
                        _limit21 = -n2;
                        _limit22 = -n1;
                    }
                }
                else
                {
                    if (front1 && front2)
                    {
                        _limit21 = n1;
                        _limit22 = n2;
                    }
                    else
                    {
                        _limit21 = -n1;
                        _limit22 = -n2;
                    }
                }
            }
            else
            {
                _limit21 = Vector2.zero;
                _limit22 = Vector2.zero;
            }

            //ComputeAdjacency(); inline end

            //EPAxis edgeAxis = ComputeEdgeSeparation(); inline start
            EPAxis edgeAxis = ComputeEdgeSeparation();

            // If no valid normal can be found than this edge should not collide.
            // This can happen on the middle edge of a 3-edge zig-zag chain.
            if (edgeAxis.Type == EPAxisType.Unknown)
            {
                return;
            }

            if (edgeAxis.Separation > _radius)
            {
                return;
            }

            EPAxis polygonAxis = ComputePolygonSeparation();
            if (polygonAxis.Type != EPAxisType.Unknown && polygonAxis.Separation > _radius)
            {
                return;
            }

            // Use hysteresis for jitter reduction.
            const float k_relativeTol = 0.98f;
            const float k_absoluteTol = 0.001f;

            EPAxis primaryAxis;
            if (polygonAxis.Type == EPAxisType.Unknown)
            {
                primaryAxis = edgeAxis;
            }
            else if (polygonAxis.Separation > k_relativeTol * edgeAxis.Separation + k_absoluteTol)
            {
                primaryAxis = polygonAxis;
            }
            else
            {
                primaryAxis = edgeAxis;
            }

            EPProxy proxy1;
            EPProxy proxy2;
            FixedArray2<ClipVertex> incidentEdge = new FixedArray2<ClipVertex>();
            if (primaryAxis.Type == EPAxisType.EdgeA)
            {
                proxy1 = _proxyA;
                proxy2 = _proxyB;
                manifold.Type = ManifoldType.FaceA;
            }
            else
            {
                proxy1 = _proxyB;
                proxy2 = _proxyA;
                manifold.Type = ManifoldType.FaceB;
            }

            int edge1 = primaryAxis.Index;

            FindIncidentEdge(ref incidentEdge, proxy1, primaryAxis.Index, proxy2);
            int count1 = proxy1.Count;

            int iv1 = edge1;
            int iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;

            Vector2 v11 = proxy1.Vertices[iv1];
            Vector2 v12 = proxy1.Vertices[iv2];

            Vector2 tangent = v12 - v11;
            tangent.Normalize();

            Vector2 normal = MathUtils.Cross(tangent, 1.0f);
            Vector2 planePoint = 0.5f * (v11 + v12);

            // Face offset.
            float frontOffset = Vector2.Dot(normal, v11);

            // Side offsets, extended by polytope skin thickness.
            float sideOffset1 = -Vector2.Dot(tangent, v11) + _radius;
            float sideOffset2 = Vector2.Dot(tangent, v12) + _radius;

            // Clip incident edge against extruded edge1 side edges.
            FixedArray2<ClipVertex> clipPoints1;
            FixedArray2<ClipVertex> clipPoints2;
            int np;

            // Clip to box side 1
            np = ClipSegmentToLine(out clipPoints1, ref incidentEdge, -tangent, sideOffset1, iv1);

            if (np < Settings.MaxManifoldPoints)
            {
                return;
            }

            // Clip to negative box side 1
            np = ClipSegmentToLine(out clipPoints2, ref clipPoints1, tangent, sideOffset2, iv2);

            if (np < Settings.MaxManifoldPoints)
            {
                return;
            }

            // Now clipPoints2 contains the clipped points.
            if (primaryAxis.Type == EPAxisType.EdgeA)
            {
                manifold.LocalNormal = normal;
                manifold.LocalPoint = planePoint;
            }
            else
            {
                manifold.LocalNormal = MathUtils.MultiplyT(ref _xf.R, ref normal);
                manifold.LocalPoint = MathUtils.MultiplyT(ref _xf, ref planePoint);
            }

            int pointCount = 0;
            for (int i1 = 0; i1 < Settings.MaxManifoldPoints; ++i1)
            {
                float separation = Vector2.Dot(normal, clipPoints2[i1].V) - frontOffset;

                if (separation <= _radius)
                {
                    ManifoldPoint cp = manifold.Points[pointCount];

                    if (primaryAxis.Type == EPAxisType.EdgeA)
                    {
                        cp.LocalPoint = MathUtils.MultiplyT(ref _xf, clipPoints2[i1].V);
                        cp.Id = clipPoints2[i1].ID;
                    }
                    else
                    {
                        cp.LocalPoint = clipPoints2[i1].V;
                        cp.Id.Features.TypeA = clipPoints2[i1].ID.Features.TypeB;
                        cp.Id.Features.TypeB = clipPoints2[i1].ID.Features.TypeA;
                        cp.Id.Features.IndexA = clipPoints2[i1].ID.Features.IndexB;
                        cp.Id.Features.IndexB = clipPoints2[i1].ID.Features.IndexA;
                    }

                    manifold.Points[pointCount] = cp;

                    ++pointCount;
                }
            }

            manifold.PointCount = pointCount;

            //Collide(ref manifold); inline end
        }