In my Player.java class, I want to incorporate a function that moves my player according to the left or right swipes. I also used time in seconds in order to vary the movement in an cyclic way:
'''
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("KK:mm");
date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
String localTime = date.format(currentLocalTime);
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
X-=K;
int currentSeconds = cal.get(Calendar.SECOND);
Y=Y*Math.cos(18.currentSeconds);
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
X+=K;
int currentSeconds = cal.get(Calendar.SECOND);
Y=Y*Math.cos(18.currentSeconds);
}
} catch (Exception e) {
// nothing
}
return false;
}
'''
After some research, this is the class I included in player.java. So my question is: Is there a more efficient way to detect swiping directions(without creating any additional class) and what is your opinion about the code structure knowing that the objective is to change X according to swipe direction.
Thank you.
1 Answer 1
I changed some local variables and make them static variables, why ? because these are created and destroyed if you use serveral times the method onFling
. The main Idea is to improve the performance and decrease the space your method uses.
Also I refactorized some pieces of code
class MyGestureDetector extends SimpleOnGestureListener {
private static DateFormat date = new SimpleDateFormat("KK:mm");
private static Calendar cal;
MyGestureDetector() {
date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
String localTime = date.format(cal.getTime());
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
X -= K;
Y *= Math.cos(18*cal.get(Calendar.SECOND)); //18 * currentSeconds i think
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
X += K;
Y *= Math.cos(18*cal.get(Calendar.SECOND));
}
} catch (Exception e) {
// Perhaps if the program does nothing or have an unexpected behavior
// you are silencing the cause (it has happened to me)
e.printStackTrace();
}
return false;
}
Hope it helped.