Canvas gamecamera - locationtranslate values messed up by applied canvas scaling
I'm working on an android game and am currently busy with a gamecamera type of component. The best method seems to be translating the canvas (possibly with a matrix) to move the entire canvas to act like a gamecamera. (please correct me if I'm wrong).
this is all getting along pretty nicely, 开发者_高级运维the gamecamera is moving and the x and y values of the camera are being used as guidelines to translate the canvas location:
public void onMove(float distanceX, float distanceY){
Camera.x += (int) distanceX;
Camera.y += (int) distanceY;
}
protected void onDraw(Canvas canvas) {
canvas.translate(Camera.x, Camera.y);
level.draw(canvas);
//the text is a ui component so shouldn't move with the level
canvas.restore();
canvas.drawText(fps + " fps", 0, 32, textPaint);
}
When trying to interact with the world I simply add the camera's coordinates to the touch's coordinates to get the correct point in the world:
public void onSingleTap(MotionEvent event) {
float mouseX = event.getX() - Camera.x;
float mouseY = event.getY() - Camera.y;
}
However, The user also has the choice to scale the screen, zooming to a point on the world.
case MotionEvent.ACTION_MOVE:
if (MODE == ZOOM && event.getPointerCount() == 2) {
float newDist = spacing(event);
if (newDist > 10f) {
Camera.zoom = newDist / PrevMultiDist;
//the midpoint for the zoom
midPoint(midpoint, event);
Camera.setPivot(midpoint.x, midpoint.y);
translateMatrix.postScale(Camera.zoom, Camera.zoom, Camera.pivotX, Camera.pivotY);
}
}
break;
The zoom is messing up the world-touch translation coordinates since the view is being moved to zoom on the chosen spot. I think if I substract the zoom offset value from the camera location that I will get the correct position in the world again.
So the touchevent becomes something like this:
public void onSingleTap(MotionEvent event) {
//ideally the zoomoffset might be added in the camera's location already?
float mouseX = event.getX() - Camera.x - zoomOffsetX;
float mouseY = event.getY() - Camera.y - zoomOffsetY;
}
I already found this question: Android get Bitmap Rect (left, top, right, bottom) on a Canvas but it doesn't provide the awsner I want and I can't figure out if his calculations can help me.
I feel like I'm missing something really simple. Hope someone can help!
精彩评论