void Update()
{
if (Input.GetKey(KeyCode.D) || (Input.GetKey(KeyCode.RightArrow)))
{
GetComponent().velocity = new Vector2(moveSpeed, GetComponent().velocity.y);
}
else if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.LeftArrow)))
{
GetComponent().velocity = new Vector2(-moveSpeed, GetComponent().velocity.y);
}
else if (Input.GetKey(KeyCode.S) || (Input.GetKey(KeyCode.DownArrow)))
{
GetComponent().velocity = new Vector2(-moveSpeed, GetComponent().velocity.x);
}
else if (Input.GetKey(KeyCode.W) || (Input.GetKey(KeyCode.UpArrow)))
{
GetComponent().velocity = new Vector2(moveSpeed, GetComponent().velocity.x);
}
else
{
GetComponent().velocity = new Vector2(0, GetComponent().velocity.y);
GetComponent().velocity = new Vector2(0, GetComponent().velocity.x);
}
}
Because that’s not how a Vector2 works. A Vector2 has an x and a y component. In all cases except the last one, you are setting the moveSpeed to the x component en the velocity.x or .y to the y component. Short answer: It’s just all wrong and mixed up. In most cases you want to use the x component for horizontal movement, so AD or left right, and the y component for vertical movement so WS or up down.
Then the last statement, the else, you are first setting the velocity to {0, velocity.y} and the next line you are setting the velocity to {0, velocity.x}. So you are just overwriting your own statement, which of course will not work how you want.
Lastly, not a must, but definitely better: You dont have to use GetComponent() for everytime you need the rigidbody. Just use the Start() function to get the Rigidbody once, and assign it to a variable. Then in the rest of the script you use that variable. This is better for performance and more readable.
So my suggestion to you, check what a Vector2 is, check how to use GetComponent() efficiently, and check the input manager of unity, because you dont have to use OR for those buttons (Like Left || A), because you could just set alternative buttons in the input manager.