Skip to content

Instantly share code, notes, and snippets.

@zzox
Created June 1, 2021 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzox/aa321c832de9af54d50de41c553a237a to your computer and use it in GitHub Desktop.
Save zzox/aa321c832de9af54d50de41c553a237a to your computer and use it in GitHub Desktop.
Tween between two sets of values in HaxeFlixel without duplicating tweens from repeated calls.
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);
}
}
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