There is a rocket that moves in a certain direction with ACTION_DOWN (when clamping) with the help of a Timer, I would like to make the user click on the screen and the rocket move, but when he lowered his finger, the rocket immediately stopped. Here is the code that was written, and in this code with ACTION_UP the timer stops, but in fact it just starts to conflict with the next pressing timer, how to fix it?

@Override public boolean onTouchEvent(final MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if(event.getY()>(Game.heightDisplay/2)) { timerTask = new MyTimerTask(); timer.scheduleAtFixedRate(timerTask, 0, 100); } else if(event.getY()<(Game.heightDisplay/2)) { timerTask2 = new MyTimerTask2(); timer2.scheduleAtFixedRate(timerTask2, 0, 100); } break; case MotionEvent.ACTION_UP: timerTask.cancel(); timerTask2.cancel(); break; } return super.onTouchEvent(event); } class MyTimerTask extends TimerTask { public void run() { if(coordY >= 930) { coordY = 930; } else { coordY = coordY + 50; } } } class MyTimerTask2 extends TimerTask { public void run() { if(coordY <= 0) { coordY = 5; } else { coordY = coordY - 50; } } } 
  • What does it start to conflict ? - Vladyslav Matviienko
  • This means that there are two timers at the same time, one of which is trying to pull the rocket up, the other also up and the rocket flies twice as fast and possibly jerks - P. Ilyin
  • @ P.Ilyin, yes, you are right, it starts moving twice as fast, but my screen is divided into two halves, clicking on which sets different directions of the rocket, so when you press the opposite side, the timer of one half and the other start to conflict, because of what the rocket freezes in one place and twitches (that is, 2 timers change the coordinates of the rocket to the opposite (+50 and -50, therefore it twitches)) - En1q0d
  • @ En1q0d, why don't you stop timers yourself? .. Ie timer.camcel(); timer2.camvel(); besides completing the timer task? - JuriySPb
  • @YuriSPb, it's just that I tried different options (in this case, without timer.cancel ();), and even with timer.cancel () and timer2.cancel (); does not work. - En1q0d

1 answer 1

The best solution would be to start one timer, which will exist during the entire gaming session, regardless of user clicks. At the same time, let the rocket have a variable velocity (velocity). When the user presses the screen, set the velocity = 50, and when removing the finger from the screen, velocity = 0. The timer will always move the rocket to the value of the velocity variable. If velocity is 50 - the rocket will move, and Elsi 0, then stand