movement tweening

BlitzMax Forums/BlitzMax Beginners Area/movement tweening

coffeedotbean(Posted 2013) [#1]
Any one got some simple code or example that shows movement tweening.

I need to move an object from point A to point B and for that journey to take a fixed amount of seconds, lets say 2 seconds regardless of how far apart point A and B are.

I need a formula to work out how fast the object needs to travel, to maintain a 2 second travel time whether A and B are 100px apart or even 1000px apart.

I have googled tweening but cannot seem to find what I am looking for.


Ravl(Posted 2013) [#2]
Well if:

100px ............ 2 seconds
X px ............... currentTimeSinceStart

you need to find X:

X = (100 px * currentTimeSinceStart) / 2

Basically if you know (and you know) when the sprite has start to move you can always know how many pixels he 'traveled'


Kryzon(Posted 2013) [#3]
You want to know how much the object has to walk 'per frame'. This requires you to define a target frames-per-second. Let's say your target FPS is 60, the default in BMax.

60 frames for a single second. Two seconds will have (2 x 60) = 120 frames total.

So divide the distance, whatever it might be, by 120. You will get how much the object has to walk 'per frame', under a 60 FPS logic, to cover that distance in two seconds.

You can wrap this logic in a function which returns the per-frame distance:
Type Vector2D
	Field x:Float, y:Float
End Type

Function walkInTwoSeconds:Vector2D(A:Vector2D, B:Vector2D, FPS:Float = 60.0)
	'AB -> Vector that goes from A to B.
	
	'Get the vector components (horizontal and vertical).
	Local ABWidth:Float = B.x - A.x
	Local ABHeight:Float = B.y - A.y
	
	Local seconds:Float = 2.0
	Local perFrameVector:Vector2D = New Vector2D
	perFrameVector.x = ABWidth / (FPS*seconds)
	perFrameVector.y = ABHeight / (FPS*seconds)

	Return perFrameVector	
End Function

Usage:
Local walkVector:Vector2D = walkInTwoSeconds(A, B)

Local starTime:Int = Millisecs()

[...]

If (startTime + 2000) > Millisecs() Then
	myObject.position.x += walkVector.x
	myObject.position.y += walkVector.y
Else
	Print "Object reached its destination in two seconds."
	WaitKey()
	End
EndIf



TomToad(Posted 2013) [#4]
One way is to use delta tweening. Just use the percentage of time passed and multiply to the distance needed to move. This way, the time is the same regardless of distance and framerate.

Edit: Just looked up the correct way to tween between two points. Even though my equation works, with the correct way, no need to calculate the distance, and you can also make modifications easier such as ease-in and ease-out.

My equation


Correct equation



coffeedotbean(Posted 2013) [#5]
WOW thanks guys, more than I could have asked for,I have tried out all methods you suggested and got it working as I intended, just need to decide which on to stick with. Thanks.