Try to use the InputManager (Unity - Manual: Input Manager) and then just do this: float movex = Input.GetAxisRaw("Horizontal"); float movey = Input.GetAxisRaw("Vertical"); GetComponent<Rigidbody2D>().velocity = new Vector2(movex * moveSpeed, movey * moveSpeed);
Thats how I do it and it’s way shorter and more efficient than your method.
public class MoveController : MonoBehaviour
{
private void Update ()
{
Vector3 euler = Vector3.zero;
if (Input.GetKey (KeyCode.W))
euler.z = 0;
else if (Input.GetKey (KeyCode.A))
euler.z = 90;
else if (Input.GetKey (KeyCode.S))
euler.z = 180;
else if (Input.GetKey (KeyCode.D))
euler.z = 270;
else
return;
//direction
Quaternion rotation = new Quaternion ();
rotation.eulerAngles = euler;
transform.rotation = rotation;
//translate
Vector3 translate = Vector3.zero;
translate.y += move_speed;
transform.Translate (translate);
}
public float move_speed = 0.01f;
}
you can dont care about translate,force on the angle totally
you can use familiar angle expression by eulerAngle
when you make sure your direction is correct, the simple way is translate the axis’s y
Of course you can use Rigidbody2D.velocity as it is shown in thousand of scripts here… Anyway I’ve found the solution by myself just using Rigidbody2D.GetRelativeVector().