How to use getLinearVelocity values

Hi - sorry, yet another basic question from me:

I’d like to put a speed meter on the screen to show some indication of the speed a display object is moving. I thought I’d be able to use getLinearVelocity for this, and I’m trying the following:

[lua]

function onEveryFrame( e )

local vx, vy = crate:getLinearVelocity()

print (“vx=” … vx)

speedx = vx

return speedx

end

Runtime:addEventListener( “enterFrame”, onEveryFrame )

local speed = display.newText( "speed: " … speedx, 80, 20, native.systemFont, 22 )

speed:setFillColor( 1, 0, 0.5 )

[/lua]

But this doesn’t work.

The values appear in the terminal, but nothing is passed through to the ‘speed’ display object.

My thinking is that

[lua]

return speedx

[/lua]

will feed the value back for the ‘speed’ display object to pick up.

I’ve tried using ‘vx’ instead of ‘speedx’ but it doesn’t help.

Another consideration is where I’m putting the Runtime listener - I’m using Composer and I thought the listener should go within scene:show … but that throws up errors.

(Mini question - I’m passing ‘e’ into the onEveryFrame function - would ‘event’ do just as well?)

Many thanks for any advice.

Hi @newbie1001,

The value (appearance) of the “speed” text object will not automatically update just because you reset the value of “speedx”. You need to explicitly tell Corona to update this text object by setting its .text property after you update (get) “vx” from the “getLinearVelocity()” function.

Hope this helps,

Brent

Hi Brent, Thank you that’s fixed it for me! Excellent!

Could I ask about e/event - are the following the same?

  1. function onEveryFrame( e )
  2. function onEveryFrame( event )

Yes, you can substitute “e” for “event”, as long as you remember to also use “e” if you need to reference that value within the function (in this case, you don’t even need it, but just for future reference…)

Brent

Brilliant, thank you.

Hi @newbie1001,

The value (appearance) of the “speed” text object will not automatically update just because you reset the value of “speedx”. You need to explicitly tell Corona to update this text object by setting its .text property after you update (get) “vx” from the “getLinearVelocity()” function.

Hope this helps,

Brent

Hi Brent, Thank you that’s fixed it for me! Excellent!

Could I ask about e/event - are the following the same?

  1. function onEveryFrame( e )
  2. function onEveryFrame( event )

Yes, you can substitute “e” for “event”, as long as you remember to also use “e” if you need to reference that value within the function (in this case, you don’t even need it, but just for future reference…)

Brent

Brilliant, thank you.