JakeTheSnake
JakeTheSnake

Reputation: 2464

When Objects "Hit" Each Other - Javascript

How can one keep track of when objects hit each other? Below is an example of a bullet (div) that flies around, hitting a triangle (svg polygon). How can one know when the bullet is within the green area of the triangle?

var left1 = parseInt(document.getElementById("bullet").style.left);
var left2 = 0; 

setInterval(bounce, 10);
function bounce() {
  if ( left1 < (window.innerWidth - 35) ) {
    left1++; 
    left2 = left1; 
    document.getElementById("bullet").style.left = left1 + "px"; 
    
  }
  if ( left1 >= (window.innerWidth -35) ) {
    left2--;
    document.getElementById("bullet").style.left = left2 + "px"; 
  }
  if ( left2 <= 0 ) {
    left1 = 0;   
  }
}
<div id="bullet" style="position:absolute; top:100px; width: 15px; height:15px; background-color: #000;"></div>
  
<svg height="200" width="200" style="position:absolute; top: 0px; left: 100px;">
  <polygon points="100,10 200,200 0,200" style="fill:#23ac6a;"/>  
</svg>

Upvotes: 0

Views: 123

Answers (1)

lukewestby
lukewestby

Reputation: 1207

The svg polygon element provides a property called points which returns the values specified in its points attribute as an array-like structure called an SVGPointList. Each element of the structure has an x and y property which is relative to the position and viewBox of the svg element. You can use those values to figure out the x and y coordinates of the bounds of the triangle in relation to your moving div and from there detect if any of the div's corners are inside the triangle.

So let's say your polygon has an id of triangle, you can get an array of those points with Array.prototype.slice.call(document.getElementById('triangle').points)

Upvotes: 1

Related Questions