how to detect when a ImageView is in collision with another ImageView?

夙愿已清 提交于 2019-12-02 20:43:57

问题


Im developing a test game with some imageviews on the screen.

with the finger, i am moving another imageview.

I want to detect when the imageview moved by the finger has touched another imageview.

¿Wich is the best way to achieve it? I can't find info about it on google...

Thanks


回答1:


I'll answer the general question - find out when two views overlap:


private boolean viewsOverlap(View v1, View v2) {
    int[] v1_coords = new int[2];
    v1.getLocationOnScreen(v1_coords);
    int v1_w = v1.getWidth();
    int v1_h = v1.getHeight();
    Rect v1_rect = new Rect(v1_coords[0], v1_coords[1], v1_coords[0] + v1_w, v1_coords[1] + v1_h);

    int[] v2_coords = new int[2];
    v2.getLocationOnScreen(v1_coords);
    int v2_w = v2.getWidth();
    int v2_h = v2.getHeight();
    Rect v2_rect = new Rect(v2_coords[0], v2_coords[1], v2_coords[0] + v2_w, v2_coords[1] + v2_h);

    return v1_rect.intersect(v2_rect) || v1_rect.contains(v2_rect) || v2_rect.contains(v1_rect);
}


My trigonometry is a little shaky these days so I'm not sure about this part:

OVERLAP ==  v1_rect.intersect(v2_rect) || v1_rect.contains(v2_rect) || v2_rect.contains(v1_rect);


Double check me. Good luck.





回答2:


Try using the intersect method of class Rect:

https://stackoverflow.com/a/19086884/3249477



来源:https://stackoverflow.com/questions/24600378/how-to-detect-when-a-imageview-is-in-collision-with-another-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!