旋转两个元素之间的碰撞 [英] Collision between two elements with rotating

查看:195
本文介绍了旋转两个元素之间的碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-js lang-js prettyprint-override> var keys = new Array(); var direction; var direction; var iNr = 0; $(document).ready(function(){looper(); $(#demo1).css(margin-top,400 +px); $(#demo2).css(margin -left,380 +px); myFunction();});函数myFunction(){iNr = iNr + 0.5; $(#main).css(transition,全0.1s); $(#main).css(transform,rotate(+ iNr +deg)); setTimeout(function(){myFunction();},50); } function looper(){var p = $(#circle); var offset = p.offset(); var t = $(。red); var roffset = t.offset(); var rect1 = {x:offset.left,y:offset.top,width:p.width(),height:p.height()} var rect2 = {x:roffset.left,y:roffset.top,width: t.width(),height:t.height()} if(rect1.x 0){$(#circle)。css(top,($(#circle)。position() .top - 2)+px);如果(方向==右){if((offset.left + 50)< $(window).width()){$(#circle).css(left,($ #circle)。position()。left + 2)+px);如果(方向==向下){if((offset.top + 50)< $(window).height()){$(#circle).css(top,($ #circle)。position()。top + 2)+px); }} ID = window.setTimeout(looper();,1); } $(document).keyup(function(event){if(event.keyCode == 37){var index = keys.indexOf(37); keys.splice(index,1); direction =;} if(event.keyCode == 38){var index = keys.indexOf(38); keys.splice(index,1); direction =;} if(event.keyCode == 39){var index = keys.indexOf(39); keys.splice(index,1); direction =;} if(event.keyCode == 40){var index = keys.indexOf(40); keys.splice( index,1); direction =;}}); $(document).keydown(function(event){if(event.keyCode == 37){keys.push(37); direction =left;} if(event.keyCode == 38){keys。 push(38); direction =up;} if(event.keyCode == 39){keys.push(39); direction =right;} if(event.keyCode == 40){ keys.push(40); direction =down;}});

 <!doctype html>< html lang =en> < HEAD> < meta charset =utf-8> <标题>试验< /标题> < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script> < /头> < body style =background-color:black; overflow-y:scroll;> < div style =width:400px; margin-left:500px; height:400px; ID = 主 > < div id =demo1style =width:400px; height:20px; background-color:red; position:absolute; class =红色测试全部>< / div> < div id =demo2style =width:20px; height:400px; background-color:yellow; position:absolute; class =全部测试>< / div> < div id =demo3style =width:400px; height:20px; background-color:blue; position:absolute; class =全部测试>< / div> < div id =demo4style =width:20px; height:400px; background-color:green; position:absolute; class =全部测试>< / div> < / DIV> < div style =width:25px; height:25px; background-color:white; position:absolute; border-radius:50%; ID = 圆 >< / DIV> < / body>< / html>  

一个游戏。
在这个游戏中,我的函数检查 div1 div2 之间是否存在冲突。
或者如果它们重叠或者如此...你想拼写它的方式。
如果没有轮换,一切都可以。



但现在我遇到了问题。
我想用 transform:rotate(Xdeg);

旋转 div2

<但是如果我这样做的话,我对碰撞的计算就没有用了。

我用这个:

  var rect1 = {x:5,y:5,width:50,height:50} 
var rect2 = {x:20,y:10,width:10,身高:10}

if(rect1.x //检测到碰撞!
}

你有什么想法解决这个问题吗?



感谢您的帮助: - )

解决方案

有几种方法可以做到这一点。这个例子只是指导你如何用矩形完成。



这些是在这里完成的步骤:




  • 您必须计算所有矩形的所有旋转角的位置,以检查它们是否正在碰撞。要获得这些旋转的角落,您可以使用几种方法。在这个例子中,使用了2d向量和2d旋转矩阵:


    • 一个向量,其起点位于中心矩形的左上角(x,y):

        var center = {
      x:x + width / 2,
      y:y + height / 2
      };

      var vector = {
      x:(x - center.x),
      y:(y - center.y)
      };


    • 将此向量与旋转矩阵相乘以旋转此向量:

        // //修正sin函数以单位度数而不是弧度计算罪恶
      函数sin(x){
      return Math .sin(x / 180 * Math.PI);


      //修改后的cos函数
      函数cos(x){
      return Math.cos(x / 180 * Math.PI);
      }

      var rotationMatrix = [[cos(angle),-sin(angle)],[sin(angle),cos(angle)]];

      var rotatedVector = {
      x:vector.x * rotationMatrix [0] [0] + vector.y * rotationMatrix [0] [1],
      y:vector.x * rotationMatrix [1] [0] + vector.y * rotationMatrix [1] [1]
      };


    • 最后得到旋转的左上角,您可以从中心开始一个矩形,并转到旋转的矢量指向的位置。这是转动后左上角的位置:

        {
      x:(center.x + rotatedVector。
      y:(center.y + rotatedVector.y)
      }


    • 上述所有步骤均由 getRotatedTopLeftCornerOfRect 完成,并且必须与其他所有角落一起完成。在下一个
      转角(右上角)的位置可以计算出来之前,下一个矢量必须被指向这个角落的calulcated。为了得到指向右上角的下一个矢量,计算第一个矢量(左上角)和第二个矢量(右上角)之间的角度。第三个矢量指向右下角时,其角度增加第一个角度,第二个角度和第四个矢量旋转角度,第一个角度,第二个角度和第三个角度相加。所有这些都在 setCorners - 方法中完成,并且此图像部分显示了此过程:

    • / ul>







      • 为了检测碰撞,有很多算法。在这个例子中,点多边形算法用于检查矩形的每个旋转角落,无论是拐角与边界或另一个矩形内,如果是,则方法 isCollided 返回true。多边形算法中的点用于 pointInPoly 中,也可以找到这里



      结合上述所有步骤都很棘手,但它适用于所有所有矩形大小和最好的,你可以通过点击运行代码片段在没有库的情况下在这里进行测试。


      $ b

      经过测试的浏览器:FF 50.1.0,IE:10-EDGE,Chrome:55.0.2883.87 m ):



      var Rectangle =(function(){function sin(x){return Math.sin(x / 180 * Math.PI);} function cos(x){return Math.cos(x / 180 * Math.PI);} function getVectorLength(x,y,width,height){var center = {x:x + width / 2,y:y + height / 2}; //console.log('center:',center); var vector = {x:(x - center.x),y:(y - center.y) }; return Math.sqrt(vector.x * vector.x + vector.y * vector.y);} getRotatedTopLeftCornerOfRect(x,y,width,height,angle){var center = { x:x + width / 2,y:y + height / 2}; //console.log('center:',center); var vector = {x:(x - center.x),y:(y - center.y)}; //console.log('vector:',vector); var rotationMatrix = [[cos(角度),-sin(角度)],[sin(角度),cos(角度)]]; //console.log('rotationMatrix:',rotationMatrix); var rotationVector = {x:vector.x * rotationMatrix [0] [0] + vector.y * rotationMatrix [0] [1],y:vector.x * rotationMatrix [1] [0] + vector.y * rotationMatrix [ 1] [1]}; //console.log('rotatedVector:',rotatedVector); return {x:(center.x + rotatedVector.x),y:(center.y + rotatedVector.y)}; } function getOffset(el){var _x = 0; var _y = 0;同时(el&!isNaN(el.offsetLeft)&!isNaN(el.offsetTop)){_x + = el.offsetLeft - el.scrollLeft; _y + = el.offsetTop - el.scrollTop; el = el.offsetParent; } return {top:_y,left:_x}; }函数pointInPoly(verties,testx,testy){var i,j,c = 0 nvert = verties.length;对于(i = 0,j = nvert-1; i testy)!=(verties [j] .y> testy)) &&(testx<(verties [j] .x - verties [i] .x)*(testy-verties [i] .y)/(verties [j] .y - verties [i] .y) + verties [i] .x))c =!c; } return c; }函数Rectangle(htmlElement,width,height,angle){this.htmlElement = htmlElement; this.width = width; this.height = height; this.setCorners(角度); } function testCollision(rectangle){var collision = false; this.getCorners()。forEach(function(corner){var isCollided = pointInPoly(rectangle.getCorners(),corner.x,corner.y); if(isCollided)collision = true;});返回碰撞; } function checkRectangleCollision(rect,rect2){if(testCollision.call(rect,rect2))return true; else if(testCollision.call(rect2,rect))返回true;返回false; } function getAngleForNextCorner(anc,vectorLength){var alpha = Math.acos(anc / vectorLength)*(180 / Math.PI);返回180 - alpha * 2; } Rectangle.prototype.setCorners = function(angle){this.originalPos = getOffset(this.htmlElement); this.leftTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left,this.originalPos.top,this.width,this.height,angle); var vecLength = getVectorLength(this.originalPos.left,this.originalPos.top,this.width,this.height); //console.log('vecLength:',vecLength); angle = angle + getAngleForNextCorner(this.width / 2,vecLength); //console.log('angle:',angle); this.rightTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left,this.originalPos.top,this.width,this.height,angle); angle = angle + getAngleForNextCorner(this.height / 2,vecLength); //console.log('angle:',angle); this.rightBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left,this.originalPos.top,this.width,this.height,angle); angle = angle + getAngleForNextCorner(this.width / 2,vecLength); //console.log('angle:',angle); this.leftBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left,this.originalPos.top,this.width,this.height,angle); //console.log(this); }; Rectangle.prototype.getCorners = function(){return [this.leftTopCorner,this.rightTopCorner,this.rightBottomCorner,this.leftBottomCorner]; }; Rectangle.prototype.isCollided = function(rectangle){return checkRectangleCollision(this,rectangle); };返回矩形; })(); var rotA = 16; var widthA = 150; var heightA = 75; var htmlRectA = document.getElementById('rectA'); var rotB = 28.9; var widthB = 50; var heightB = 130; var htmlRectB = document.getElementById('rectB'); var msgDiv = document.getElementById('msg'); var rectA = new Rectangle(htmlRectA,widthA,heightA,rotA); var rectB = new Rectangle(htmlRectB,widthB,heightB,rotB); window.requestAnimFrame = function(){return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; }();函数draw(){rotA + = 1.2; ('+ rotA +'deg); - webkit-transform:rotate rotB + = 5.5; htmlRectB.setAttribute('style',' - ms-transform:rotate('+ rotB +'deg); - webkit-transform:rotate('+ rotB +'deg); transform:rotate('+ rotB +'deg)'); rectA.setCorners(ROTA); rectB.setCorners(rotB); if(rectA.isCollided(rectB)){msgDiv.innerHTML ='Collision detected!'; msgDiv.setAttribute('style','color:#FF0000'); } else {msgDiv.innerHTML ='不碰撞!'; msgDiv.setAttribute('style','color:#000000'); } setTimeout(function(){window.requestAnimFrame(draw);},50); } window.requestAnimFrame(draw);

      #rectA {background -color:#0000FF;宽度:150像素;高度:960x75像素;位置:绝对的;顶部:60像素;左:180像素; -ms-transform:rotate(16deg); -webkit-transform:rotate(16deg); transform:rotate(16deg);}#rectB {background-color:#FF0000;宽度:50像素;高度:130px;位置:绝对的;顶:140px;左:250像素; -ms-transform:rotate(28.9deg); -webkit-transform:rotate(28.9deg); transform:rotate(28.9deg);}

      < div id =rectA> A< / div>< div id =rectB> B< / div>< div id =msg>< / div> / pre>


      var keys = new Array();
      	var direction;
      	var direction;
      	var iNr = 0;
      	
      	$(document).ready(function(){
      		looper();
      		$("#demo1").css("margin-top", 400 + "px");
      		$("#demo2").css("margin-left", 380 + "px");
      		myFunction();
      	});
      	
      	function myFunction()
      	{
      		iNr = iNr + 0.5;
      		$("#main").css("transition","all 0.1s");
      		$("#main").css("transform","rotate(" + iNr + "deg)");
      		
      		
      		setTimeout(function()
      		{
      			myFunction();
      		}, 50);
      	
      	}
      	
      	function looper()
      	{	
      		var p =$("#circle");
      		var offset = p.offset();
      		var t =$(".red");
      		var roffset = t.offset();
      		
      		var rect1 = {x: offset.left, y: offset.top, width: p.width(), height: p.height()}
      		var rect2 = {x: roffset.left, y: roffset.top, width: t.width(), height: t.height()}
      
      		if (rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y) {
      			
      			console.log("now");
      		}
      		
      		if(direction == "left")
      		{
      			if(offset.left - 50 > 0)
      			{
      				$("#circle").css("left", ($("#circle").position().left - 2) + "px");
      			}
      		}
      		if(direction == "up")
      		{
      			if(offset.top - 50 > 0)
      			{
      				$("#circle").css("top", ($("#circle").position().top - 2) + "px");
      			}
      		}
      		if(direction == "right")
      		{
      			if((offset.left + 50) < $(window).width())
      			{
      				$("#circle").css("left", ($("#circle").position().left + 2) + "px");
      			}
      		}
      		if(direction == "down")
      		{
      			if((offset.top + 50) < $(window).height())
      			{
      				$("#circle").css("top", ($("#circle").position().top + 2) + "px");
      			}
      		}
      		
      		
      		
      		ID=window.setTimeout("looper();", 1);
      	}
      
      	
      	$(document).keyup(function(event) {
      		
      		if (event.keyCode == 37)
      		{
      			var index = keys.indexOf("37");
      			keys.splice(index, 1);
      			direction = "";
      		}
      		if (event.keyCode == 38)
      		{
      			var index = keys.indexOf("38");
      			keys.splice(index, 1);
      			direction = "";
      		}
      		if (event.keyCode == 39)
      		{
      			var index = keys.indexOf("39");
      			keys.splice(index, 1);
      			direction = "";
      		}
      		if (event.keyCode == 40)
      		{
      			var index = keys.indexOf("40");
      			keys.splice(index, 1);
      			direction = "";
      		}
      	});
      	
      	$(document).keydown(function(event) {
      		
      		if (event.keyCode == 37)
      		{
      			keys.push("37");
      			direction = "left";
      		}
      		if (event.keyCode == 38)
      		{
      			keys.push("38");
      			direction = "up";
      		}
      		if (event.keyCode == 39)
      		{
      			keys.push("39");
      			direction = "right";
      		}
      		if (event.keyCode == 40)
      		{
      			keys.push("40");
      			direction = "down";
      		}
      	});

      <!doctype html>
      <html lang="en">
      
      	<head>
      		<meta charset="utf-8">
      		<title>test</title>
      
      		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      		
      	</head>
      	
      	
      	<body style="background-color:black; overflow-y:scroll;">
      	
      		<div style="width:400px; margin-left:500px; height:400px;" id="main">
      			<div id="demo1" style="width:400px; height:20px; background-color:red; position:absolute;" class="red test all"></div>
      			<div id="demo2" style="width:20px; height:400px; background-color:yellow; position:absolute;" class="test all"></div>
      			<div id="demo3" style="width:400px; height:20px; background-color:blue; position:absolute;" class="test all"></div>
      			<div id="demo4" style="width:20px; height:400px; background-color:green; position:absolute;" class="test all"></div>
      		</div>
      		
      		<div style="width:25px; height:25px; background-color:white; position:absolute; border-radius:50%;" id="circle"></div>
      	
      	</body>
      </html>

      I have programmed a game. In this game my function checks, whether there is a collision between div1 and div2. Or if they are overlapping or so... how you want to spell it. Without a rotation everything is ok.

      But now i have a problem. I want to rotate div2 with transform:rotate(Xdeg);

      but if I do this my calculation for the collision dosen't work.

      I use this:

      var rect1 = {x: 5, y: 5, width: 50, height: 50}
      var rect2 = {x: 20, y: 10, width: 10, height: 10}
      
      if (rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y) {
          // collision detected!
      }
      

      do you have any ideas to solve this problem?

      Thanks for helping :-)

      解决方案

      There are several ways to do this. This example just guides you of how it could be done with rectangles.

      These are the steps that are done here:

      • You have to calculate the position of all rotated corners of all rectangles that you want to check whether they are being collided. To get these rotated corners, you can use several methods. In this example 2d-vectors and a 2d-rotation-matrix are used:

        • a vector that has its origin in the center of a rectangle and directs to the top-left-corner(x,y) of a rectangle:

          var center = {
              x: x + width / 2,
              y: y + height / 2
          };
          
          var vector = {
              x: (x - center.x),
              y: (y - center.y)
          };
          

        • multiply this vector with a rotation-matrix to rotate this vector:

          // modified sin function to calulcate sin in the unit degrees instead of radians
          function sin(x) {
             return Math.sin(x / 180 * Math.PI);
          }
          
          // modified cos function 
          function cos(x) {
             return Math.cos(x / 180 * Math.PI);
          }
          
          var rotationMatrix = [[cos(angle), -sin(angle)],[sin(angle), cos(angle)]];
          
          var rotatedVector = {
              x: vector.x * rotationMatrix[0][0] + vector.y * rotationMatrix[0][1],
              y: vector.x * rotationMatrix[1][0] + vector.y * rotationMatrix[1][1]
          };
          

        • And finally get the rotated top-left-corner, you can start from the center of a rectangle and go to where the rotated vector points to. This is where top-left-corner is located after rotation:

          {
              x: (center.x + rotatedVector.x),
              y: (center.y + rotatedVector.y)
          }
          

        • All the steps described above are done by getRotatedTopLeftCornerOfRect and must be done with all other corners as well. Before the location of the next corner (right-top) can be calculated next vector must be calulcated that points to this corner. To get the next vector that points to the top-right-corner the angle between the first vector (left-top) and the second vector (right-top) is calculated. The third vector points to the right-bottom-corner when its angle is incremended by the first angle and the second angle and the fourth vector is rotated by an angle that is summed up the first, second and third angle. All of this is done in the setCorners-method and this image shows this process partly:


      • To detect a collision there are tons of algorithms. In this example the Point in polygon algorithm is used to check each rotated corner of a rectangle whether a corner is with the border or within another rectangle, if so, then the method isCollided returns true. The Point in polygon algorithm is used in pointInPoly and can also be found here.

      Combining all of the steps described above was tricky, but it works with all rectangles of all sizes and the best of all you can test it right here without a library by clicking on "Run code snippet".

      (tested browsers: FF 50.1.0, IE:10-EDGE, Chrome:55.0.2883.87 m):

          var Rectangle = (function () {
      
              function sin(x) {
                  return Math.sin(x / 180 * Math.PI);
              }
      
              function cos(x) {
                  return Math.cos(x / 180 * Math.PI);
              }
      
              function getVectorLength(x, y, width, height){
                  var center = {
                      x: x + width / 2,
                      y: y + height / 2
                  };
                  //console.log('center: ',center);
                  var vector = {
                      x: (x - center.x),
                      y: (y - center.y)
                  };
                  return Math.sqrt(vector.x*vector.x+vector.y*vector.y);
              }
      
              function getRotatedTopLeftCornerOfRect(x, y, width, height, angle) {
                  var center = {
                      x: x + width / 2,
                      y: y + height / 2
                  };
                  //console.log('center: ',center);
                  var vector = {
                      x: (x - center.x),
                      y: (y - center.y)
                  };
                  //console.log('vector: ',vector);
                  var rotationMatrix = [[cos(angle), -sin(angle)],[sin(angle), cos(angle)]];
                  //console.log('rotationMatrix: ',rotationMatrix);
                  var rotatedVector = {
                      x: vector.x * rotationMatrix[0][0] + vector.y * rotationMatrix[0][1],
                      y: vector.x * rotationMatrix[1][0] + vector.y * rotationMatrix[1][1]
                  };
                  //console.log('rotatedVector: ',rotatedVector);
                  return {
                      x: (center.x + rotatedVector.x),
                      y: (center.y + rotatedVector.y)
                  };
              }
      
              function getOffset(el) {
                  var _x = 0;
                  var _y = 0;
                  while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
                      _x += el.offsetLeft - el.scrollLeft;
                      _y += el.offsetTop - el.scrollTop;
                      el = el.offsetParent;
                  }
                  return {
                      top: _y,
                      left: _x
                  };
              }
      
              function pointInPoly(verties, testx, testy) {
                  var i,
                          j,
                          c = 0
                  nvert = verties.length;
                  for (i = 0, j = nvert - 1; i < nvert; j = i++) {
                      if (((verties[i].y > testy) != (verties[j].y > testy)) && (testx < (verties[j].x - verties[i].x) * (testy - verties[i].y) / (verties[j].y - verties[i].y) + verties[i].x))
                          c = !c;
                  }
                  return c;
              }
      
              function Rectangle(htmlElement, width, height, angle) {
                  this.htmlElement = htmlElement;
                  this.width = width;
                  this.height = height;
                  this.setCorners(angle);
              }
      
              function testCollision(rectangle) {
                  var collision = false;
                  this.getCorners().forEach(function (corner) {
                      var isCollided = pointInPoly(rectangle.getCorners(), corner.x, corner.y);
                      if (isCollided) collision = true;
                  });
                  return collision;
              }
      
              function checkRectangleCollision(rect, rect2) {
                  if (testCollision.call(rect, rect2)) return true;
                  else if (testCollision.call(rect2, rect)) return true;
                  return false;
              }
      
              function getAngleForNextCorner(anc,vectorLength) {
                  var alpha = Math.acos(anc/vectorLength)*(180 / Math.PI);
                  return 180 - alpha*2;
              }
      
              Rectangle.prototype.setCorners = function (angle) {
                  this.originalPos = getOffset(this.htmlElement);
                  this.leftTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
      
                  var vecLength = getVectorLength(this.originalPos.left, this.originalPos.top, this.width, this.height);
                  //console.log('vecLength: ',vecLength);
      
                  angle = angle+getAngleForNextCorner(this.width/2, vecLength);
                  //console.log('angle: ',angle);
                  this.rightTopCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
      
                  angle = angle+getAngleForNextCorner(this.height/2, vecLength);
                  //console.log('angle: ',angle);
                  this.rightBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
      
                  angle = angle+getAngleForNextCorner(this.width/2, vecLength);
                  //console.log('angle: ',angle);
                  this.leftBottomCorner = getRotatedTopLeftCornerOfRect(this.originalPos.left, this.originalPos.top, this.width, this.height, angle);
      
                  //console.log(this);
              };
      
              Rectangle.prototype.getCorners = function () {
                  return [this.leftTopCorner,
                      this.rightTopCorner,
                      this.rightBottomCorner,
                      this.leftBottomCorner];
              };
      
              Rectangle.prototype.isCollided = function (rectangle) {
                  return checkRectangleCollision(this, rectangle);
              };
      
              return Rectangle;
      
          }) ();
      
      
          var rotA = 16;
          var widthA = 150;
          var heightA = 75;
          var htmlRectA = document.getElementById('rectA');
      
          var rotB = 28.9;
          var widthB = 50;
          var heightB = 130;
          var htmlRectB = document.getElementById('rectB');
      
          var msgDiv = document.getElementById('msg');
      
          var rectA = new Rectangle(htmlRectA, widthA, heightA, rotA);
          var rectB = new Rectangle(htmlRectB, widthB, heightB, rotB);
      
          window.requestAnimFrame = function(){
              return  window.requestAnimationFrame       ||
                      window.webkitRequestAnimationFrame ||
                      window.mozRequestAnimationFrame    ||
                      window.oRequestAnimationFrame      ||
                      window.msRequestAnimationFrame;
          }();
      
          function draw(){
      
              rotA+=1.2;
              htmlRectA.setAttribute('style','-ms-transform: rotate('+rotA+'deg);-webkit-transform: rotate('+rotA+'deg);transform: rotate('+rotA+'deg)');
      
              rotB+=5.5;
              htmlRectB.setAttribute('style','-ms-transform: rotate('+rotB+'deg);-webkit-transform: rotate('+rotB+'deg);transform: rotate('+rotB+'deg)');
      
              rectA.setCorners(rotA);
              rectB.setCorners(rotB);
      
              if(rectA.isCollided(rectB)){
                  msgDiv.innerHTML = 'Collision detected!';
                  msgDiv.setAttribute('style','color: #FF0000');
              }
              else {
                  msgDiv.innerHTML = 'No Collision!';
                  msgDiv.setAttribute('style','color: #000000');
              }
      
              setTimeout(function(){
                  window.requestAnimFrame(draw);
              },50);
          }
      
          window.requestAnimFrame(draw);

      #rectA{
              background-color: #0000FF;
              width:150px;
              height:75px;
              position:absolute;
      
              top:60px;
              left:180px;
      
              -ms-transform: rotate(16deg);
              -webkit-transform: rotate(16deg);
              transform: rotate(16deg);
      }
      
      #rectB{
              background-color: #FF0000;
              width:50px;
              height:130px;
              position:absolute;
      
              top:140px;
              left:250px;
      
              -ms-transform: rotate(28.9deg);
              -webkit-transform: rotate(28.9deg);
              transform: rotate(28.9deg);
      
      }

      <div id="rectA">A</div>
      <div id="rectB">B</div>
      
      <div id="msg"></div>

      这篇关于旋转两个元素之间的碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆