Home > Software design >  Object moves faster going in the diagonal
Object moves faster going in the diagonal

Time:11-26

I made a little player script by myself to make my player move, but I wanted the speed to be cut in half when he is moving in the diagonal because it has double the value of whenever he is going in a straight line. How would that be possible?

void Update()
    {
        Vector3 direction = new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime );
        gameObject.transform.position = gameObject.transform.position   direction;  
    }

CodePudding user response:

but I wanted the speed to be cut in half when he is moving in the diagonal because it has double the value of whenever he is going in a straight line

No, actually it will be up to times √(2) ;)

You want to be using Vector3.ClampMagnitude in order to always have a maximum magnitude of 1f for your input:

void Update()
{
    var input = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    gameObject.transform.position  = Vector3.ClampMagnitude(direction, 1f) * moveSpeed * Time.deltaTime;  
}
  • Related