当前位置: 首页>>代码示例>>C#>>正文


C# Vector2.Normalize方法代码示例

本文整理汇总了C#中UnityEngine.Vector2.Normalize方法的典型用法代码示例。如果您正苦于以下问题:C# Vector2.Normalize方法的具体用法?C# Vector2.Normalize怎么用?C# Vector2.Normalize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在UnityEngine.Vector2的用法示例。


在下文中一共展示了Vector2.Normalize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FixedUpdate

        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);
        }
开发者ID:arhpositive,项目名称:GGJ2016,代码行数:25,代码来源:Ball.cs

示例2: CmdSpawnBullet

 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);
 }
开发者ID:TheWulo,项目名称:DontDoIt,代码行数:8,代码来源:PlayerWeapon.cs

示例3: run

 private void run()
 {
     if (checkDistance() <= _control.Settings.DistanceToRun)
     {
         _direction = _control.transform.position - _control.Settings.Monster.transform.position;
         _direction.Normalize();
     }
 }
开发者ID:gracianogodoy,项目名称:GameJam,代码行数:8,代码来源:IAInput.cs

示例4: SetTrajectory

        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;
        }
开发者ID:Ben-P-Leda,项目名称:Leda-CoB-Remake,代码行数:10,代码来源:WarpTracker.cs

示例5: AttackOnPlayer

 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);
     }
 }
开发者ID:Danton19,项目名称:UnityGame01,代码行数:11,代码来源:EnemyAI01.cs

示例6: PlayerMovesAtNormalizedSpeedWhenMovingDiagonal

        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);
        }
开发者ID:CaliberMengsk,项目名称:gateway2dwest,代码行数:15,代码来源:PlayerMovementTest.cs

示例7: PlayerMovesAtNormalizedSpeedWhenMovingDiagonal

        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);
        }
开发者ID:kurtosterhage,项目名称:gateway2dwest,代码行数:15,代码来源:PlayerMovementTest.cs

示例8: OnCollisionStay2D

        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);
        }
开发者ID:stlgamedev,项目名称:gateway2dwest,代码行数:19,代码来源:DamageDealerTest.cs

示例9: getAngleOfVector

        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;
        }
开发者ID:RandomTiger,项目名称:OgresLairVR,代码行数:19,代码来源:Entity.cs

示例10: TransformToPosition

        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;
        }
开发者ID:gregoriobenatti,项目名称:spjam2015,代码行数:23,代码来源:HatGuyJoystick.cs

示例11: Compute

        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;
        }
开发者ID:silverweed,项目名称:colony,代码行数:24,代码来源:Wander.cs

示例12: PhillipsSpectrum

        /// <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);
        }
开发者ID:Togene,项目名称:BeCalm,代码行数:26,代码来源:Ocean.cs

示例13: Start

        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();
        }
开发者ID:Togene,项目名称:BeCalm,代码行数:85,代码来源:Ocean.cs

示例14: OnDrag

        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;
        }
开发者ID:xclouder,项目名称:godbattle,代码行数:68,代码来源:SimpleJoystick.cs

示例15: GetInput

        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());
            }
        }
开发者ID:Baensi,项目名称:Assets,代码行数:52,代码来源:IngroundMovements.cs


注:本文中的UnityEngine.Vector2.Normalize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。