-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
52dcbe9
commit fc0b7be
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
var pos = 0; | ||
const pacArray = [ | ||
['PacMan1.png', 'PacMan2.png'], | ||
['PacMan3.png', 'PacMan4.png'] | ||
]; | ||
var direction = 0; | ||
const pacMen = []; | ||
function setToRandom(scale) { | ||
return { | ||
x: Math.random() * scale, | ||
y: Math.random() * scale | ||
} | ||
} | ||
// Factory to make a PacMan at a random position with random velocity | ||
function makePac() { | ||
// returns an object with random values scaled {x: 33, y: 21} | ||
let velocity = setToRandom(10); // {x:?, y:?} | ||
let position = setToRandom(200); | ||
// Add image to div id = game | ||
let game = document.getElementById('game'); | ||
let newimg = document.createElement('img'); | ||
newimg.style.position = 'absolute'; | ||
newimg.src = 'PacMan1.png'; | ||
newimg.width = 100; | ||
newimg.style.left = position.x; | ||
newimg.style.top = position.y; | ||
game.appendChild(newimg); | ||
// return details in an object | ||
return { | ||
position, | ||
velocity, | ||
newimg | ||
} | ||
} | ||
|
||
function update() { | ||
//loop over pacmen array and move each one and move image in DOM | ||
pacMen.forEach((item) => { | ||
checkCollisions(item) | ||
item.position.x += item.velocity.x; | ||
item.position.y += item.velocity.y; | ||
|
||
item.newimg.style.left = item.position.x; | ||
item.newimg.style.top = item.position.y; | ||
}) | ||
setTimeout(update, 20); | ||
} | ||
|
||
function checkCollisions(item) { | ||
if (item.position.x + item.velocity.x + item.newimg.width > window.innerWidth || | ||
item.position.x + item.velocity.x < 0) item.velocity.x = -item.velocity.x; | ||
if (item.position.y + item.velocity.y + item.newimg.height > window.innerHeight || | ||
item.position.y + item.velocity.y < 0) item.velocity.y = -item.velocity.y; | ||
} | ||
|
||
function makeOne() { | ||
pacMen.push(makePac()); // adds a new PacMan | ||
} |