最近项目中要实现点击游戏主角附近位置,控制主角的运动,之前总是出现问题,触摸主角左上角时得到的坐标和主角位图在屏幕中的坐标不一致。

最终问题得到解决,一个原因是坐标系的选取是否都选取了屏幕坐标系,第二个原因是主角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 stubfloat 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;}

更多相关文章

  1. Android保持屏幕常亮的两种方法
  2. Android-UI屏幕适配全攻略
  3. android屏幕适配,除了使用dp,还可以使用比例
  4. android dp sp px区别,android获取屏幕尺寸、密度
  5. 仅仅是个人记录:Android(安卓)的机型适配: 屏幕适配(包括dpi,dp,sp
  6. android中屏幕适配的方式
  7. Android高清输出四大名“捕”
  8. 入手 Nexus S
  9. 【Android游戏开发二十二】(图文详解)游戏中灵活实现动画播放!

随机推荐

  1. Android中Dialog实现自定义弹出对话框
  2. Android按钮设置文字变色
  3. android启动:app_process实现恢复出厂设置
  4. Android自定义对话框
  5. Android Log Analysis bugreport
  6. Android sqlite3 数据库批量操作
  7. Android跟踪NDK崩溃信息
  8. Android注解框架 AndroidAnnotations
  9. android view获取焦点且有黄色高亮效果
  10. android 播放铃声