Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android using animation to make an object fall towards the ground using gravity

I am new to Android development and I am trying to create an image at the top of the screen and make it fall to the bottom. I have been looking around and cannot get a straight answer or pointer in the correct direction. A lot of the examples I am finding are out of date and many of the methods don't work any more.

I have an image in my drawable folder that I would like to create after 10 seconds and have it fall towards the ground like it has gravity.

I have seen a lot about ObjectAnimator, canvas, velocity, animation. I am not sure where to start.

like image 442
L1ghtk3ira Avatar asked Jan 25 '16 04:01

L1ghtk3ira


1 Answers

Be sure to check out the ViewPropertyAnimator class and its methods. For acceleration and bouncing etc. there are so called Interpolators, to make Animations more lifelike / realistic. The simplest way I can think of would be something like this :

Lets say you have a RelativeLayout as Parent and an ImageView as a child in a xml file like this :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/your_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

Then start the Animation like this in your Java Code :

ImageView imageView = (ImageView) findViewById(R.id.your_image);

float bottomOfScreen = getResources().getDisplayMetrics()
    .heightPixels - (imageView.getHeight() * 4);
        //bottomOfScreen is where you want to animate to

imageView.animate()
    .translationY(bottomOfScreen)
    .setInterpolator(new AccelerateInterpolator())
    .setInterpolator(new BounceInterpolator())
    .setDuration(2000);

That should get you started.

like image 55
A Honey Bustard Avatar answered Sep 27 '22 19:09

A Honey Bustard