gpt4 book ai didi

java - android中2个 View 之间的碰撞

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:50 24 4
gpt4 key购买 nike

我在 android 中有 2 个 View ,它们是可拖动的。我想检测它们之间的碰撞。目前我正在使用此代码来检测碰撞,但我认为它不起作用。请建议需要检查碰撞的内容。

public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();

_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams ParamsA = (RelativeLayout.LayoutParams) view
.getLayoutParams();
ParamsA.leftMargin = X - _xDelta;
ParamsA.topMargin = Y - _yDelta;
ParamsA.rightMargin = -250;
ParamsA.bottomMargin = -250;

for (int i = 0; i < balls.size(); i++) {
if (balls.get(i).getTag() != view.getTag()) {
RelativeLayout.LayoutParams ParamsB = (RelativeLayout.LayoutParams) balls
.get(i).getLayoutParams();

Rect b = new Rect(ParamsB.leftMargin,ParamsB.topMargin,ParamsB.rightMargin,ParamsB.bottomMargin);
Rect a = new Rect(ParamsA.leftMargin,ParamsA.topMargin,ParamsA.rightMargin,ParamsA.bottomMargin);


if(a.intersect(b))
{
Toast.makeText(getApplicationContext(), "Collision Detected", Toast.LENGTH_SHORT).show();
}
}

}

view.setLayoutParams(ParamsA);
break;
}
// _root.invalidate();
return true;
}

“balls”是放置在屏幕上的“View”类型的数组。

最佳答案

我自己找到了解决方案,它在所有情况下都很完美。

public boolean CheckCollision(View v1,View v2) {
Rect R1=new Rect(v1.getLeft(), v1.getTop(), v1.getRight(), v1.getBottom());
Rect R2=new Rect(v2.getLeft(), v2.getTop(), v2.getRight(), v2.getBottom());
return R1.intersect(R2);
}

关于java - android中2个 View 之间的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com