如上图,主菜单的选项有各自的坐标数,点击在固定的范围内才能触发相应事件
package com.badlogic.androidgames.mrnom;
import java.util.List;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.Screen;
public class MainMenuScreen extends Screen {
public MainMenuScreen(Game game) {
super(game);
}
public void update(float deltaTime) {
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
if(inBounds(event, 0, g.getHeight() - 64, 64, 64)) {
Settings.soundEnabled = !Settings.soundEnabled;
if(Settings.soundEnabled)
Assets.click.play(1);
}
if(inBounds(event, 64, 220, 192, 42) ) {
game.setScreen(new GameScreen(game));
if(Settings.soundEnabled)
Assets.click.play(1);
return;
}
if(inBounds(event, 64, 220 + 42, 192, 42) ) {
game.setScreen(new HighscoreScreen(game));
if(Settings.soundEnabled)
Assets.click.play(1);
return;
}
if(inBounds(event, 64, 220 + 84, 192, 42) ) {
game.setScreen(new HelpScreen(game));
if(Settings.soundEnabled)
Assets.click.play(1);
return;
}
}
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width, int height) {
if(event.x > x && event.x < x + width - 1 &&
event.y > y && event.y < y + height - 1)
return true;
else
return false;
}
public void present(float deltaTime) {
Graphics g = game.getGraphics();
g.drawPixmap(Assets.background, 0, 0);
g.drawPixmap(Assets.logo, 32, 20);
g.drawPixmap(Assets.mainMenu, 64, 220);
if(Settings.soundEnabled)
g.drawPixmap(Assets.buttons, 0, 416, 0, 0, 64, 64);
else
g.drawPixmap(Assets.buttons, 0, 416, 64, 0, 64, 64);
}
public void pause() {
Settings.save(game.getFileIO());
}
public void resume() {
}
public void dispose() {
}
}
present 方法是在界面中画出背景图,游戏logo,游戏主菜单选项(实际上是一整张图片,不同选项),选择静音的按钮
inBounds方法限定触摸屏幕时,事件触发的区域
if(Settings.soundEnabled)
Assets.click.play(1);
上面的代码就是点击菜单以后,如果没有静音,那么播放点击时的音效
总的来说,还是很好理解的