【问题标题】:how to detect when a ImageView is in collision with another ImageView?如何检测 ImageView 何时与另一个 ImageView 发生冲突?
【发布时间】:2021-05-02 10:11:44
【问题描述】:

我正在开发一个屏幕上有一些图像视图的测试游戏。

用手指,我正在移动另一个图像视图。

我想检测手指移动的imageview何时触摸到另一个imageview。

实现它的最佳方法是什么?我在 Google 上找不到有关它的信息。

【问题讨论】:

    标签: android android-layout imageview collision-detection collision


    【解决方案1】:

    我将回答一般性问题 - 找出两个视图何时重叠


    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);
    }
    


    这些天我的三角函数有点不稳定,所以我不确定这部分:

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


    仔细检查我。祝你好运。


    【讨论】:

    • 嗨,谢谢,但它创建了一个矩形,我的图像不是矩形,是带有圆形图片的 png,如云或球。所以,这种碰撞策略给了我一个失败,因为当imageview的角落接触到另一个imageview的角落时它给了我碰撞,但是imageviews里面的位图没有被触摸......这可以解决吗?
    • @AndroidUser99 你找到解决办法了吗?
    【解决方案2】:

    尝试使用Rect类的intersect方法:

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

    【讨论】:

    • 这个问题也和你的不同。你试过了吗?
    • 嗨,谢谢,但它创建了一个矩形,我的图像不是矩形,是带有圆形图片的 png,如云或球。所以,这种碰撞策略给了我一个失败,因为当imageview的角落接触到另一个imageview的角落时它给了我碰撞,但是imageviews里面的位图没有被触摸......这可以解决吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多