呵呵, 先上效果图, 搞了半天终于学会在博客上上传动态的gif图片了。 刚玩了个画线闯关的小游戏, 然后试着做个用手在屏幕上画线, 然后sprite绕着线移动的例子。
还是比较简单的, 只需要在每次屏幕的action_move事件中, 记录当前坐标, 然后和上次的坐标之间用Line连接起来。 并且把所有坐标拼成一个Path, 当action_up时,在最开头生成一个sprite, 并且注册PathModifer就可以了。 话不多说, 上代码。
初始化代码, 无关紧要, 主要就是资源加载和定义了几个变量:
private static final int width = 720;
private static final int height = 480;
private BuildableBitmapTextureAtlas bbta;
private ITextureRegion smi;
private float lastX = 0;
private float lastY = 0;
private List<Float> listx = new ArrayList<Float>();
private List<Float> listy = new ArrayList<Float>();
@Override
public EngineOptions onCreateEngineOptions() {
Camera camera = new Camera(0, 0, width, height);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(width, height), camera);
}
@Override
protected void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
bbta = new BuildableBitmapTextureAtlas(getTextureManager(), 128, 128);
smi = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bbta, getAssets(), "smi.png");
try {
bbta.build(new BlackPawnTextureAtlasBuilder(0, 0, 0));
bbta.load();
} catch (TextureAtlasBuilderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
下面重点来了, 主要的逻辑就在这里, 每次移动的时候,就在上次记录的点lastx, lasty和当前的点之间画LINE, 然后记录当前坐标, 当ACTION_UP时, 把所有的坐标拼成一个Path , 生成一个sprite 按照这个path‘移动即可, 很简单的一个功能。
@Override
protected Scene onCreateScene() {
final Scene scene = new Scene();
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()){
lastX = pSceneTouchEvent.getX();
lastY = pSceneTouchEvent.getY();
listx.add(lastX);
listy.add(lastY);
}
if(pSceneTouchEvent.isActionMove()){
Line line = new Line(lastX, lastY, pSceneTouchEvent.getX(), pSceneTouchEvent.getY(), getVertexBufferObjectManager());
scene.attachChild(line);
listx.add( pSceneTouchEvent.getX()-smi.getWidth()/2);
listy.add( pSceneTouchEvent.getY()-smi.getHeight()/2);
lastX = pSceneTouchEvent.getX();
lastY = pSceneTouchEvent.getY();
}
if(pSceneTouchEvent.isActionUp()){
if(listx.size() == listy.size() && listx.size()>0){
Sprite sprite = new Sprite(listx.get(0), listy.get(0), smi, getVertexBufferObjectManager());
float pathx[] = new float[listx.size()];
float pathy[] = new float[listx.size()];
for(int i=0; i<pathx.length; i++){
pathx[i] = listx.get(i);
pathy[i] = listy.get(i);
}
Path path = new Path(pathx, pathy);
sprite.registerEntityModifier(new PathModifier(2, path));
scene.attachChild(sprite);
listx.clear();
listy.clear();
}
}
return true;
}
});
scene.setTouchAreaBindingOnActionDownEnabled(true);
return scene;
}