Yami
Yami

Reputation: 7

addforce moving diagonally faster

I am still a novice with Unity and am trying to make a top down 2D game and am stuck with the movement script where the movement is faster when I move diagonally. When I use normalized on the "axis" vector2 and start moving the player keeps moving for a bit and then stops moving suddenly when I stop pressing on any key and when I remove the normalized the movement goes back to normal and the player stops moving slowly and perfectly, but still when I move diagonally it is faster.

Here is my code:

{
Rigidbody2D rb;
Vector2 axis;

public float Speed = 400;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
    movement();
}

void movement()
{
    axis = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normlized * Speed;
    rb.AddForce(axis, ForceMode2D.Force);
    rb.drag = 60;

}
}

Upvotes: 0

Views: 558

Answers (1)

derHugo
derHugo

Reputation: 90862

What happens is that the returned values of GetAxis are smoothed over some frames. So when you normalize the vector it returns a magnitude of 1 for a while even though your input is actually smaller than that since it is smoothing out.

In general instead of

new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical").normalized`

which always returns magnitude 1 also for smaller input you rather want to use Vector2.ClampMagnitude

axis = Vector2.ClampMagnitude(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")), 1f) * Speed;

which only clamps if the vector has a total magnitude > 1

Upvotes: 0

Related Questions