- Home /
 
 
               Question by 
               BenediktFisch · May 21, 2016 at 11:13 AM · 
                scripting problem2d gamemovement scriptdirection  
              
 
              How can i normalize 2d Vectors?
I´ve coded some very basic player movement
 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour {
 
     private bool isDodging;
     private Vector2 direction;
     private float stamina;
     private float characterSpeed = 0.10F;
     
     void Start()
     {
         stamina = 100f;
     }
 
     void FixedUpdate()
     {                                                 
         if (Input.GetKey(KeyCode.W))                                
         {
             direction = Vector2.up;
             transform.Translate(direction * characterSpeed);
         }
         if (Input.GetKey(KeyCode.A))
         {
             direction = Vector2.left;
             transform.Translate(direction * characterSpeed);
         }
         if (Input.GetKey(KeyCode.S))
         {
             direction = Vector2.down;
             transform.Translate(direction * characterSpeed);
         }
         if (Input.GetKey(KeyCode.D))
         {
             direction = Vector2.right;
             transform.Translate(direction * characterSpeed);
         }
 
         if (isDodging != true)
         {
             if (Input.GetKey(KeyCode.LeftShift))
             {
                 characterSpeed = 0.2F;
             }
             else
             {
                 characterSpeed = 0.10F;
             }
         }
 
         if (Input.GetKeyDown(KeyCode.Space))
         {
             StartCoroutine("Roll");
         }
             
     }
 
     IEnumerator Roll()
     {
         isDodging = true;
         characterSpeed = 0.20f;
 
         yield return new WaitForSeconds(0.3f);
 
         characterSpeed = 0.05f;
 
         yield return new WaitForSeconds(0.25f);
 
         isDodging = false;
         characterSpeed = 0.10f;
     }
 }
 
               When 2 directions are pressed simultaneously the resulting speed is higher.
How can i prevent this?
               Comment
              
 
               
              Answer by michal253 · May 21, 2016 at 06:02 PM
  void FixedUpdate()
  {   
       direction = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"));
       direction.Normalize();
       transform.Translate(direction*Time.deltaTime*characterSpeed);
  }
 
 
              Your answer