Add penalty to previous path on point graph to prevent u-turns? A* Pathfinding Project - graph

I am using Aron Granberg's A* Pathfinding Project. So I have a point graph set up in this picture:
I have each car choosing a random node on the point graph and following a path to it.
Right now, the cars traveling on the road have a tendency to make u-turns to get to their next destination. For example, suppose the original path was from point A to point B. Once the car reaches point B, it then randomly chooses to travel to point C.
Is there any way where I can force it to always take the yellow path instead of the purple path to prevent u-turns? I was thinking something along the lines of setting penalties for the previous path, but the penalties would have to only apply to a single agent as I don't want the penalties to apply to the other cars on the road. Is there a feasible way to do this? I have included my pathfinding code below.
using UnityEngine;
using System.Collections;
using System.Linq;
//Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors
//This line should always be present at the top of scripts which use %Pathfinding
using Pathfinding;
public class newPathfind : MonoBehaviour {
//The point to move to
private Vector3 targetPosition;
private bool pathComplete;
public bool ManualList = false;
//public int members = 0;
//private int x = 0;
public GameObject target1;
public GameObject target2;
public GameObject target3;
public GameObject target4;
public GameObject target5;
private GameObject[] Waypoints;
private GameObject[] oneway;
private GameObject[] twoway;
public static int randomPoint;
private Seeker seeker;
private CharacterController controller;
//The calculated path
public Path path;
//The AI's speed per second
public float speed = 500;
//The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 3;
//The waypoint we are currently moving towards
private int currentWaypoint = 0;
public void Start () {
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
Vector3 randomLoc = Vector3.zero;
if (ManualList) {
Waypoints = new GameObject[5];
Waypoints[0] = target1;
Waypoints[1] = target2;
Waypoints[2] = target3;
Waypoints[3] = target4;
Waypoints[4] = target5;
} else {
//Waypoints = GameObject.FindGameObjectsWithTag("network");
twoway = GameObject.FindGameObjectsWithTag ("network");
oneway = GameObject.FindGameObjectsWithTag ("oneway");
Waypoints = oneway.Concat (twoway).ToArray ();
}
do {
randomPoint = Random.Range (0, Waypoints.Length-1);
randomLoc = Waypoints[randomPoint].transform.position;
targetPosition = new Vector3 (randomLoc.x, gameObject.transform.position.y, randomLoc.z);
} while ((Vector3.Distance(gameObject.transform.position, targetPosition) < 50f));
//Start a new path to the targetPosition, return the result to the OnPathComplete function
seeker.StartPath (transform.position,targetPosition, OnPathComplete);
}
public void OnPathComplete (Path p) {
Debug.Log ("Yey, we got a path back. Did it have an error? "+p.error);
if (!p.error) {
path = p;
//Reset the waypoint counter
currentWaypoint = 0;
pathComplete = true;
}
}
public void FixedUpdate () {
if (path == null) {
return;
}
if (currentWaypoint >= path.vectorPath.Count && pathComplete == true) {
Debug.Log ("End Of Path Reached");
Start();
pathComplete = false;
return;
}
//Direction to the next waypoint
Vector3 dir = Vector3.zero;
if (currentWaypoint >= 0 && currentWaypoint < path.vectorPath.Count) {
dir = (path.vectorPath [currentWaypoint] - transform.position).normalized;
}
if (dir != Vector3.zero) {
transform.rotation = Quaternion.LookRotation (dir);
}
dir *= speed * Time.fixedDeltaTime;
controller.SimpleMove (dir);
//Check if we are close enough to the next waypoint
//If we are, proceed to follow the next waypoint
if (Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance) {
currentWaypoint++;
return;
}
}
public void OnDisable () {
seeker.pathCallback -= OnPathComplete;
}
}

I couldn't find how to do this using Aron Granberg's A* Pathfinding Project, but essentially you'll need to change the cost of the last visited node to maybe about 3-5 times its normal cost (would probably need experimenting) before calling seeker.StartPath again.
I would assume that the pathfinder has some way of asking you what the cost for each node is. If the node is the same as the last node the unit visited, you would return a multiple of its actual cost. Of course, you will need to know for which unit it is pathing for.
Closest thing I could find (knowing nothing about the library) was GraphUpdates where you are able to apply penalties to various nodes:
GraphUpdateObject guo = new GraphUpdateObject(myBounds);
guo.addPenalty = 10000; //Here goes the penalty to apply, you need quite large values usually
AstarPath.active.UpdateGraphs (guo);
Not sure how you would tie this with a unit other than updating the graph before calling the seeker for a particular unit and making sure nobody else calls the seeker until that's done (very inefficient).

Difficult question... One thing you could do (for a car already traveling) is evaluate a straight line on the path of the car to the next intersection. That would be the next logical time that the driver would make a decision to recalculate their path. Doing it this way would tell the car to continue using the seeker until it found the starting node of the path (in this case it would drastically reduce your u-turn behavior) which happens to be at the next intersection making your hypothetical much less likely and closer mimick driving behavior.
Also on busy roads you may want to consider using the filter called alternative path... If you add this to your existing car prefab, you can create a penalty for too many other units taking the same path. If you set it to ...say 100, unless it was the only realistic path, after 10 cars took the same path likely you would have cars taking alternate routes
Just my two cents
My edited two cents, adding weights to roads, unless it is the entirety of the road (ie dirt vs. pavement) isnt going to be too feasible. Unless I have missed something in the docs (let me know if I did because I want to use it) you are unable to get the weight for a given node/waypoint.You can however choose between different paths with different penalties. (IE you cant do path.vectorPath[currentWaypoint].weight, but you can do path.GetTagPenalty and choose an alternate path)

Angle Penalty in the "Advanced" section may help here.

Related

Calculating bank angle between two objects

I have a drone following a path for movement. That is, it doesn't use a rigidbody so I don't have access to velocity or magnitude and such. It follows the path just fine, but I would like to add banking to it when it turns left or right. I use a dummy object in front of the drone, thinking I could calculate the bank/tilt amount using the transform vectors from the two objects.
I've been working on this for days as I don't have a lot of math skills. Basically I've been copying pieces of code trying to get things to work. Nothing I do works to make the drone bank. The following code manages to spin (not bank).
// Update is called once per frame
void Update () {
Quaternion rotation = Quaternion.identity;
Vector3 dir = (dummyObject.transform.position - this.transform.position).normalized;
float angle = Vector3.Angle( dir, transform.up );
float rollAngle = CalculateRollAngle(angle);
rotation.SetLookRotation(dir, transform.right);// + rollIntensity * smoothRoll * right);
rotation *= Quaternion.Euler(new Vector3(0, 0, rollAngle));
transform.rotation = rotation;
}
/// <summary>
/// Calculates Roll and smoothes it (to compensates for non C2 continuous control points algorithm) /// </summary>
/// <returns>The roll angle.</returns>
/// <param name="rollFactor">Roll factor.</param>
float CalculateRollAngle(float rollFactor)
{
smoothRoll = Mathf.Lerp(smoothRoll, rollFactor, rollSmoothing * Time.deltaTime);
float angle = Mathf.Atan2(1, smoothRoll * rollIntensity);
angle *= Mathf.Rad2Deg;
angle -= 90;
TurnRollAngle = angle;
angle += RollOffset;
return angle;
}
Assuming you have waypoints the drone is following, you should figure out the angle between the last two (i.e. your "now-facing" and "will be facing" directions). The easy way is to use Vector2.Angle.
I would use this angle to determine the amount I'll tilt the drone's body: the sharper the turn, the harder the banking. I would use a ratio value (public initially so I can manipulate it from the editor).
Next, instead of doing any math I would rely on the engine to do the rotation for me - so I would go for Transform.Rotate function.In case banking can go too high and look silly, I would set a maximum for that and Clamp my calculated banking angle between zero and max.
Without knowing exactly what you do and how, it's not easy to give perfect code, but for a better understand of the above, here's some (untested, i.e. pseudo) code for the solution I visualize:
public float turnSpeed = 7.0f; //the drone will "rotate toward the new waypoint" by this speed
//bankSpeed+turnBankRatio must be two times "faster" (and/or smaller degree) than turning, see details in 'EDIT' as of why:
public float bankSpeed = 14.0f; //banking speed
public float turnBankRatio = .5f; //90 degree turn == 45 degree banking
private float turnAngle = 0.0f; //this is the 'x' degree turning angle we'll "Lerp"
private float turnAngleABS = 0.0f; //same as turnAngle but it's an absolute value. Storing to avoid Mathf.Abs() in Update()!
private float bankAngle = 0.0f; //banking degree
private bool isTurning = false; //are we turning right now?
//when the action is fired for the drone it should go for the next waypoint, call this guy
private void TurningTrigger() {
//remove this line after testing, it's some extra safety
if (isTurning) { Debug.LogError("oups! must not be possible!"); return; }
Vector2 droneOLD2DAngle = GetGO2DPos(transform.position);
//do the code you do for the turning/rotation of drone here!
//or use the next waypoint's .position as the new angle if you are OK
//with the snippet doing the turning for you along with banking. then:
Vector2 droneNEW2DAngle = GetGO2DPos(transform.position);
turnAngle = Vector2.Angle(droneOLD2DAngle, droneNEW2DAngle); //turn degree
turnAngleABS = Mathf.Abs(turnAngle); //avoiding Mathf.Abs() in Update()
bankAngle = turnAngle * turnBankRatio; //bank angle
//you can remove this after testing. This is to make sure banking can
//do a full run before the drone hits the next waypoint!
if ((turnAngle * turnSpeed) < (bankAngle * bankSpeed)) {
Debug.LogError("Banking degree too high, or banking speed too low to complete maneuver!");
}
//you can clamp or set turnAngle based on a min/max here
isTurning = true; //all values were set, turning and banking can start!
}
//get 2D position of a GO (simplified)
private Vector2 GetGO2DPos(Vector3 worldPos) {
return new Vector2(worldPos.x, worldPos.z);
}
private void Update() {
if (isTurning) {
//assuming the drone is banking to the "side" and "side" only
transform.Rotate(0, 0, bankAngle * time.deltaTime * bankSpeed, Space.Self); //banking
//if the drone is facing the next waypoint already, set
//isTurning to false
} else if (turnAngleABS > 0.0f) {
//reset back to original position (with same speed as above)
//at least "normal speed" is a must, otherwise drone might hit the
//next waypoint before the banking reset can finish!
float bankAngle_delta = bankAngle * time.deltaTime * bankSpeed;
transform.Rotate(0, 0, -1 * bankAngle_delta, Space.Self);
turnAngleABS -= (bankAngle_delta > 0.0f) &#63 bankAngle_delta : -1 * bankAngle_delta;
}
//the banking was probably not set back to exactly 0, as time.deltaTime
//is not a fixed value. if this happened and looks ugly, reset
//drone's "z" to Quaternion.identity.z. if it also looks ugly,
//you need to test if you don't """over bank""" in the above code
//by comparing bankAngle_delta + 'calculated banking angle' against
//the identity.z value, and reset bankAngle_delta if it's too high/low.
//when you are done, your turning animation is over, so:
}
Again, this code might not perfectly fit your needs (or compile :P), so focus on the idea and the approach, not the code itself. Sorry for not being able right now to put something together and test myself - but I hope I helped. Cheers!
EDIT: Instead of a wall of text I tried to answer your question in code (still not perfect, but goal is not doing the job, but to help with some snippets and ideas :)
So. Basically, what you have is a distance and "angle" between two waypoints. This distance and your drone's flight/walk/whatever speed (which I don't know) is the maximum amount of time available for:
1. Turning, so the drone will face in the new direction
2. Banking to the side, and back to zero/"normal"
As there's two times more action on banking side, it either has to be done faster (bankSpeed), or in a smaller angle (turnBankRatio), or both, depending on what looks nice and feels real, what your preference is, etc. So it's 100% subjective. It's also your call if the drone turns+banks quickly and approaches toward the next waypoint, or does things in slow pace and turns just a little if has a lot of time/distance and does things fast only if it has to.
As of isTurning:
You set it to true when the drone reached a waypoint and heads out to the next one AND the variables to (turn and) bank were set properly. When you set it to false? It's up to you, but the goal is to do so when the maneuver is finished (this was buggy in the snippet the first time as this "optimal status" was not possible to ever be reached) so he drone can "reset banking".For further details on what's going on, see code comments.Again, this is just a snippet to support you with a possible solution for your problem. Give it some time and understand what's going on. It really is easy, you just need some time to cope ;)Hope this helps! Enjoy and cheers! :)

Minimum number of jumps required to climb stairs

I recently had an interview with Microsoft for an internship and I was asked this question in the interview.
Its basically like, you have 2 parallel staircases and both the staircases have n steps. You start from the bottom and you may move upwards on either of the staircases. Each step on the staircase has a penalty attached to it.
You can also move across both the staircases with some other penalty.
I had to find the minimum penalty that will be imposed for reaching the top.
I tried writing a recurrence relation but I couldn't write anything because of so many variables.
I recently read about dynamic programming and I think this question is related to that.
With some googling, I found that this question is the same as
https://www.hackerrank.com/contests/frost-byte-final/challenges/stairway
Can you please give a solution or an approach for this problem ?
Create two arrays to keep track of the minimal cost to reach every position. Fill both arrays with huge numbers (e.g. 1000000000) and the start of the arrays with the cost of the first step.
Then iterate over all possible steps, and use an inner loop to iterate over all possible jumps.
foreach step in (0, N) {
// we're now sure we know minimal cost to reach this step
foreach jump in (1,K) {
// updating minimal costs here
}
}
Now every time we reach updating there are 4 possible moves to consider:
from A[step] to A[step+jump]
from A[step] to B[step+jump]
from B[step] to A[step+jump]
from B[step] to B[step+jump]
For each of these moves you need to compute the cost. Because you already know that you have the optimal cost to reach A[step] and B[step] this is easy. It's not guaranteed this new move is an improvement, so only update the target cost in your array if the new cost is lower then the cost already there.
Isn't this just a directed graph search? Any kind of simple pathfinding algorithm could handle this. See
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
https://en.wikipedia.org/wiki/A*_search_algorithm
Just make sure you enforce the directional of the stairs (up only) and account for penalties (edge weights).
Worked solution
Of course, you could do it with dynamic programming, but I wouldn't be the one to ask for that...
import java.io.;
import java.util.;
public class Main {
public static int csmj(int []a,int src,int[] dp){
if(src>=a.length){
return Integer.MAX_VALUE-1;
}
if(src==a.length-1){
return 0;
}
if(dp[src]!=0){
return dp[src];
}
int count=Integer.MAX_VALUE-1;
for(int i=1;i<=a[src];i++){
count = Math.min( count , csmj(a,src+i,dp)+1 );
}
dp[src] = count;
return count;
}
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i] = s.nextInt();
}
int minJumps = csmj(a,0,new int[n]);
System.out.println(minJumps);
}
}
bro you can have look at that solution my intuition is that

Map a Matrix to a Circular Frame Image

I have a matrix and o want to map it to a circular frame. Each element in matrix should be mapped to a predefined position on the circular frame. What i am really do is dealing with the human brain signals recorded from different electrodes installed over the skull. This is the final plot i want to get:
http://www.ihr.mrc.ac.uk/img/research/2009/3/scan-banner.jpg
Any Sugestion?
Please, correct me if I'm wrong. I don't know what kind of data these electrodes are able to retrieve, but in any case, I think you can view them in two different natures: first, sampled data (a class that encapsulates all information gathered through one specific electrode) and second, a geographically mapping object, binding the data from each electrode to one specific location.
As for the first part, you can design whatever class you wish, according to your needs. This class may have but a single double value (like intensity or electric level, or whatever) or a complete set of variables or even other classes arranged in such a way that represent what you need.
As for the second part, as you want to map the data retrieved from each electrode into a pre-determined point in a circular area, I think a class having an horizontal and a vertical positioning value is good. This can be a java.awt.Point (which can map to the real X and Y position of the point you wish) or a custom class (non-related to any domain) with the two X and Y variables, that can translate to a real X and Y coordinate in the final image.
Something like that
public class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
and
public class Sample {
private double electricalLevel;
private Position position;
public double getElectricalLevel() {
return electricalLevel;
}
public void setElectricalLevel(double electricalLevel) {
this.electricalLevel = electricalLevel;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
Something like that.
Then you'll have to instantiate each Sample, map it to a Position instance and keep updating the values.
As for the mapping to the correct Position, you can have all the positions pre-calculated and entered as literals, or calculated from a positioning function. I think the pre-calculated positions are ok, as they are not prone to changing...
Then you'll have something like:
Sample s1 = new Sample();
s1.setPosition(new Position(100, 100));
Sample s2 = new Sample();
s2.setPosition(new Position(150, 80));
and so on, for each electrode.
As for the drawing itself, you'll have to dig into java imaging. This will not be so simple, because you're not really only plotting the points themselves. Actually, the colour of each point and its surrounding area will be a function of the sampled data, if I'm correct, as the colour seems to be reflecting the sampled data from that brain region.
To make things worse, the boundary areas between multiple points will influence each other, so that a colour gradient will be generated.
I suggest you first focus in the given scenario and that you ask about the painting and java imaging issue in other question.
Sorry, this is a really general answer, but it's as far as I can go with many assumptions and without knowing what exactly you're dealing with. I hope it helps, though.

Collision Detection and maintaining momentum on an object

I have been implementing various forms of simple collision detection with varying results. I have a fairly good working version of collision detection, but there are some odd behaviors that I can't work out.
Just for a reference, i'm making a simple pong game, and trying to refine the collision. The problems I get are when the ball collides with the paddle on either the top or bottom side. In those cases, the ball hovers above (or below) the paddle and does not move. I'm guessing this is because of how i'm checking for collision and how i'm altering the movespeed of the ball.
I would like to implement a way I differentiate between top/bottom and left/right collision but this is the only method that works decently:
static void CheckCollision(PActor object1, PActor object2, PInput pinput)
{
if ( CheckObjectCollision( object1, object2 ) )
{
AdjustMoveSpeed( object1, object2, pinput );
}
}
static bool CheckObjectCollision(PActor object1, PActor object2)
{
int object1LeftBound = object1.position.x;
int object1RightBound = object1.position.x + object1.actorTextureXSize;
int object1TopBound = object1.position.y;
int object1BottomBound = object1.position.y + object1.actorTextureYSize;
int object2LeftBound = object2.position.x;
int object2RightBound = object2.position.x + object1.actorTextureXSize;
int object2TopBound = object2.position.y;
int object2BottomBound = object2.position.y + object2.actorTextureYSize;
if ( object1RightBound < object2LeftBound )
return false;
if ( object1LeftBound > object2RightBound )
return false;
if ( object1BottomBound < object2TopBound )
return false;
if ( object1TopBound > object2BottomBound )
return false;
return true;
}
I am guessing that the root of some of the problems i'm having is the function AdjustMoveSpeed, here it is:
static void AdjustMoveSpeed(PActor object1, PActor object2, PInput pinput)
{
PVector prevMouseLocation = pinput.GetPrevMouseLocation();
PVector currMouseLocation = pinput.GetCurrMouseLocation();
int currentMoveSpeed;
int nextMoveSpeed;
if (typeid(object1) == typeid(PBall))
{
object1.moveSpeed.x *= -1;
if ( typeid(object2) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object1.moveSpeed.y > 0)
object1.moveSpeed.y *= -1;
}
}
else if (typeid(object2) == typeid(PBall))
{
object2.moveSpeed.x *= -1;
if ( typeid(object1) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object2.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object2.moveSpeed.y > 0)
object2.moveSpeed.y *= -1;
}
}
}
What I was attempting to do with AdjustMoveSpeed, is first check to see which object is the ball, after this, multiply the x move speed by -1 to reverse its direction. After this, I check to see if the other object is a player, if so I set the y move speed to the difference between the previous mouse location and current mouse location. This is here to give the player option to change the balls y speed, or add spin.
I've tried checking for intersection between objects so that I can get a specific side, and the result is the ball just flying in the middle of the screen without actually hitting either paddle.
How do I properly check for collision detection on two objects that are squares?
How can I fix AdjustMoveSpeed so that it works properly with collision detection?
Lastly, how do I keep the momentum of the ball of its current speed is greater than the difference of the mouse location before and after the hit?
I've tried taking comparing the absolute value of currentMoveSpeed and nextMoveSpeed but then the ball doesn't change y speed. Something like this:
if ( abs(currentMoveSpeed) < abs(nextMoveSpeed )
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
else
object1.moveSpeed.y *= -1
Pong is simple enough that, rather than moving the ball each frame and checking for a collision with a paddle, you can actually solve the equation for when the paddle and ball will collide - if that time is less than one frame, there is a collision.
This completely eliminates the issue of the ball moving so fast it moves through the paddle, an issue that plagues many pong-clones that use the naive method of collision-detection.
This solution is called continuous collision detection - see this answer for more information.
If the ball gets stuck on the paddle instead of bouncing it is probably because it keeps changing direction back and forth. The ball should only bounce if it is heading towards the paddle.
if (sgn(object1.moveSpeed.x) == sgn(object1.x - object2.x)) {
// Ball is already moving away from the paddle, don't bounce!
}
else {
// Ok to bounce!
object1.moveSpeed.x *= -1;
}

Move an object along waypoints in 2D

I created this function to move a unit along way points that are saved in list_. Every Unit has its own list_. move() is initially called with the speed (distance/step) every step. Then depending on the distance to the next way point three possible actions are taken.
Can you suggest any improvements?
void Unit::move(qreal maxDistance)
{
// Construct a line that goes from current position to next waypoint
QLineF line = QLineF(pos(), list_.firstElement().toPointF());
// Calculate the part of this line that can be "walked" during this step.
qreal part = maxDistance / line.length();
// This step's distance is exactly the distance to next waypoint.
if (part == 1) {
moveBy(line.dx(), line.dy());
path_.removeFirst();
}
// This step's distance is bigger than the distance to the next waypoint.
// So we can continue from next waypoint in this step.
else if (part > 1)
{
moveBy(line.dx() , line.dy());
path_.removeFirst();
if (!path_.isEmpty())
{
move(maxDistance - line.length());
}
}
// This step's distance is not enough to reach next waypoint.
// Walk the appropriate part of the length.
else /* part < 1 */
{
moveBy(line.dx() * part, line.dy() * part);
}
}
I'll hate myself for suggesting a deprecated way of doing things, but there's no reference to the replacing method :(
QGraphicsItemAnimation
It has addStep and linear interpolation stuff as a convenience.
It seems Qt devs would like you to use QTimeLine itself as a replacement.
I'd use Qt Animation Framework, more precisely QPropertyAnimation:
// I use QPainterPath to calculate the % of whole route at each waypoint.
QVector<qreal> lengths;
QPainterPath path;
path.moveTo(list_.first());
lengths.append(0);
foreach (const QPointF &waypoint, list_.mid(1)) {
path.lineTo(waypoint);
lengths.append(path.length());
}
// KeyValues is typedef for QVector< QPair<qreal, QVariant> >
KeyValues animationKeyValues;
for (int i(0); i != lenghts.count(); ++i) {
animationKeyValues.append(qMakePair(path.percentAtLength(lenghts.at(i)), list_.at(i)));
}
// I assume unit is a pointer to a QObject deriving Unit instance and that
// Unit has QPointF "position" property
QPropertyAnimation unitAnimation(unit, "position");
unitAnimation.setKeyValues(animationKeyValues);
unitAnimation.setDuration(/* enter desired number here */);
unitAnimation.start();
I haven't tested this solution, but you should get the general idea.

Resources