64 Polygons - JcerelusDev/CanvasGameJs GitHub Wiki

PolyGons

PolyGons is a constructor that allows us to create non-complexe polygon shape or (convex polygon). It is useful if you want to create a polygon's based game.

Polygon based Space-invaders

How to create a polygon

It has 9 parameters :

PolyGons(startX, startY, sides, radius, color, angle, speedX, speedY,fill)

startX = x position

startY = y position

sides = number sides to create the shape

radius = the size of the polygon

color = color of the shape

angle = angle

speedX = the speed in x axis

speedY = the speed in y axis

fill = is a boolean to fill the shape with color if set to true, by default it is false and the shape is stroked

Example :

const player = new PolyGons(30,70,3,13,"red",0,0,0,true)

How to draw ?

 player.draw()

How to update automatically ?

To update automatically you need to provide speedX to update on x axis and speedY on y axis

to go to the left use negative value to go to the right use positive value

// the following will go to the left
const player = new PolyGons(30,70,3,13,"red",0,-2,0,true)
 player.update()

Good to know :

if you want the shape to autorotate give the angle a value greater or less then 0

How to check collision

There's a method called : polygon.checkCollision(otherPolygon)

to be clear see the following :

 
 const player = new PolyGons(30,70,3,13,"red",0,1,0,true)
 
 const enemy = new PolyGons(330,70,3,13,"white",0,-2,0,false)
 
 //in the update function do the following
 
 game.update = function(){
   if(player.checkCollision(enemy)){
      player.lives--
   }
 
 }
 
 

the code above check if the player collided with the enemy then remove 1 from the player's life.

How to check collision between a polygon shape and non-polygon shape (rectangle, circle) ?

To detect collision between a polygon and another type of shape use the following :

isCollideBoxPolygon(pol,obj)

pol = the polygon shape

obj = the non-polygon shape

const player = new PolyGons(30,70,3,13,"red",0,-2,0,true)

const enemy = new Sprite(230,70,32,32,5,0,"blue")


if(isCollideBoxPolygon(player,enemy)){
   player.lives--

}

Important :

The addBullet is still usable, but addBulletIm is not taking into account Look for how to use addBullet