V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Corbusier

JS 检测碰撞的方法有哪些?

  •  
  •   Corbusier · May 20, 2017 · 2970 views
    This topic created in 3266 days ago, the information mentioned may be changed or developed.

    我写的是非常非常基础的根据其中一个 obj 页面元素的上下左右,与另一个 obj 页面元素的上下左右比较之后判断是否碰撞,具体代码如下。觉得这么写不是特别的高效,判断太多了,有没有好一点的方式?

    	function getRect(obj){
    		return obj.getBoundingClientRect();
    	}
    	function crash(obj1,obj2){
    		var first_Rect = getRect(obj1);
    		var second_rect = getRect(obj2);
    
    		var firstLeft = getRect(obj1).left;
    		var firstTop = getRect(obj1).top;
    		var firstRight = getRect(obj1).right;
    		var firstBottom = getRect(obj1).bottom;
    
    		var secondLeft = getRect(obj2).left;
    		var secondTop = getRect(obj2).top;
    		var secondRight = getRect(obj2).right;
    		var secondBottom = getRect(obj2).bottom;
    		if(firstLeft > secondRight||firstRight < secondLeft||firstTop > secondBottom||firstBottom < secondTop){
    			return false;
    		}else{
    			return true;
    		}
    	}
    
    2 replies    2017-05-20 10:50:50 +08:00
    Biwood
        1
    Biwood  
       May 20, 2017 via Android
    简单的碰撞检测就是这么写的,没有什么更好的办法,你可以在此基础上进行优化,比如用变量缓存坐标数据,减少 getBoundingClientRect 的执行次数
    Corbusier
        2
    Corbusier  
    OP
       May 20, 2017
    @Biwood 好的,感谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5162 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 05:40 · PVG 13:40 · LAX 22:40 · JFK 01:40
    ♥ Do have faith in what you're doing.