android 触摸点在屏幕中的坐标与bitmap在屏幕中坐标的比较

本文介绍了解决游戏中点击屏幕控制角色移动时遇到的坐标偏差问题,详细分析了坐标系选择及屏幕密度对坐标计算的影响,并提供了一个具体的实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值