Created
June 1, 2021 21:51
Tween between two sets of values in HaxeFlixel without duplicating tweens from repeated calls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Snapper; | |
import flixel.FlxSprite; | |
// Example Squash-n-Strech | |
class Player extends FlxSprite { | |
var stretchDownSnapper:Snapper; | |
public function new (x:Float, y:Float) { | |
super(x, y); | |
stretchDownSnapper = new Snapper( | |
this, | |
{ "scale.x": 1, "scale.y": 1 }, | |
{ "scale.x": 0.75, "scale.y": 1.33 }, | |
0.05 | |
); | |
} | |
override public function update (elapsed:Float) { | |
if (FlxG.keys.pressed.DOWN) { | |
velocity.y = 600; | |
stretchDownSnapper.push(); | |
} else { | |
stretchDownSnapper.pull(); | |
} | |
super.update(elapsed); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flixel.tweens.FlxTween; | |
import flixel.tweens.FlxTween.TweenOptions; | |
enum SnapperState { | |
Pushing; | |
Pulling; | |
Pushed; | |
Pulled; | |
} | |
// used to move tween between two different values without duplicating tweens | |
class Snapper { | |
var state:SnapperState; | |
var pullTween:Null<FlxTween>; | |
var pushTween:Null<FlxTween>; | |
var target:Dynamic; | |
var time:Float; | |
var pullValues:Dynamic; | |
var pushValues:Dynamic; | |
var options:Null<TweenOptions>; | |
public function new (target:Dynamic, pullValues:Dynamic, pushValues:Dynamic, time:Float, ?options:TweenOptions) { | |
state = Pulled; | |
this.target = target; | |
this.time = time; | |
this.pullValues = pullValues; | |
this.pushValues = pushValues; | |
this.options = options; | |
} | |
public function push () { | |
var t = time; | |
if (state == Pulling || state == Pulled) { | |
if (state == Pulling) { | |
t = pullTween.percent * time; | |
pullTween.cancel(); | |
} | |
pushTween = FlxTween.tween(target, pushValues, t, options); | |
pushTween.onComplete = (_:FlxTween) -> state = Pushed; | |
state = Pushing; | |
} | |
} | |
public function pull () { | |
var t = time; | |
if (state == Pushing || state == Pushed) { | |
if (state == Pushing) { | |
t = pushTween.percent * time; | |
pushTween.cancel(); | |
} | |
pullTween = FlxTween.tween(target, pullValues, t, options); | |
pullTween.onComplete = (_:FlxTween) -> state = Pulled; | |
state = Pulling; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment