碰撞檢測算法:點和矩形碰撞、點和圓形碰撞、矩形碰撞、圓形碰撞


點和矩形碰撞

/** 
     *  
     * @param x1 點 
     * @param y1 點 
     * @param x2 矩形view x 
     * @param y2 矩形view y 
     * @param w  矩形view 寬 
     * @param h  矩形view 高 
     * @return 
     */  
    public static boolean isCollision(int x1, int y1, int x2, int y2, int w, int h) {  
        if (x1 >= x2 && x1 <= x2 + w && y1 >= y2 && y1 <= y2 + h) {  
            return true;  
        }   
        return false;  
    }  

矩形碰撞

/** 
     * 檢測兩個矩形是否碰撞 
     * @return 
     */  
    public boolean isCollisionWithRect(int x1, int y1, int w1, int h1,   
            int x2,int y2, int w2, int h2) {  
        if (x1 >= x2 && x1 >= x2 + w2) {  
            return false;  
        } else if (x1 <= x2 && x1 + w1 <= x2) {  
            return false;  
        } else if (y1 >= y2 && y1 >= y2 + h2) {  
            return false;  
        } else if (y1 <= y2 && y1 + h1 <= y2) {  
            return false;  
        }  
        return true;  
    }  

點(x1,x2) , 圓心(x2,y2) ,半徑r

if (Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) <= r) {  
            // 如果點和圓心距離小於或等於半徑則認為發生碰撞  
            return true;  
        }  

圓和圓

/** 
     * 圓形碰撞 
     *  
     * @param x1 
     *            圓形1的圓心X坐標 
     * @param y1 
     *            圓形2的圓心X坐標 
     * @param x2 
     *            圓形1的圓心Y坐標 
     * @param y2 
     *            圓形2的圓心Y坐標 
     * @param r1 
     *            圓形1的半徑 
     * @param r2 
     *            圓形2的半徑 
     * @return 
     */  
    private boolean isCollisionWithCircle(int x1, int y1, int x2, int y2,  
            int r1, int r2) {  
        // Math.sqrt:開平方  
        // Math.pow(double x, double y): X的Y次方  
        //直角坐標系,依點1和點2做平行線,|x1-x2|為橫向直角邊,|y1-y2|為縱向直角邊 依勾股定理 c^2=a^2+b^2  
        if (Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) <= r1 + r2) {  
            // 如果兩圓的圓心距小於或等於兩圓半徑和則認為發生碰撞  
            return true;  
        }  
        return false;  
    }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM