在手機游戲的開發中,要做多機型的適配,但是越來越多的機器開始支持觸摸屏操作。
那么我們也要很好的去實現其觸摸屏的輸入,以讓玩家有類似甚至超過鍵盤控制的舒適感。
下面是一個觸摸屏游戲按鈕管理思想,對游戲中人物的觸摸屏控制會在整理后放出。
該思路并不一定是最佳的,只是我是這么實現的。
-0-
屏幕上所有可以被點擊的區域(RECT)按鈕都是一個對象,他們有自己被點擊的todo()方法,還有一個觸點管理器,該管理器控制添加觸摸按鈕以及清理所有觸摸按鈕和每個按鈕是否被點擊的判定。
具體實現如下:
1
import javax.microedition.lcdui.Graphics;
2
3
import vectors.CVector;
4
5
import base.CTools;
6
import base.CType;
7
8
/** *//**
9
* 觸點區域
10
*
11
* @example 重寫todo方法<br>
12
* pointAreaManager.addPionterArea(pointAreaManager.new
13
* PointArea(10, 10, 50, 50){
14
* <br>public void todo(){ <br>
15
* // 寫要被點擊后要做的邏輯<br>
16
*
17
* // ------------------------------------------------------------<br>
18
* }<br>
19
* });
20
*
21
*
22
* @author Colonleado
23
*
24
*/
25
public class PointAreaManager
{
26
27
public CVector a = new CVector();
28
29
public void addPionterArea(PointArea area)
{
30
31
a.addElement(area);
32
33
}
34
35
public void update()
{
36
37
for (int i = 0; i < a.size(); ++i)
{
38
39
PointArea b = (PointArea) a.elementAt(i);
40
41
b.update();
42
43
}
44
45
}
46
47
public void debug(Graphics g)
{
48
for (int i = 0; i < a.size(); ++i)
{
49
50
PointArea b = (PointArea) a.elementAt(i);
51
52
b.debug(g);
53
54
}
55
}
56
57
public void clear()
{
58
59
a.removeAllElements();
60
61
}
62
63
public abstract class PointArea
{
64
65
private int x, y, width, height;
66
67
public PointArea(int _x, int _y, int _width, int _height)
{
68
69
x = _x;
70
71
y = _y;
72
73
width = _width;
74
75
height = _height;
76
77
}
78
79
private boolean isPointerClick()
{
80
81
// 是否發生了觸摸事件
82
if (CType.havePointerEvent)
{
83
84
// 如果發生了觸摸事件 檢測下是否觸點在該區域矩形內
85
if (CTools.isPointInRect(CType.getPointerX(),
86
CType.getPointerY(), x, y, width, height))
{
87
88
CType.havePointerEvent = false;
89
90
return true;
91
92
}
93
94
}
95
96
return false;
97
98
}
99
100
public void update()
{
101
102
// 如果被點擊了 那么執行自己的todo
103
if (isPointerClick())
{
104
105
todo();
106
107
}
108
109
}
110
111
// 抽象方法todo 供不同矩形按鈕去實現
112
protected abstract void todo();
113
114
public void debug(Graphics g)
{
115
g.setColor(0x00ffff);
116
g.drawRect(x, y, width, height);
117
}
118
119
}
120
121
}
我們在主類(一般是我們的Canvas)中實例一個PointAreaManager的對象,以此來完成對觸摸屏輸入的所有管理。
1
// 實例一個觸點管理器
2
psm = new PointAreaManager();
3
// 添加一個按鈕
4
psm.addPionterArea(psm.new PointArea(0, CType.ScreenHeight - 30,
5
40, 30)
{
6
7
// 實現todo方法
8
protected void todo()
{
9
10
// 如果被點擊了 就打開音樂
11
pointerAskMusicOk();
12
13
}
14
15
});
這樣當進入一個新的界面時,我們只需要向管理器中添加我們需要的矩形區域按鈕們,他們各自實現了自己的todo。而在游戲的邏輯更新中會執行管理器的update,管理器會去檢查每一個按鈕是否被點擊,是就執行該按鈕的todo。這樣就做到了按鈕自己管理自己。
當切換界面的時候只需要清理掉管理器中的所有按鈕,再添加新按鈕們即可。