- Home /
Movement issues with keyboard
Hello, my first question, so not sure if it is too over asked, but I really need some help.
So, I'm making a top down game, and I have movement code below, and the diagnol movement is faster than the crossWay moving. Any ideas? Thanks a million guys it would help a lot
--Peace
 public float speed;
     public Vector2 position;
 
     public void Update()
     {
         CheckInput();
         transform.position = position;
     }
 
     public void CheckInput()
     {
         if (Input.GetKey(KeyCode.W))
             position.y += 1;
         if (Input.GetKey(KeyCode.S))
             position.y -= 1;
         if (Input.GetKey(KeyCode.A))
             position.x -= 1;
         if (Input.GetKey(KeyCode.D))
             position.x += 1;
     }
Answer by Xarbrough · Jun 15, 2015 at 12:01 AM
There are two ways to do this:
 if(Input.GetKey (KeyCode.W))
 {
     transform.position = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
 }
 
 if(Input.GetKey (KeyCode.S))
 {
     Vector3 nextPosition = transform.position;
     nextPosition.y -= 1;
     transform.position = nextPosition;
 }
For a detailed explanation why: Unity official tutorials - Data Types
In short: You cannot modify your position value, because it is only a copy of transform.position. Instead modify transform.position. Secondly, you cannot modify transform.position.y directly, because it only returns a copy of the value, not the actual reference to the object transform. You have to assign a whole new Vector3 to transform.position to change it.
Answer by cmonroy · Mar 10, 2016 at 04:39 AM
It seems to me that you need to normalize diagonal movement using Time.deltatime...
You move left, right, forward or backwards one unit at a given time, but to move diagonal you need to traverse two units in the same amount of time. Hence, the additional speed perceived.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                