jozza710
jozza710

Reputation: 95

Gradually Increasing Movement Speed Using Normalized Speed

As the title says, I wish to achieve gradually increasing movement speed using a xbox controller's left thumbstick and the Input.GetAxis() method. The issue is I need to normalize the movement vector in order to stop diagonal movement being faster than forward, backwards, etc.. movements. Normalizing will automatically make the magnitude 1 so I lose the ability to control speed with the position of my left thumbstick. Thanks in Advance!

Can control speed amount with position of thumb stick, however diagonal movement is faster than other movement.

    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

    rigidBody.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime);

Can't contol speed amount with position of thumb stick, however diagonal movement is the same speed as other movement.

    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

    rigidBody.MovePosition(transform.position + moveDirection.normalized * moveSpeed * Time.deltaTime);

Upvotes: 0

Views: 486

Answers (2)

Rather than normalize or scale: clamp.

Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 moveDirection = new Vector3(
    Mathf.Clamp(input.x, -Mathf.Abs(input.normalized.x), Mathf.Abs(input.normalized.x)),
    0,
    Mathf.Clamp(input.z, -Mathf.Abs(input.normalized.z), Mathf.Abs(input.normalized.z))
);

rigidBody.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime);

All values inside the unit circle will remain unchanged, while values outside the unit circle are recalculated to be on the unit circle.

Could also write it as:

Vector3 move = (input.magnitude<1?input:input.normalized);

Upvotes: 1

jozza710
jozza710

Reputation: 95

There is probably a better solution to this issue but this is how I solved it. I am going to leave the ability to answer this question open for a while to see if anyone else has a better solution.

    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

    rigidBody.MovePosition(transform.position +  new Vector3(moveDirection.normalized.x * moveSpeed * Time.deltaTime * Mathf.Abs(moveDirection.x), 0,
                                                             moveDirection.normalized.z * moveSpeed * Time.deltaTime * Mathf.Abs(moveDirection.z)));

Upvotes: 0

Related Questions