我想开发一个简单的互动游戏(如arcanoid)。我已经实现了一个菜单和不同的视图,现在我需要开发实际游戏(绘制飞球,一些可移动平台),我不知道该怎么做。我需要像画布一样的东西,我可以在每一帧画出我的图形。
我已尝试使用Canvas和Timer实现此功能。但它不希望更新图形本身,但只有当用户点击屏幕或类似时。我也看到了com.google.gwt.canvas.client.Canvas,但我无法理解如何在Vaadin应用程序中使用它。
所以接下来我的问题是:是否有可能以任何方式以高帧率绘制每帧的图形?如果可能的话,我该怎么做?
P.S。我使用Vaadin 7.3.3。
答案 0 :(得分:5)
稍后添加:
Here is a link to my educational project with implementation below. 如果有人帮助我,我会很高兴。
原始回答:
嗯......我自己找到了解决方案。首先,我创建了自己的小部件 - "客户端"组件(根据此article)。
客户端部分:
public class GWTMyCanvasWidget extends Composite {
public static final String CLASSNAME = "mycomponent";
private static final int FRAMERATE = 30;
public GWTMyCanvasWidget() {
canvas = Canvas.createIfSupported();
initWidget(canvas);
setStyleName(CLASSNAME);
}
连接器:
@Connect(MyCanvas.class)
public class MyCanvasConnector extends AbstractComponentConnector {
@Override
public Widget getWidget() {
return (GWTMyCanvasWidget) super.getWidget();
}
@Override
protected Widget createWidget() {
return GWT.create(GWTMyCanvasWidget.class);
}
}
服务器端部分:
public class MyCanvas extends AbstractComponent {
@Override
public MyCanvasState getState() {
return (MyCanvasState) super.getState();
}
}
然后我只在我的视图中添加MyCanvas
组件:
private void createCanvas() {
MyCanvas canvas = new MyCanvas();
addComponent(canvas);
canvas.setSizeFull();
}
现在我可以在Canvas上绘制任何东西(在GWTMyCanvasWidget的客户端)并且具有很好的性能=)。例如:
public class GWTMyCanvasWidget extends Composite {
public static final String CLASSNAME = "mycomponent";
private static final int FRAMERATE = 30;
private Canvas canvas;
private Platform platform;
private int textX;
public GWTMyCanvasWidget() {
canvas = Canvas.createIfSupported();
canvas.addMouseMoveHandler(new MouseMoveHandler() {
@Override
public void onMouseMove(MouseMoveEvent event) {
if (platform != null) {
platform.setCenterX(event.getX());
}
}
});
initWidget(canvas);
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent resizeEvent) {
resizeCanvas(resizeEvent.getWidth(), resizeEvent.getHeight());
}
});
initGameTimer();
resizeCanvas(Window.getClientWidth(), Window.getClientHeight());
setStyleName(CLASSNAME);
platform = createPlatform();
}
private void resizeCanvas(int width, int height) {
canvas.setWidth(width + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setHeight(height + "px");
canvas.setCoordinateSpaceHeight(height);
}
private void initGameTimer() {
Timer timer = new Timer() {
@Override
public void run() {
drawCanvas();
}
};
timer.scheduleRepeating(1000 / FRAMERATE);
}
private void drawCanvas() {
canvas.getContext2d().clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight());
drawPlatform();
}
private Platform createPlatform() {
Platform platform = new Platform();
platform.setY(Window.getClientHeight());
return platform;
}
private void drawPlatform() {
canvas.getContext2d().fillRect(platform.getCenterX() - platform.getWidth() / 2, platform.getY() - 100, platform.getWidth(), platform.getHeight());
}
}