我有一个我无法解决的问题。问题是我想用另一个矩形推一个矩形,我这样做:
public boolean onTouchEvent(MotionEvent event){
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
case MotionEvent.ACTION_UP:
dx = touchX - event.getX();
dy = touchY - event.getY();
if(Math.abs(dy) > Math.abs(dx)){
if(dy > 0){ //Direction UP
manFirstY = manFirstY - 50;
manSecondY = manSecondY - 50;
if(manFirstY < targetSecondY && manFirstX == targetFirstX){
targetFirstY = targetFirstY - 50;
targetSecondY = targetSecondY - 50;
}
}
else if(dy < 0){ //Direction DOWN
manFirstY = manFirstY + 50;
manSecondY = manSecondY + 50;
if(manSecondY > targetFirstY && manFirstX == targetFirstX){
targetFirstY = targetFirstY + 50;
targetSecondY = targetSecondY + 50;
}
}
}
else{
if(dx > 0){ //Direction LEFT
manFirstX = manFirstX - 50;
manSecondX = manSecondX - 50;
if(manFirstX < targetSecondX && manFirstY == targetFirstY){
targetFirstX = targetFirstX - 50;
targetSecondX = targetSecondX - 50;
}
}
else if(dx < 0){ //Direction RIGHT
manFirstX = manFirstX + 50;
manSecondX = manSecondX + 50;
if(manSecondX > targetFirstX && manFirstY == targetFirstY){
targetFirstX = targetFirstX +50;
targetSecondX = targetSecondX +50;
}
}
}
}
return true;
}
但是有一个问题。当我使用这种方式它可以工作但除了推动它是用它来改变矩形。我不希望矩形携带另一个我只想推它而当我想要矩形移动远离他推动的那个我只想释放它。
答案 0 :(得分:0)
假设manFirstX / manSecondX / manFirstY / manSecondY是第一个矩形的左,右,上,下边缘,第二个矩形的目标是相同的,你应该尝试用一个例子检查你的代码!
如果第一个矩形位于第二个矩形的右侧,manSecondX
将始终大于targetSecondX
。如果您向右移动并且第一个矩形位于第二个矩形的右侧,则您的条件if(manSecondX > targetFirstX && manFirstY == targetFirstY)
将始终为真!
所以我的建议是简单地添加条件,例如
public boolean onTouchEvent(MotionEvent event){
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
case MotionEvent.ACTION_UP:
dx = touchX - event.getX();
dy = touchY - event.getY();
if(Math.abs(dy) > Math.abs(dx)){
if(dy > 0){ //Direction UP
manFirstY = manFirstY - 50;
manSecondY = manSecondY - 50;
if(targetFirstY < manSecondY && manFirstY < targetSecondY && manFirstX == targetFirstX){
targetFirstY = targetFirstY - 50;
targetSecondY = targetSecondY - 50;
}
}
else if(dy < 0){ //Direction DOWN
manFirstY = manFirstY + 50;
manSecondY = manSecondY + 50;
if(targetSecondY > manFirstY && manSecondY > targetFirstY && manFirstX == targetFirstX){
targetFirstY = targetFirstY + 50;
targetSecondY = targetSecondY + 50;
}
}
}
else{
if(dx > 0){ //Direction LEFT
manFirstX = manFirstX - 50;
manSecondX = manSecondX - 50;
if(targetFirstX < manSecondX && manFirstX < targetSecondX && manFirstY == targetFirstY){
targetFirstX = targetFirstX - 50;
targetSecondX = targetSecondX - 50;
}
}
else if(dx < 0){ //Direction RIGHT
manFirstX = manFirstX + 50;
manSecondX = manSecondX + 50;
if(targetSecondX > manFirstX && manSecondX > targetFirstX && manFirstY == targetFirstY){
targetFirstX = targetFirstX +50;
targetSecondX = targetSecondX +50;
}
}
}
}
return true;
这有希望成功!