Author Topic: Getting player horizontal velocity  (Read 4400 times)

How would I get the horizontal speed of a player?

I am using getvelocity
%PSpeed = mAbs(getWord(%player.getvelocity(), 0)) + mAbs(getWord(%player.getvelocity(), 1));
This works correctly if the player is moving on the x or y axis, but going diagonal gives a higher number.

Going at a speed of 20 on the x axis gives: 19.9... and 0.1... combined gives 20
Going at a speed of 20 diagonally gives: 13.5... and 12.5... combined gives 25 for some reason

Is there a better way or what am I doing wrong?

Well the reason it's giving incorrect results is because you're using simple addition.

What you need to do is use the pythagorean formula for finding the hypotenuse of a triangle. That would be the sqrt(A2+B2)

or, do VectorLen(getWords(%velocity, 0, 1) SPC 0), which is essentially the same thing that Ipquarx said in one shorter statement

p sure appending 0 isn't necessary but

Of course, why didn't I think of that!
Thanks Ip and otto

So my final code is:
    %Vec1 = mAbs(getWord(%player.getvelocity(), 0));
    %Vec2 = mAbs(getWord(%player.getvelocity(), 1));

    %PSpeed = msqrt((%Vec1*%Vec1) + (%Vec2*%Vec2));

Its worth noting that vectorLen(getWords(%player.getVelocity(), 0, 1)) is more efficient not only in physical space, but also to be executed, as vectorLen is an engine level function, which lets it run a lot faster than doing the math yourself in torquescript. While there's no noticable difference normally, if you start running this script thousands of times a second, then it will start to add up.

Also worth nothing that there's no reason to use mAbs if you're going to square the result, as the sign will drop away anyways.