1
\$\begingroup\$

So I've got an Android app where if you swipe in a particular direction (UP, DOWN, RIGHT, LEFT), the dice move in that direction using TranslateAnimation. This is how I generate random numbers - arrayNumber = generateRandomCoordinateNumbers((Tut3Main.maxX / 2)+170,50);

So say if you swipe down, the swipe() method is called, which will generate 4 random float numbers, and then pass them to a method which runs the animation

swipedDiceInThisDirection(float n1, float n2, float n3, float n4)

But I've been having a couple of problems getting everything 100% correct. These problems are:

  1. When you tap on a single die, it's supposed to change the dice's image to (R.drawable.die1). Instead of changing the dice image, it will run an onTouchEvent, meaning it will either run the swipe event for moving the dice up, down, left, or right.
  2. The dice go off the screen during the Translate and won't move in the right direction

The reason the dice are going off the screen is because I cannot get my calculations right when generation 4 random coordinates that are suppose to be in the VIEW. So at the moment when I swipe up it will generate a number between -50 AND -((Tut3Main.maxY / 2) - 170). This seems to be working fine as the dice go in the top half of the screen.

But generating random numbers for the LEFT, RIGHT, and BOTTOM sections of the screen doesn't work. They just go way of the screen. I'm unsure to how I can generate 4 coordinates for each section of the screen.

E.g If the user Swipes down, the dice are suppose to move somewhere within the bottom half of the phone screen. Instead the dice go way off the screen, down near the bottom right corner.

Here's my working code:

dice.java

This class has all the logic for moving the dice, generating random coordinates, and etc.

public class dice {
    private static int type;
    private static int singleDieClicked;
    private static ImageView die1;
    private static ImageView die2;

    //Translate animations
    private static TranslateAnimation moveDie1;
    private static TranslateAnimation moveDie2;


    public dice(int type, ImageView die1, ImageView die2, int singleDieClicked) {
        this.type = type;
        this.die1 = die1;
        this.die2 = die2;
        this.singleDieClicked = singleDieClicked;
    }

    public static void swipe() {

        float[] arrayNumber; //Holds random coordinates

        //Swipe down
        if(type == 1){
            arrayNumber = generateRandomCoordinateNumbers((Tut3Main.maxX / 2)+170,50);
            swipedDiceInThisDirection(arrayNumber[0],arrayNumber[1],
                    arrayNumber[2],arrayNumber[3] );

        }
        //Swipe up
        else if(type == 2){
            arrayNumber = generateRandomCoordinateNumbers(-50, -((Tut3Main.maxY / 2) - 170));
            swipedDiceInThisDirection(arrayNumber[0],arrayNumber[1],
                    arrayNumber[2],arrayNumber[3] );

        }
        //Swipe right
        else if(type == 3){
            arrayNumber = generateRandomCoordinateNumbers(Tut3Main.maxY/2, (Tut3Main.maxY/2)-50);
            swipedDiceInThisDirection(arrayNumber[0],arrayNumber[1],
                    arrayNumber[2],arrayNumber[3] );

        }

    }
    public static void swipedDiceInThisDirection(float n1, float n2, float n3, float n4){

        //Die1
        moveDie1 = new TranslateAnimation(0, n1, 0, n2);  //  new TranslateAnimation(xFrom,xTo, yFrom,yTo)
        moveDie1.setDuration(2000);  // animation duration

        //Die2
        moveDie2 = new TranslateAnimation(0, n3, 0, n4);
        moveDie2.setDuration(2000);

        moveDie1.setFillAfter(true);
        moveDie2.setFillAfter(true);
        moveDie1.setFillEnabled(true);
        moveDie2.setFillEnabled(true);

        animationListeners(); //Animation listeners
        determineDiceClicked();

    }

    //Determine which dice was clicked depending on INT value
    public static void determineDiceClicked(){
        //Start the animations
        if(singleDieClicked == 0) {
            die1.startAnimation(moveDie1);
            die2.startAnimation(moveDie2);
            Log.d("2 die clicked:", "two dice were clicked ->"+singleDieClicked);

        }
        else if(singleDieClicked == 1) {
            die1.startAnimation(moveDie1); //If die1 was only clicked
            Log.d("2 die clicked:", "two die were clicked ->"+singleDieClicked);
        }
        else {
            die2.startAnimation(moveDie2); //If die 2 was only clicked
            Log.d("2 die clicked:", "two die were clicked ->"+singleDieClicked);
        }

    }

    public static void animationListeners(){
        final int[] setDice = generateRandomDrawableNumbers();

        moveDie1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
//                die1.setBackgroundResource(R.drawable.animate_dice);
                die1.setImageResource(R.drawable.animate_dice);
            }


            @Override
            public void onAnimationEnd(Animation animation) {
                die1.setImageResource(Tut3Main.die[setDice[1]]); //Set dice to random dice drawable

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });




        moveDie2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
//                die2.setBackgroundResource(R.drawable.animate_dice);
                die2.setImageResource(R.drawable.animate_dice);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                die2.setImageResource(Tut3Main.die[setDice[0]]);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    private static float[] generateRandomCoordinateNumbers(int high, int low){
        float[] numbers = new float[4];
        float R;

        float Low = low;
        float High = high;
        Log.d("LOW_HIGH: ", ""+Low+ "  "+High);

        for(int i=0;i<numbers.length;i++) {
            Random r = new Random();
            R = r.nextFloat() * (High - Low) + Low;
            numbers[i] = R;
            Log.d("Number " + i, "--> " + numbers[i]);
        }

        return numbers;
    }

//    public void
    private static int[] generateRandomDrawableNumbers(){
        int[] numbers = new int[2];
        int R;

        int Low = 0;
        int High = 5;

        for(int i=0;i<numbers.length;i++) {
            Random r = new Random();
            R = r.nextInt(High - Low) + Low;
            numbers[i] = R;
        }

        return numbers;
    }
}

Tut3Main.java

This has all the logic for finding out which direction the user swiped, if they've swiped a single dice

public class Tut3Main extends ActionBarActivity {

    public static final int[] die = {R.drawable.die1, R.drawable.die2,R.drawable.die3,R.drawable.die4,
                        R.drawable.die5, R.drawable.die6};
    float x1,x2;
    float y1, y2;
    public static ImageView dice1;
    public static ImageView dice2;
    public static RelativeLayout main_layout;
    public static int maxX;
    public static int maxY;
    public static int singleDiceClicked;
    public static boolean cancelSwipe=false;

    GestureDetector gestureDetector;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tut3_main);
        getScreenDetails();


        dice1 = (ImageView) findViewById(R.id.die1);
        dice2 = (ImageView) findViewById(R.id.die2);
        main_layout = (RelativeLayout) findViewById(R.id.main_layout);
        gestureDetector = new GestureDetector(this.getApplicationContext(), new GestureListener());
//        onClickDice();
        checkIfSingleDieClicked();


    }

    //Get the screen details
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void getScreenDetails(){
        Display mdisp = getWindowManager().getDefaultDisplay();
        Point mdispSize = new Point();
        mdisp.getSize(mdispSize);
        maxX = mdispSize.x;
        maxY = mdispSize.y;

    }


    public void checkIfSingleDieClicked() {

        //Check for die1
        dice1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                onTouchEvents(event, 1);

                return true;
            }
        });
        //Check for die2
        dice2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(!cancelSwipe)
                    onTouchEvents(event, 2);

                dice1.setImageResource(die[0]);

                return true;
            }
        });


        main_layout.setOnTouchListener(new View.OnTouchListener() {
            boolean firstTouch = false;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                onTouchEvents(event, 0);


                return true;
            }
        });
    }

//    public void onClickDice(){
//        dice1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // do something when the corky3 is clicked
//                dice1.setImageResource(die[0]);
//                cancelSwipe=true;
////                return;
//            }
//        });
//    }

    public boolean onTouchEvents(MotionEvent touchevent, int singleDiceClicked)
    {


//        checkIfSingleDieClicked(); //Checks if a single dice has been clicked
        switch (touchevent.getAction())
        {

            // when user first touches the screen we get x and y coordinate
            case MotionEvent.ACTION_DOWN:
            {
                x1 = touchevent.getX();
                y1 = touchevent.getY();


                break;
            }
            case MotionEvent.ACTION_UP:
            {
//                if(x1%x2 < 100) {
//                    Toast.makeText(this, "Swiped Down", Toast.LENGTH_LONG).show();
//                    return false;
//                }
                x2 = touchevent.getX();
                y2 = touchevent.getY();

                //if left to right sweep event on screen
                if (x1 < x2)
                {
//                   Toast.makeText(this, "Swiped left", Toast.LENGTH_LONG).show();
//                    Swipe left:
                    dice diceCall = new dice(3, dice1, dice2,singleDiceClicked);
                    diceCall.swipe();

                }

                // if right to left sweep event on screen
                if (x1 > x2)
                {
//                    Toast.makeText(this, "Swiped left", Toast.LENGTH_LONG).show();
////                    Swipe left:
//                    dice diceCall = new dice(3, dice1, dice2,singleDiceClicked);
//                    diceCall.swipe();


                }

                // if UP to Down sweep event on screen
                if (y1 < y2)
                {
                    //Swipe down:
                    Toast.makeText(this, "Swiped Down", Toast.LENGTH_LONG).show();
                    checkIfSingleDieClicked();
                    dice diceCall = new dice(1, dice1, dice2, singleDiceClicked);
                    diceCall.swipe();
                }

                //if Down to UP sweep event on screen
                if (y1 > y2)
                {
                    //Swipe up:
                    Toast.makeText(this, "Swiped Up", Toast.LENGTH_LONG).show();
                    checkIfSingleDieClicked();
                    dice diceCall = new dice(2, dice1, dice2,singleDiceClicked);
                    diceCall.swipe();

                }
                break;
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_tut3_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
        // event when double tap occurs
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            float x = e.getX();
            float y = e.getY();



            return true;
        }
    }

}

Here are the XML files:

activity_tut3_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Tut3Main"
    android:id="@+id/main_layout">
    <ImageView
        android:id="@+id/die1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/die1"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/die2"
        android:layout_toStartOf="@+id/die2"
        android:layout_marginRight="10dp" />

    <ImageView
        android:id="@+id/die2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/die1"
        android:layout_marginRight="58dp"
        android:layout_marginEnd="58dp"
        android:layout_alignTop="@+id/die1"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

animate_dice.xml

<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/die_1_3_5" android:duration="50" />
    <item android:drawable="@drawable/die_4_2_6" android:duration="50" />


</animation-list>

die_1_3_5.xml

<animation-list
    android:id="@+id/animate_dice"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/die1" android:duration="100" />
    <item android:drawable="@drawable/die3" android:duration="100" />
    <item android:drawable="@drawable/die5" android:duration="100" />
</animation-list>

Note: Im happy to upload the whole project to github if anyone wants to run it :)

\$\endgroup\$
  • \$\begingroup\$ any update on this? \$\endgroup\$ – Nidhin Prathap May 17 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.