Created
September 18, 2017 19:53
-
-
Save Ekalips/9c1afb23869092807c311dfc73d58dc3 to your computer and use it in GitHub Desktop.
Animations and stuff
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
package com.ekalips; | |
/** | |
* Created by Ekalips on 9/18/2017. | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
Point a = new Point(0, 0); | |
Point b = new Point(0, 100); | |
Animator animator = new Animator(200, a, b); | |
animator.setValueChangeCallback(p -> drawChartLine(a, p)); | |
animator.run(); | |
} | |
public static void drawChartLine(Point a, Point b) { | |
//do stuff | |
System.out.println("x: " + b.getX() + " y: " + b.getY()); | |
} | |
static class Point { | |
float x, y; | |
Point(float x, float y) { | |
this.x = x; | |
this.y = y; | |
} | |
float getX() { | |
return x; | |
} | |
float getY() { | |
return y; | |
} | |
void setX(float x) { | |
this.x = x; | |
} | |
void setY(float y) { | |
this.y = y; | |
} | |
} | |
static class Animator { | |
static int MIN_THRESHOLD = 17; | |
float duration; // 200 ms | |
Point start; // (0;0) | |
Point end; // (0;100) | |
Point currentPoint; | |
ValueChangeCallback valueChangeCallback; | |
public Animator(float duration, Point start, Point end) { | |
this.duration = duration; | |
this.start = start; | |
this.end = end; | |
currentPoint = start; | |
} | |
public void setValueChangeCallback(ValueChangeCallback valueChangeCallback) { | |
this.valueChangeCallback = valueChangeCallback; | |
} | |
public void run() { | |
float addX = (end.getX() - start.getX()) / duration; // per millisecond (0) | |
float addY = (end.getY() - start.getY()) / duration; // per millisecond (0.5) | |
new Thread() { | |
@Override | |
public void run() { | |
super.run(); | |
long timeNow = System.currentTimeMillis(); | |
while (currentPoint.getX() < end.getX() || currentPoint.getY() < end.getY()) { | |
long passedTime = System.currentTimeMillis() - timeNow; | |
if (passedTime < MIN_THRESHOLD) { | |
continue; | |
} | |
timeNow = System.currentTimeMillis(); | |
float passedAddX = addX * passedTime; | |
float passedAddY = addY * passedTime; | |
float newX = currentPoint.x + passedAddX; | |
float newY = currentPoint.y + passedAddY; | |
if (Math.abs(newX) > Math.abs(end.getX())) { | |
newX = end.getX(); | |
} | |
if (Math.abs(newY) > Math.abs(end.getY())) { | |
newY = end.getY(); | |
} | |
currentPoint.setX(newX); | |
currentPoint.setY(newY); | |
valueChangeCallback.onValueChanged(currentPoint); | |
} | |
} | |
}.start(); | |
} | |
public interface ValueChangeCallback { | |
void onValueChanged(Point p); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment