Reputation: 85
I am working on a mini game for Android. When I click and hold down the button that I am clicking I expect that a event should be triggered once at a interval of time.
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
moveLeft();
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
moveRight();
return (true);
}
}
This code works if I am using the simulator and the arrows in my keyboard. I also put down 2 Buttons on the layout and now want the same efect the object to move left or right when the button is touched at a interval of time. How can I do that ?
Upvotes: 1
Views: 1098
Reputation: 2253
What button? there's no left and right button on android phones.
but anyway the best way to do that kinda depends on how your game is built I guess, you probably should use either a postDelay or a thread.
maybe you can try setting a boolean that will be set to true when the key is down and false when its up and then run a postDelay when the key is down like so
new Handler().postDelayed(new Runnable(){
public void run(){
if (movingLeft) //your boolean
moveLeft();
}
},1000); //time interval in milliseconds
don't forget to kill it, you don't want thousands of handlers running .. I don't really have any experience in programming games though.. hope it helps.
Upvotes: 2