Unity AddForce Problem (not a bug problem, but a math problem)

Sorry for the lack of details in the title, the reason for that is that I don’t know a short way of how to explain the problem I want to solve. Here’s some context: I’m making a 3D platformer game where my player is a sphere that rolls and jumps around. I’ve already got in an orbital camera, the controls work fine and everything, but the method I use to move my player around is AddForce.

Problem:

This becomes a problem when I hold down both the W and the D key, it’s applying the same speed unit to both the x and the z axis, which is actually causing my sphere to move faster diagonally rather than laterally. I’ve included a bit of a diagram at the bottom of what’s happening versus what I’m trying to get to happen:

For the purposes of simplicity, let’s only add forces of 1 unit. Let the green arrow represent the force being applied.

Uhm you have to normalize your force vector. Or if you want to have smaller values you may want to use Vector3.ClampMagnitude with a max length of 1f. This will make the vector to be clamped to the length of 1 only if it’s larger.

109823-root2tri.gif

What you should do is detect when there is both Vertical and Horizontal input and then instead do rb.AddForce(0.7071, 0, 0.7071)