我是初学者,但我想制作一款游戏。现在我正在为我的英雄做移动功能。当我触摸图像并将其移动到右侧时,英雄将从原始位置向右移动每秒100dp,但它无法工作。
以下是我用作移动功能的代码:
public View.OnTouchListener move = new View.OnTouchListener() {
private float x, y;
private int mx, my, hx, hy;
public boolean onTouch(final View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN)) {
x = event.getX();
y = event.getY();
mx = (int) (event.getRawX() - x);
my = (int) (event.getRawY() - y);
} else if ((event.getAction() == MotionEvent.ACTION_MOVE)) {
hx = (int) (event.getRawX() - x);
hy = (int) (event.getRawY() - y);
v.layout(hx, hy, hx + v.getWidth(), hy + v.getHeight());
} else if ((event.getAction() == MotionEvent.ACTION_UP)) {
while (hx > mx) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mx += 100;
v.layout(mx, my, mx + v.getWidth(), my + v.getHeight());
}
}, 1000);
}
}
Log.e("x =", String.valueOf(x) + " y =" + String.valueOf(y));
Log.e("hx =", String.valueOf(hx) + " hy =" + String.valueOf(hy));
Log.e("mx =", String.valueOf(mx) + " my =" + String.valueOf(my));
return true;
}
};
答案 0 :(得分:0)
在ACTION_MOVE
和ACTION_UP
:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
//edit layout params according to your need
view.setLayoutParams(layoutParams);