unity topdown movement 2d code example
Example 1: unity 2D top down movement
public float moveSpeed = 5f;
public Rigidbody2D rb;
private Vector2 _movement;
void Update()
{
_movement.x = Input.GetAxisRaw("Horizontal");
_movement.y = Input.GetAxisRaw("Vertical");
_movement = new Vector2(_movement.x, _movement.y).normalized;
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + _movement * moveSpeed * Time.fixedDeltaTime);
}
Example 2: top down 2d movement unity
public float Speed = 5f;
private void Update()
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0);
Vector3 velocity = input.normalized * Speed;
transform.position += velocity * Time.deltaTime;
}