Android TranslationAnimation not working correctly - android

I am trying to animate cards across the screen.
My code looks like this:
private void animate(ImageView animationSource, ImageView animationTarget, int animationDuration, int animationDelay) {
int[] animationSourcePosition = {0,0};
int[] animationTargetPosition = {0,0};
animationSource.getLocationInWindow(animationSourcePosition);
animationTarget.getLocationInWindow(animationTargetPosition);
TranslateAnimation cardDealingAnimation = new TranslateAnimation(
Animation.ABSOLUTE,animationSourcePosition[0],
Animation.ABSOLUTE,animationTargetPosition[0],
Animation.ABSOLUTE,animationSourcePosition[1],
Animation.ABSOLUTE,animationTargetPosition[1]);
cardDealingAnimation.setDuration(animationDuration);
cardDealingAnimation.setStartOffset(animationDelay);
animationTarget.startAnimation(cardDealingAnimation);
}
What happens is that it just pops up in the new place without showing the places in-between.
Funnily enough, on one of my targets it does sometimes show up.

There are two problems I see here.
One problem is that you're getting the position of your objects in the Window, where you should just use the position of the objects in their parent container. It's easier, faster, and more what you're looking for - where the objects live in their layout. If they do not live in the same container, then you may need to get the position in the window or the screen, and then just deal with delta values (the difference in their locations, not the absolute locations themselves).
You can get these simple container positions from the getLeft() and getTop() methods on View.
The second problem is that the TranslateAnimation parameters don't do what you think they do. The numeric values (the second, fourth, sixth, and eighth values) specify the starting and ending locations of the target object as offsets from its current location. That's why they have the word 'delta' in them in the method declaration. So you should not send in the absolute coordinates of the object positions their, but, rather, the deltas that they should have.
Let's suppose you have calculated an xDelta and yDelta as the difference in x and y between the source and target positions. If you're animating the source to the target position, then you would use something like 0, xDelta, 0, yDelta for these values.
Note that TranslateAnimation() does not physically move the object - it just draws it in a different place. So as soon as the animation is complete, the object will snap back to its original location. You may want to set the fillAfter property to maintain its end location on the screen when the animation completes.

Related

Simultaneously move six points in circular paths around their own orbital centers

Suppose I have six points drawn in a Canvas along the circumference of a circle, in the pattern of a hexagon.
I want to simultaneously move and re-draw each of these six points in a small circular path - for example, each point moves along the circumference of a circle with 1/10th the radius of the larger circle.
I'm a little lost on how to do this with Canvas and onDraw and I don't know if better solutions exist. How would you do this?
Some answers have at least pointed me toward this which shows how a point might move along a circular path, but I don't know how to implement it for this situation:
for (double t = 0; t < 2*Pi; t += 0.01)
{
x = R*cos(t) + x_0;
y = R*sin(t) + y_0;
}
Thank you!
Here's one approach:
Start with a custom view that extends View and overrides onDraw. You are on the right track with using the drawing functions of Canvas.
Give your custom view a field to hold the current angle:
private float mTheta;
Then add a method like:
public void setTheta(float radians) {
mTheta = radians;
invalidate();
}
Then in onDraw, use the current value of mTheta to calculate the position of your points.
Of course, with the custom view you might need to handle sizing with an onMeasure override and possibly some layout with an onLayout override. If you set the dimensions of the view to an absolute dp value, the default behavior should work for you.
Doing it this way will set you up to override onTouch and allow user interaction to move the graphics, or use a ValueAnimator to cycle from 0 to 2π calling setTheta from within your AnimatorUpdateListener.
Put some code together and when you get stuck, post another question. If you add a comment to this answer with a link to the new question, I'll take a look at it.

how to make coordinates relative to a canvas

I have a 600x1000 pixel screen and my player starts near the bottom left. His x and y coordinates are (50, 900). I'm drawing this player to a canvas and using
canvas.translate(-player.getX()+GAMEWIDTH/2, 0)
to make sure the player stays in the middle of the screen with respect to the x-axis. This results in my player being rendered at (300, 900), however the player's x and y coordinates remain at (50, 900). This presents an issue because I need the player's coordinates to be the same as his rendered location because I use touch events on the player's collision rectangles to move him around. Is there any way to make my screen's coordinates be relative to my canvas coordinates so that my player's coordinates correspond to where they actually get rendered? Or is there maybe another way to do it?
The touchEvents are always based on the the x & y relative to the canvas element itself. Since the view is centering the character by translating the view canvas.translate(-player.getX() + GAMEWIDTH/2 , 0); you need to also apply that translation to the touchEvent. You can do it in the touch handler itself, or you could store both a relative and absolute position for the items in your game world. This will become more important if items become nested in one another. This is typically done by storing the parent element of a sprite/object.
//example of how I usually handle object hierarchy
this._x = this.x + this.parent._x;
this._y = this.y + this.parent._y;
the canvas/stage would also store it's center as a ._x and ._y which would be the parent of the the objects added, this way when you generate the global position to do your touchEvents against instead of passing in the .x or .y you would pass in the ._x and ._y which are already translated by the GAMEWIDTH/2.

Determining translationX/Y values for ObjectAnimator; how to move a view to an exact screen position?

I'm trying to move a view to the upper right corner of the screen, using ObjectAnimator.ofFloat(...) But, I'm not getting the results I expect. I'm getting the coordinates of the view beforehand, using ViewTreeListener, etc, and I already know the x value I need to offset from the end of the overall width. I can't get either dimension to move to where I want it. Relevant code:
Getting the starting coordinate; where the view currently is:
int[] userCoords = new int[]{0,0};
userControlLayout.getLocationInWindow(userCoords);
//also tried getLocationInScreen(userCoords); same result
userUpLeft = userCoords[0];
userUpTop = userCoords[1];
Surprisingly, I get the same value as userUpLeft (which is in screen coordinates, and not relative to parent) when I call userControlLayout.getLeft() I'd expect them to be different per my understanding of the docs. Anyway...
Constructing the ObjectAnimators:
//testXTranslate is a magic number of 390 that works; arrived at by trial. no idea why that
// value puts the view where I want it; can't find any correlation between the dimension
// and measurements I've got
ObjectAnimator translateX = ObjectAnimator.ofFloat(userControlLayout, "translationX",
testXTranslate);
//again, using another magic number of -410f puts me at the Y I want, but again, no idea //why; currently trying the two argument call, which I understand is from...to
//if userUpTop was derived using screen coordinates, then isn't it logical to assume that -//userUpTop would result in moving to Y 0, which is what I want? Doesn't happen
ObjectAnimator translateY = ObjectAnimator.ofFloat(userControlLayout, "translationY",
userUpTop, -(userUpTop));
My understanding is that the one arg call is equivalent to specifying the end coordinate you want to translate/move to, and the two arg version is starting at...ending at, or, from...to I've messed around with both and can't get there.
Clearly, I'm missing very fundamental knowledge, just trying to figure out what exactly that is. Any guidance much appreciated. Thanks.
First, userControlLayout.getLeft() is relative to the parent view. If this parent is aligned to the left edge of the screen, those values will match. For getTop() it's generally different simply because getLocationInWindow() returns absolute coordinates, which means that y = 0 is the very top left of the window -- i.e. behind the action bar.
Generally you want to translate the control relative to its parent (since it won't even be drawn if it moves outside those bounds). So supposing you want to position the control at (targetX, targetY), you should use:
int deltaX = targetX - button.getLeft();
int deltaY = targetY - button.getTop();
ObjectAnimator translateX = ObjectAnimator.ofFloat(button, "translationX", deltaX);
ObjectAnimator translateY = ObjectAnimator.ofFloat(button, "translationY", deltaY);
When you supply multiple values to an ObjectAnimator, you're indicating intermediate values in the animation. So in your case userUpTop, -userUpTop would cause the translation to go down first and then up. Remember that translation (as well as rotation and all the other transformations) is always relative to the original position.

How do i animate an image in android so it follows a path made of several coordinate?

I found out that the movement of an image between two point can be achieved with this simple code:
ImageView image_to_move = (ImageView) findViewById(R.id.image_to_move);
TranslateAnimation animation = new TranslateAnimation(50, 100, 50, 100);
animation.setDuration(5000);
image_to_move.startAnimation(animation);
The image is an ImageView set initially in position (0,0) inside a FrameLayout and the code move it from the point (50,50) to (100,100).
What if i have to move it on a path, made of several point, in the form of absolute coordinate (x,y)? For example, move from (50,50) to (75,75) then to (100,100)
There's a way to pass to the translating function an array of coordinate or i have simply to iterate the animation for every couple of points?
Btw, i saw that if i don't initially locate the image in (0,0) the function moves the image in a weird way, like the coordinate i give are not read as absolute. Am i missing something?
EDIT: The last thing happens when i pass as parameters to the TranslateAnimation something like "n92.getX()" where n92 is a button on my frame layout, from which position i want the animation to start.
DETAIL: Just to understand better the problem: I am implementing the animation of a point moving on a map, to show the user how to get from one point to another of a map. That's why i have absolute coordinate (the reachable points) that must be followed (you can't arrive from one point to another without following a precise path on the map)
to do so you need to Calculate the position on a quadratic bezier curve. try this answer it might be work for you

How to explain the Coordinate system on Android animation?

As we know , the android coordinate system is start from the top left corner of the android screen. The x-axis is down growth and the y-axis is right growth.But I found it's not right for the animation.
For example, I initialized the TranslateAnimation using the constructed function:
TranslateAnimation ta = new TranslateAnimation(0.0f, 200, 0.0f, 200);
Does the coordinate system have changed ? I found it didn't start from the top left corner.
Then I initialized the other translateAnimation for moving up and right direction :
TranslateAnimation ta = new TranslateAnimation(0.0f, 200, 0.0f, -200);
ta.setReaptMode(Animation.REVERSE);
The same behavior would be found.
I am confused about it.
I believe that constructor for TranslateAnimation uses deltas. See this. Or look at the constructor sig. : (float fromXDelta, float toXDelta, float fromYDelta, float toYDelta). So if you want your anim. to jump up first, you could use a negative third ctor param.
More precisely:
An animation can never start until after the layout has been measured. One usually shouldn't have to worry about how this works beyond that the algorithm is mostly very good and you can take control of its strategies by setting layout parameters. In short, by the time an animation might be started, we know where you want the view to be on the screen, because you set layout parameters.
Translate animation then takes deltas from that position. So your current animation shouldn't start from the top left, but rather wherever those layout params were evaluated by onMeasure.
Some would say- how annoying. It's gonna get complicated even if you just want to do some simple up-down type animations... Well, here's an advisable development strategy; it snould make android animation development a breeeze. Set an animationListener on every animation. In onAnimationEnd, in possibly a parametized way, reset the layout parameters on the view your animating to where you expect it to be. That way, you'll get no surprising "jumps" when you re-apply an animation again. You may need to invalidate in some circumstances, or clearAnimation. The reason that this works is that the measure pass will be caused to come round again and you'll have a new offset for your TranslateAnimation. Finally, you may want to do all this resetting posted to the message queue of a view using post(Runnable runnable) in the listener, so you're off the last pass of the animation draw.
I too found android Animations can occasionally surprise you and cause jumpy behaviour. But if you do it like this, constructors taking delta params shouldn't be confusing again.

Categories

Resources