I am looking for a solution to add node's with fade-in or flipping or any animation.
Thanks for any help.
I found the same question but without any further help here: Animated component adding-delete in a VBox
As jewelsea already mentioned, you would use Transitions.
Here is an example of how to do it for your use case :
public static void addFadingIn(final Node node, final Group parent) {
final FadeTransition transition = new FadeTransition(Duration.millis(250), node);
transition.setFromValue(0);
transition.setToValue(1);
transition.setInterpolator(Interpolator.EASE_IN);
parent.getChildren().add(node);
transition.play();
}
public static void removeFadingOut(final Node node, final Group parent) {
if (parent.getChildren().contains(node)) {
final FadeTransition transition = new FadeTransition(Duration.millis(250), node);
transition.setFromValue(node.getOpacity());
transition.setToValue(0);
transition.setInterpolator(Interpolator.EASE_BOTH);
transition.setOnFinished(finishHim -> {
parent.getChildren().remove(node);
});
transition.play();
}
}
Or a more gerneral implementation using Java8 :
public static void addAnimating(final Node node, final Group parent,
final Supplier<Animation> animationCreator) {
parent.getChildren().add(node);
animationCreator.get().play();
}
public static void removeAnimating(final Node node, final Group parent,
final Supplier<Animation> animationCreator) {
if (parent.getChildren().contains(node)) {
final Animation animation = animationCreator.get();
animation.setOnFinished(finishHim -> {
parent.getChildren().remove(node);
});
animation.play();
}
}
You can find a full example on https://gist.github.com/bugabinga/9576634
You can use the built-in Transitions or a 3rd party library such as FXExperience Canned Animations.
For an example of integrating an animation with a standard layout pane see this LayoutAnimator code used in the example solution to: Animation upon layout changes. The LayoutAnimator is very generic and will work with other Panes than the FlowPane sample it is provided with (it just looks a bit cooler with the FlowPane).
Related
I am searching for a way to animate the dots between two markers on a google map in android device.
So what i want in the end is the following line between the two images:
and it would be used like this typical google polyline implementation:
lets say there is a point A and a Point B. if im directing the user to point B, then the line animates to from point A to point B so the user knows to walk in this direction.
to achieve this i thought i could get the points out of the polyLine and remove them and add them back
rapidily. so lets say i had 5 points in the polyLine, i would remove position 1 , then put it back, then remove position 2, and put it back, to simulate this animation.
but it does not work . once hte polyline is set it seems i cannot alter it. you have any suggestions ?
val dotPattern = Arrays.asList(Dot(), Gap(convertDpToPixel(7).toFloat()))
val polyLineOptions: PolylineOptions = PolylineOptions()
.add(usersLocation)
.add(users_destination)
.pattern(dotPattern)
.width(convertDpToPixel(6).toFloat())
dottedPolyLine = googleMap.addPolyline(polyLineOptions)
dottedPolyLine?.points?.removeAt(1) // here as a test if my idea i try removing a point but it looks like a point here means current location or destination so there always 2. i thought a point would be one of the dots.
You can use MapView-based custom view View Canvas animationlike in this answer:
This approach requires
MapView-based
custom
view,
that implements:
drawing over the MapView canvas;
customizing line styles (circles instead of a simple line);
binding path to Lat/Lon coordinates of map
performing animation.
Drawing over the MapView needs to override dispatchDraw().
Customizing line styles needs
setPathEffect()
method of
Paint
class that allows to create create path for "circle stamp" (in
pixels), which will repeated every "advance" (in pixels too),
something like that:
mCircleStampPath = new Path(); mCircleStampPath.addCircle(0,0,
CIRCLE_RADIUS, Path.Direction.CCW); mCircleStampPath.close();
For binding path on screen to Lat/Lon coordinates
Projection.toScreenLocation()
needed, that requires
GoogleMap
object so custom view should implements OnMapReadyCallback for
receive it. For continuous animation
postInvalidateDelayed()
can be used.
but not draw path directly from point A to point B, but from point A to point C that animated from A to B. To get current position of point C you can use SphericalUtil.interpolate() from Google Maps Android API Utility Library. Something like that:
public class EnhancedMapView extends MapView implements OnMapReadyCallback {
private static final float CIRCLE_RADIUS = 10;
private static final float CIRCLE_ADVANCE = 3.5f * CIRCLE_RADIUS; // spacing between each circle stamp
private static final int FRAMES_PER_SECOND = 30;
private static final int ANIMATION_DURATION = 10000;
private OnMapReadyCallback mMapReadyCallback;
private GoogleMap mGoogleMap;
private LatLng mPointA;
private LatLng mPointB;
private LatLng mPointC;
private float mCirclePhase = 0; // amount to offset before the first circle is stamped
private Path mCircleStampPath;
private Paint mPaintLine;
private final Path mPathFromAtoC = new Path();
private long mStartTime;
private long mElapsedTime;
public EnhancedMapView(#NonNull Context context) {
super(context);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable GoogleMapOptions options) {
super(context, options);
init();
}
#Override
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.save();
drawLineFomAtoB(canvas);
canvas.restore();
// perform one shot animation
mElapsedTime = System.currentTimeMillis() - mStartTime;
if (mElapsedTime < ANIMATION_DURATION) {
postInvalidateDelayed(1000 / FRAMES_PER_SECOND);
}
}
private void drawLineFomAtoB(Canvas canvas) {
if (mGoogleMap == null || mPointA == null || mPointB == null) {
return;
}
// interpolate current position
mPointC = SphericalUtil.interpolate(mPointA, mPointB, (float) mElapsedTime / (float)ANIMATION_DURATION);
final Projection mapProjection = mGoogleMap.getProjection();
final Point pointA = mapProjection.toScreenLocation(mPointA);
final Point pointC = mapProjection.toScreenLocation(mPointC);
mPathFromAtoC.rewind();
mPathFromAtoC.moveTo(pointC.x, pointC.y);
mPathFromAtoC.lineTo(pointA.x, pointA.y);
// change phase for circles shift
mCirclePhase = (mCirclePhase < CIRCLE_ADVANCE)
? mCirclePhase + 1.0f
: 0;
mPaintLine.setPathEffect(new PathDashPathEffect(mCircleStampPath, CIRCLE_ADVANCE, mCirclePhase, PathDashPathEffect.Style.ROTATE));
canvas.drawPath(mPathFromAtoC, mPaintLine);
}
private void init() {
setWillNotDraw(false);
mCircleStampPath = new Path();
mCircleStampPath.addCircle(0,0, CIRCLE_RADIUS, Path.Direction.CCW);
mCircleStampPath.close();
mPaintLine = new Paint();
mPaintLine.setColor(Color.BLACK);
mPaintLine.setStrokeWidth(1);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setPathEffect(new PathDashPathEffect(mCircleStampPath, CIRCLE_ADVANCE, mCirclePhase, PathDashPathEffect.Style.ROTATE));
// start animation
mStartTime = System.currentTimeMillis();
postInvalidate();
}
#Override
public void getMapAsync(OnMapReadyCallback callback) {
mMapReadyCallback = callback;
super.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
invalidate();
}
});
if (mMapReadyCallback != null) {
mMapReadyCallback.onMapReady(googleMap);
}
}
public void setPoints(LatLng pointA, LatLng pointB) {
mPointA = pointA;
mPointB = pointB;
}
}
NB! This is just idea, not full tested code.
Could someone please maybe download and see my project? It is very simple, but not working as in the tutorial.
In my project, I set IsTrigger to true in either the ThirdPersonController or the AIThirdPersonController for one of the characters. This makes the character fall down from the Plane.
I also changed one of the characters to be tagged as Player and changed the state from PATROL to CHASE but that changed nothing. The other player never chases/follows the player I am controlling and moving around.
Why are the players falling down when I set IsTrigger to true in my project?
I see in the video that the instructor is using a Maze Plane. Is that a package I should import in the Assets or is it already somewhere in the Assets? I just added regular Plane for now because I could not find a Maze Plane.
Here is a link for my project from my OneDrive. The file name is Demo AI.rar:
Project in OneDrive
Here is a link for the video tutorial I am attempting to follow. It is supposes to be simple I suppose:
Tutorial
Here is the BasicAi class I'm using in my project, the same script from the tutorial video:
using System.Collections;
using UnityStandardAssets.Characters.ThirdPerson;
public class BasicAi : MonoBehaviour {
public NavMeshAgent agent;
public ThirdPersonCharacter character;
public enum State {
PATROL,
CHASE
}
public State state;
private bool alive;
// Variables for patrolling
public GameObject[] waypoints;
private int waypointInd = 0;
public float patrolSpeed = 0.5f;
// Variable for chasing
public float chaseSpeed = 1f;
public GameObject target;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent> ();
character = GetComponent<ThirdPersonCharacter>();
agent.updatePosition = true;
agent.updateRotation = false;
state = BasicAi.State.PATROL;
alive = true;
StartCoroutine ("FSM");
}
IEnumerator FSM()
{
while (alive)
{
switch (state)
{
case State.PATROL:
Patrol ();
break;
case State.CHASE:
Chase ();
break;
}
yield return null;
}
}
void Patrol()
{
agent.speed = patrolSpeed;
if (Vector3.Distance (this.transform.position, waypoints [waypointInd].transform.position) >= 2) {
agent.SetDestination (waypoints [waypointInd].transform.position);
character.Move (agent.desiredVelocity, false, false);
} else if (Vector3.Distance (this.transform.position, waypoints [waypointInd].transform.position) <= 2) {
waypointInd += 1;
if (waypointInd > waypoints.Length) {
waypointInd = 0;
}
}
else
{
character.Move (Vector3.zero, false, false);
}
}
void Chase()
{
agent.speed = chaseSpeed;
agent.SetDestination (target.transform.position);
character.Move (agent.desiredVelocity, false, false);
}
void OnTriggerEnter(Collider coll)
{
if (coll.tag == "Player")
{
state = BasicAi.State.CHASE;
target = coll.gameObject;
}
}
}
Once a collider is a trigger it no longer collides with objects, your best bet is to place a child object that has a collider and setting that to the trigger, this way the original collider will still collide with your ground.
As for your other question how are you referencing your third person character, are you dragging it from the scene into the inspector, and you also have to bake your navmesh into your scene. I haven't looked at your project as that would take a lot of time, but maybe go through the tutorial again and see how they reference the character. With the inbuilt characters you normally have to access the namespace first.
so quicky, I am doing program which demonstrate methods used for computer graph drawing. I need to create timeline or history of actions like ( placeVertex(x,y), moveVertex(newX,newY) etc. ) and iterate through (forward and backwards, automatically or manual)
I already achieved that by using command design pattern but few of these commands are using transitions. First idea was to use Condition interface's lock, await and signal in setOnFinished between each commands but it led to gui freezing.
I tryed SequentialTransition but it's no use for my problem - can't change properties dynamically between transitions.
Is there a possibility to somehow inform generation that one transition ended and next can run without GUI freezing and drawing?
Thanks!
edit: I ll try to simplify it all
Here is my Command interface and one of these commands:
public interface Command {
public void execute();
}
public class MoveVertex implements Command {
public MoveVertex(Data d, Vertex v, double changedX, double changedY){..};
#Override
public void execute() {
Path path = new Path();
path.getElements().add(new MoveTo(v.getCenterX(), v.getCenterY()));
path.getElements().add(new LineTo(changedX, changedY));
PathTransition pathTransition = new PathTransition();
pathTransition.setDuration(Duration.millis(velocity));
pathTransition.setPath(path);
pathTransition.setNode(v.getVertex());
pathTransition.play(); }
}
These Commands are stored in my history class which is basically
private List<Command> history;
And I do going through the list and executing Commands
public boolean executeNext() {
if (history.size() != position) {
history.get(position).execute();
position++;
return true;
}
return false;
}
And I am trying to achieve state when next Command is started only if previous finished. Tryed to put await/signal in between without success.
The solution below uses Itachi's suggestion of providing an onFinished handler to move to a node to a new (random) location after we get to the next location.
It could probably be made more efficient (and simpler to understand) by re-using a single Transition rather than using recursion within the event handler. It is probably unnecessary to create a new Transition for each movement - but, as long as there aren't hundreds of thousands of movement iterations, it should be acceptable as is.
import javafx.animation.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.geometry.Point2D;
import javafx.scene.*;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.Random;
// animates moving a node forever in a random walk pattern.
public class RandomWalk extends Application {
private static final Random random = new Random(42);
private static final double W = 200;
private static final double H = 200;
private static final double R = 10;
private static final Node node = new Circle(
R, Color.FORESTGREEN
);
#Override
public void start(Stage stage) {
// start from the center of the screen.
node.relocate(W / 2 - R, H / 2 - R);
stage.setScene(new Scene(new Pane(node), W, H));
stage.show();
walk();
}
// start walking from the current position to random points in sequence.
private void walk() {
final Point2D to = getRandomPoint();
final Transition transition = createMovementTransition(
node,
to
);
transition.setOnFinished(
walkFrom(to)
);
transition.play();
}
private EventHandler<ActionEvent> walkFrom(final Point2D from) {
return event -> {
// Finished handler might be called a frame before transition complete,
// leading to glitches if we relocate in the handler.
// The transition works by manipulating translation values,
// so zero the translation out before relocating the node.
node.setTranslateX(0);
node.setTranslateY(0);
// After the transition is complete, move the node to the new location.
// Relocation co-ordinates are adjusted by the circle's radius.
// For a standard node, the R adjustment would be unnecessary
// as most nodes are located at the top left corner of the node
// rather than at the center like a circle is.
node.relocate(
from.getX() - R,
from.getY() - R
);
// Generate the next random point and play a transition to walk to it.
// I'd rather not use recursion here as if you recurse long enough,
// then you will end up with a stack overflow, but I'm not quite sure
// how to do this without recursion.
final Point2D next = getRandomPoint();
final Transition transition = createMovementTransition(node, next);
transition.setOnFinished(walkFrom(next));
transition.play();
};
}
// We use a PathTransition to move from the current position to the next.
// For the simple straight-line movement we are doing,
// a straight TranslateTransition would have been fine.
// A PathTransition is just used to demonstrate that this
// can work for the generic path case, not just straight line movement.
private Transition createMovementTransition(Node node, Point2D to) {
Path path = new Path(
new MoveTo(
0,
0
),
new LineTo(
to.getX() - node.getLayoutX(),
to.getY() - node.getLayoutY()
)
);
return new PathTransition(
Duration.seconds(2),
path,
node
);
}
// #return a random location within a bounding rectangle (0, 0, W, H)
// with a margin of R kept between the point and the bounding rectangle edge.
private Point2D getRandomPoint() {
return new Point2D(
random.nextInt((int) (W - 2*R)) + R,
random.nextInt((int) (H - 2*R)) + R
);
}
public static void main(String[] args) {
launch(args);
}
}
I have got a larger Pane (Parent) to which I have added another smaller Pane (Child). I would like to drag the child Pane without dragging the parent Pane (i.e. register mouse event only on the child and not on the parent).
How can we best implement it?
I managed to find a work around to my problem.
In the Parent Pane: I used mouseEvent.isControlDown()- So I use crtl+mousebutton down to drag the pane.
In the Child Pane: I used !mouseEvent.isControlDown(). So control keystoke is used to determine which part of the event works.
The parent goes like this:
node.addEventFilter(
MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
public void handle(final MouseEvent mouseEvent) {
if (mouseEvent.isControlDown()) {
// remember initial mouse cursor coordinates
// and node position
dragContext.mouseAnchorX = mouseEvent.getSceneX();
dragContext.mouseAnchorY = mouseEvent.getSceneY();
dragContext.initialTranslateX
= node.getTranslateX();
dragContext.initialTranslateY
= node.getTranslateY();
}
}
});
The Child goes like this:
node.addEventFilter(
MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
public void handle(final MouseEvent mouseEvent) {
if (!mouseEvent.isControlDown()) {
dragContext.mouseAnchorX = mouseEvent.getSceneX();
dragContext.mouseAnchorY = mouseEvent.getSceneY();
dragContext.initialTranslateX
= node.getTranslateX();
dragContext.initialTranslateY
= node.getTranslateY();
}
}
});
I am trying to catch the events on the JavaFX Slider especially the one which indicates that the drag stopped and was released. At first I used the valueProperty with mock-up code like this
slider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) {
log.fine(newValue.toString());
}
});
but with this it update too often. So I searched within SceneBuilder and the API and found some interessting like
slider.setOnMouseDragReleased(new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
System.out.println("setOnMouseDragReleased");
}
});
but they never get fired. There only some like setOnMouseReleased I get some output, but this for example count for the whole Node like the labels etc.
So my question is, which is the correct hook to know the value is not changing anymore (if possible after release of the mouse like drag'n'drop gesture) and maybe with a small example to see its interfaces working.
Add a change listener to the slider's valueChangingProperty to know when the slider's value is changing, and take whatever action you want on the value change.
The sample below will log the slider's value when it starts to change and again when it finishes changing.
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class SliderChangeLog extends Application {
private final ListView<String> startLog = new ListView<>();
private final ListView<String> endLog = new ListView<>();
#Override public void start(Stage stage) throws Exception {
Pane logsPane = createLogsPane();
Slider slider = createMonitoredSlider();
VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
layout.getChildren().setAll(
slider,
logsPane
);
VBox.setVgrow(logsPane, Priority.ALWAYS);
stage.setTitle("Slider Value Change Logger");
stage.setScene(new Scene(layout));
stage.show();
}
private Slider createMonitoredSlider() {
final Slider slider = new Slider(0, 1, 0.5);
slider.setMajorTickUnit(0.5);
slider.setMinorTickCount(0);
slider.setShowTickMarks(true);
slider.setShowTickLabels(true);
slider.setMinHeight(Slider.USE_PREF_SIZE);
slider.valueChangingProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(
ObservableValue<? extends Boolean> observableValue,
Boolean wasChanging,
Boolean changing) {
String valueString = String.format("%1$.3f", slider.getValue());
if (changing) {
startLog.getItems().add(
valueString
);
} else {
endLog.getItems().add(
valueString
);
}
}
});
return slider;
}
private HBox createLogsPane() {
HBox logs = new HBox(10);
logs.getChildren().addAll(
createLabeledLog("Start", startLog),
createLabeledLog("End", endLog)
);
return logs;
}
public Pane createLabeledLog(String logName, ListView<String> log) {
Label label = new Label(logName);
label.setLabelFor(log);
VBox logPane = new VBox(5);
logPane.getChildren().setAll(
label,
log
);
logPane.setAlignment(Pos.TOP_LEFT);
return logPane;
}
public static void main(String[] args) { launch(args); }
}
There could be times when you want to know when the user is moving the slider versus the slider value changing due to a binding to a property. One example is a slider that is used on a media player view to show the media timeline. The slider not only displays the time but also allows the user to fast forward or rewind. The slider is bound to the media player's current time which fires the change value on the slider. If the user moves the slider, you may want to detect the drag so as to stop the media player, have the media player seek to the new time and resume playing. Unfortunately the only drag event that seems to fire on the slider is the setOnDragDetected event. So I used the following two methods to check for a slider drag.
slider.setOnDragDetected(new EventHandler<Event>() {
#Override
public void handle(Event event) {
currentPlayer.pause();
isDragged=true;
}
});
slider.setOnMouseReleased(new EventHandler<Event>() {
#Override
public void handle(Event event) {
if(isDragged){
currentPlayer.seek(Duration.seconds((double) slider.getValue()));
currentPlayer.play();
isDragged=false;
}
}
});
jewelsea's answer was very helpful for setting me on the right track, however if "snapToTicks" is on, undesired behavior results. The "end" value as captured by jewelsea's listener is before the snap takes place, and the post-snap value is never captured.
My solution sets a listener on value but uses valueChanging as a sentinel. Something like:
slider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(
ObservableValue<? extends Number> observableValue,
Number previous,
Number now) {
if (!slider.isValueChanging()
|| now.doubleValue() == slider.getMax()
|| now.doubleValue() == slider.getMin()) {
// This only fires when we're done
// or when the slider is dragged to its max/min.
}
}
});
I found that checking for the max and min value was necessary to catch the corner case where the user drags the slider all the way past its left or right bounds before letting go of the mouse. For some reason, that doesn't fire an event like I'd expect, so this seems like an okay work-around.
Note: Unlike jewelsea, I'm ignoring the starting value for the sake of simplicity.
Note 2: I'm actually using ScalaFX 2, so I'm not sure if this Java translation compiles as-written.