我的应用程序中有一个球,它随着触摸而移动。我只是想让它只水平、垂直或倾斜移动不要移动它曲折我厌倦了按照代码和它的工作正常。
public class MainActivity extends Activity implements OnTouchListener {
Ourview v;
Bitmap ball;
float x,y;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = new Ourview(this);
v.setOnTouchListener(this);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.circle_green);
x = y = 0;
setContentView(v);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class Ourview extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
public Ourview(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void run() {
// TODO Auto-generated method stub
while (isItOk == true){
//perfom convas drawing
if (!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(250, 10, 50, 100);
c.drawBitmap(ball, x - (ball.getWidth()/2), y - (ball.getHeight()/2), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause(){
isItOk = false;
while(true){
try{
t.join();
}catch (InterruptedException e){
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOk = true;
t = new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent me) {
// TODO Auto-generated method stub
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch(me.getAction()){
case MotionEvent.ACTION_DOWN:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_MOVE:
x = me.getX();
y = me.getY();
break;
}
return true;
}
}
我的球随着触球向任何方向移动。我只是想限制我的球只能在水平或垂直或倾斜方向移动,它不应该以之字形移动。
谢谢