最近项目中要实现点击游戏主角附近位置,控制主角的运动,之前总是出现问题,触摸主角左上角时得到的坐标和主角位图在屏幕中的坐标不一致。
最终问题得到解决,一个原因是坐标系的选取是否都选取了屏幕坐标系,第二个原因是主角bitmap在屏幕中的坐标跟屏幕的density 有关。
density = android中图片宽:pc中图片宽 = 1.5
最终解决方案:
最终问题得到解决,一个原因是坐标系的选取是否都选取了屏幕坐标系,第二个原因是主角bitmap在屏幕中的坐标跟屏幕的density 有关。
density = android中图片宽:pc中图片宽 = 1.5
event.getRawY()//得到触摸点在屏幕中的坐标private void drawImage(Canvas canvas, int x, int y,
Bitmap bsrc, int sx, int sy, int w, int h) {
Rect rect_src = new Rect();
rect_src.left = sx;
rect_src.right = sx + w;
rect_src.top = sy;
rect_src.bottom = sy + h;
Rect rect_dst = new Rect();
rect_dst.left = x;
rect_dst.right = x + w;
rect_dst.top = y;
rect_dst.bottom = y + h;
canvas.drawBitmap(bsrc, rect_src, rect_dst, null);
rect_src = null;
rect_dst = null;
}//This function ignores the density associated with the bitmap. This is because the source and destination rectangle coordinate spaces are in their respective densities, so must already have the appropriate scaling factor applied.
最终解决方案:
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// TODO Auto-generated method stub
float y = event.getRawY()*3/2;
float x = event.getRawX()*3/2;
touch_y = y;
touch_x = x;
// 按ship上方
if ((int) y < (Ship.ship_screen_ypos)) {
Ship.changeShipState(1);
Ship.ship_screen_ypos -= Ship.ship_height;
} else if ((int) y > Ship.ship_screen_ypos+Ship.ship_height) {
// 按ship下方
Ship.changeShipState(2);
Ship.ship_screen_ypos += Ship.ship_height;
}
if((int)x>(Ship.ship_screen_xpos+Ship.ship_width)){
// 加速
ConstantUtil.SPEED+=5;
}else if((int)x<Ship.ship_screen_xpos){
// 减速
ConstantUtil.SPEED-=5;
}
}
return true;
}
本文介绍了解决游戏中点击屏幕控制角色移动时遇到的坐标偏差问题,详细分析了坐标系选择及屏幕密度对坐标计算的影响,并提供了一个具体的实现方案。
7190

被折叠的 条评论
为什么被折叠?



