Won't let me set class name of a Javascript created div - javascript

I'm using a function to create a div element on the page. I want to assign a className but I get the error: cannot set property className of undefined.
But I did this in another function and it worked. Why is this one not working?
If I failed to provide the code relevant to the problem I apologize. I'm in a rush and included code that I thought might be relevant in order of relevancy.
** WORKING FUNCTION **
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb'; //DOESN'T THROW ERROR ----
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
** NOT WORKING FUNCTION **
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet'; //THROWS ERROR -----
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x +
(player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y +
(player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
** STARTING CODE THAT MIGHT HAVE CONTEXT IDK**
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
** OTHER CODE THAT MIGHT HAVE CONTEXT **
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * .
gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
** JUST IN CASE YOU NEED -- idk its hard for me to keep track of everything that might be related to the problem... sorry.. **
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
** FULL JS FILE: BE WARNED IM VERY NEW AND THIS IS NOT GOOD CODE **
const title = document.querySelector(".title");
const gameMessage = document.querySelector(".gameMessage");
function changeColor() {
let newArray = ["darksalmon", "lightsalmon", "crimson", "red", "deeppink", "yellowgreen", "ghostwhite"];
let random = Math.floor(Math.random() * Math.floor(newArray.length - 1));
if (title.style.color != newArray[random]) {
title.style.color = newArray[random];
console.log(title.style.color);
} else {
changeColor();
}
}
title.addEventListener("click", changeColor);
const gameArea = document.querySelector(".gameArea");
const game = document.querySelector(".game");
const scoreArea = document.querySelector(".scoreArea");
const score = document.querySelector(".score");
const text = document.querySelector(".text");
document.addEventListener('keydown', pressOn);
document.addEventListener('keyup', pressOff);
gameMessage.addEventListener('click', start);
let player = {
score: 2000,
speed: 5,
inplay: false,
ready: true,
maxBombs: 4,
hasBomb: 0,
hit: 0,
hitMax: 9,
games: 0,
enemy: {
x: 0
},
getHit: 0,
getHitMax: 20,
swing: false
}
let keys = {
space: false
}
function start() {
if (player.games === 1) {
gameArea.removeChild(finalScore);
}
gameMessage.style.display = 'none';
score.style.display = "inline-block";
scoreArea.style.display = "inline-block";
text.style.display = "inline-block";
player.inplay = true;
makeEnemy();
player.plane = document.createElement("div");
player.plane.setAttribute("class", "plane");
gameArea.appendChild(player.plane);
player.enemy.x = player.enemy.offsetLeft;
player.enemy.y = player.enemy.offsetTop;
player.x = player.plane.offsetLeft;
player.y = player.plane.offsetTop;
window.requestAnimationFrame(playGame);
}
function playGame() {
if (player.inplay) {
moveBomb();
if(player.x < (gameArea.offsetWidth / 2)) {
console.log('WORKED');
makeBullet();
}
if (player.swing){
player.plane.style.backgroundImage ='url(guts1.png)';
player.swing = false;
//player.plane.style.width = 210 + 'px';
}
if (keys['x'] && player.enemy && isCollide(player.plane, player.enemy)) {
removeEnemy();
}
if (player.enemy) {
if (isCollide(player.plane, player.enemy)) {
player.getHit++;
if (player.getHit > player.getHitMax){
endGame();
}
} else {
player.getHit = 0;
}
if (player.x > player.enemy.x) {
player.enemy.x += 1;
}
if (player.x < player.enemy.x) {
player.enemy.x -= 1;
}
player.enemy.style.left = player.enemy.x + 'px';
}
if (player.hasBomb >= player.maxBombs && player.bomb.y > gameArea.offsetHeight - 20) {
endGame();
}
if (keys.space) {
makeBomb()
}
if (keys.ArrowUp && player.y > 0) {
player.y -= (player.speed + (player.speed * .5));
}
if (keys.ArrowDown && player.y < (gameArea.offsetHeight - player.plane.offsetHeight - 30)) {
player.y += (player.speed + (player.speed * .5));
}
if (keys.ArrowLeft && player.x > 0) {
player.x -= (player.speed + (player.speed * .5));
}
if (keys.ArrowRight && player.x < (gameArea.offsetWidth)) {
player.x += (player.speed - (player.speed * .5));
}
if (player.x == (gameArea.offsetWidth)) {
player.x = 0;
player.score -= 100;
if (!player.enemy) {
makeEnemy();
}
}
player.score -= .4;
if (player.score < 0) {
player.score = 0;
}
player.x += (player.speed * .5);
score.innerHTML = Math.floor(player.score) + ' Bombs left: ' + (player.maxBombs - player.hasBomb);
player.plane.style.left = player.x + 'px';
player.plane.style.top = player.y + 'px';
window.requestAnimationFrame(playGame);
}
}
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false){
playerPlane = player.plane;
player.plane.style.backgroundImage ='url(guts2.png)';
setTimeout(function () {
player.swing = true;
}, 300);
//player.plane.style.width = 400 + 'px';
}
console.log(tempKey)
console.log(keys);
}
function pressOff(e) {
e.preventDefault();
let tempKey = (e.key== " ") ? "space" : e.key;
console.log(tempKey);
// if (keys['x'] && player.swing){
// playerPlane = player.plane;
// player.plane.style.backgroundImage ='url(guts1.png)';
// player.swing = false;
// //player.plane.style.width = 210 + 'px';
//
// }
if (keys['space'] || keys['x']) {
keys['space'] = 0;
keys['x'] = 0;
}
keys[tempKey] = false;
console.log(keys);
}
function moveBomb() {
let bombs = document.querySelectorAll('.bomb');
bombs.forEach(function (item) {
item.y += 10;
item.style.top = item.y + 'px';
if (item.y > gameArea.offsetHeight) {
item.parentNode.removeChild(item);
player.bomb = null;
}
if (player.enemy && player.bomb) {
if (isCollide(item, player.enemy)) {
player.hit++;
}
}
if (player.hit > player.hitMax) {
item.parentNode.removeChild(item);
player.bomb = null;
player.score += 2000;
player.hit = 0;
player.hasBomb -= 2
gameArea.removeChild(player.enemy);
player.enemy = null;
}
})
}
function makeEnemy() {
player.enemy = document.createElement('div');
player.enemy.className = 'enemy';
player.enemy.style.left = Math.floor(Math.random() * gameArea.offsetWidth - 300) + 100 + 'px';
gameArea.appendChild(player.enemy);
player.enemy.x = player.enemy.offsetLeft;
}
//function getLocationX(a){
// let aRect = a.getBoundingClientRect();
// let aX = aRect.x;
// return aX;
// //w console.log(aX);
//}
//
//function getLocationY(a){
// let aRect = a.getBoundingClientRect();
// let aY = aRect.y;
// return aY;
// // console.log(aY);
//}
function isCollide(a, b) {
let aRect = a.getBoundingClientRect();
let bRect = b.getBoundingClientRect();
return !(
(aRect.bottom < bRect.top) ||
(aRect.top > bRect.bottom) ||
(aRect.right < bRect.left) ||
(aRect.left > bRect.right)
)
}
function makeBomb() {
if (player.ready && (player.hasBomb < player.maxBombs)) {
player.score -= 300;
player.hasBomb++;
player.bomb = document.createElement('div');
player.bomb.className = 'bomb';
gameArea.appendChild(player.bomb);
player.bomb.x = player.x;
player.bomb.y = player.y;
player.bomb.style.left = player.bomb.x + 'px';
player.bomb.style.top = player.bomb.y + 'px';
player.ready = false;
setTimeout(function () {
player.ready = true;
}, 1000);
}
}
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount && player.enemy.bulletInterval == true)
player.enemy.bullet = document.createElement('div');
player.enemy.bullet.className = 'bullet';
gameArea.appendChild(player.enemy.bullet);
player.enemy.bullet.x = player.enemy.x;
player.enemy.bullet.y = player.enemy.y;
player.enemy.bullet.style.left = player.enemy.bullet.x + (player.enemy.offsetWidth / 3) + 'px';
player.enemy.bullet.style.top = player.enemy.bullet.y + (player.enemy.offsetHeight / 4) + 'px';
player.enemy.bulletCount++;
player.enemy.bulletInterval = false;
setInterval(function(){
player.enemy.bulletInterval = true;
}, 4000);
}
function endGame() {
if (player.enemy) {
gameArea.removeChild(player.enemy);
}
gameArea.removeChild(player.plane);
if (player.bomb){
gameArea.removeChild(player.bomb);
player.bomb = null;
}
score.style.display = 'none';
scoreArea.style.display = 'none';
text.style.display = 'none';
gameMessage.style.display = 'inline-block';
player.inplay = false;
player.hasBomb = 0;
finalScore = document.createElement('div');
finalScore.classList.add('finalScore');
finalScore.innerHTML = 'YOU SCORED: ' + Math.floor(player.score);
gameArea.appendChild(finalScore);
player.games = 1;
player.getHit = 0;
}
function removeEnemy() {
gameArea.removeChild(player.enemy);
player.enemy = null;
player.score += 2000;
}

function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true)
youre missing curly braces at the end of the if statement and i think its interpretting the next line as a part single line if statement
change to
function makeBullet() {
if (player.enemy.bulletCount < player.enemy.maxBulletCount &&
player.enemy.bulletInterval == true) {
...
...
...
}
}

Related

im trying to increment the score by 10 only when the end of myCar passes the end of enemyCar

Im trying to increment the score by 10 only when the end of myCar passes the end of enemyCar. The score should be incremented by 10 at each passing and each time i reload it I can't seem to start with 0 score or the whole score just disappears:
Here's my code below:
<script>
const score = document.querySelector(".score");
const startScreen = document.querySelector(".startScreen");
const gameArea = document.querySelector(".gameArea");
startScreen.addEventListener("click", initializeGame);
let player = { speed: 5, score: 0 };
let keys = {
ArrowUp: false,
ArrowDown: false,
ArrowLeft: false,
ArrowRight: false,
};
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
function keyDown(e) {
e.preventDefault();
keys[e.key] = true;
}
function keyUp(e) {
e.preventDefault();
keys[e.key] = false;
}
function isCollide(a, b) {
aRect = a.getBoundingClientRect();
bRect = b.getBoundingClientRect();
return !(
aRect.bottom < bRect.top ||
aRect.top > bRect.bottom ||
aRect.right < bRect.left ||
aRect.left > bRect.right
);
}
function moveLines() {
let lines = document.querySelectorAll(".lines");
lines.forEach(function (item) {
if (item.y >= 700) {
item.y -= 750;
}
item.y += player.speed;
item.style.top = item.y + "px";
});
}
function endGame() {
clearInterval(timer);
player.start = false;
startScreen.classList.remove("hide");
startScreen.innerHTML =
"Game over <br> Your final score is " +
player.score +
" <br> press here to restart the game.";
}
function moveEnemy(myCar) {
let enemyCarList = document.querySelectorAll(".enemyCar");
enemyCarList.forEach(function (enemyCar) {
if (isCollide(myCar, enemyCar)) {
endGame();
}
if (enemyCar.y >= 750) {
enemyCar.y = -300;
enemyCar.style.left = Math.floor(Math.random() * 350) + "px";
}
// Here's the problem when i try to execute it doesn't show anything
if (myCar.x + myCar.y < enemyCar.x + enemyCar.y) {
player.score += 10;
}
enemyCar.y += player.speed;
enemyCar.style.top = enemyCar.y + "px";
});
}
function runGame() {
let car = document.querySelector(".myCar");
let road = gameArea.getBoundingClientRect();
if (player.start) {
moveLines();
moveEnemy(car);
if (keys.ArrowUp && player.y > road.top + 150) {
player.y -= player.speed;
}
if (keys.ArrowDown && player.y < road.bottom - 85) {
player.y += player.speed;
}
if (keys.ArrowLeft && player.x > 0) {
player.x -= player.speed;
}
if (keys.ArrowRight && player.x < road.width - 50) {
player.x += player.speed;
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
window.requestAnimationFrame(runGame);
player.score++;
score.innerText =
"Score: " + player.score + "\nSpeed: " + player.speed;
}
}
function initializeGame() {
startScreen.classList.add("hide");
gameArea.innerHTML = "";
player.start = true;
player.score = 0;
window.requestAnimationFrame(runGame);
for (x = 0; x < 5; x++) {
let roadLine = document.createElement("div");
roadLine.setAttribute("class", "lines");
roadLine.y = x * 150;
roadLine.style.top = roadLine.y + "px";
gameArea.appendChild(roadLine);
}
let car = document.createElement("div");
car.setAttribute("class", "myCar");
gameArea.appendChild(car);
player.x = car.offsetLeft;
player.y = car.offsetTop;
for (x = 0; x < 3; x++) {
let enemyCar = document.createElement("div");
enemyCar.setAttribute("class", "enemyCar");
enemyCar.y = (x + 1) * 350 * -1;
enemyCar.style.top = enemyCar.y + "px";
enemyCar.style.left = Math.floor(Math.random() * 350) + "px";
gameArea.appendChild(enemyCar);
}
}
</script>
I tried to put this in the function moveEnemy(myCar) but it doesn't work
if (myCar.x + myCar.y < enemyCar.x + enemyCar.y) {
player.score += 10;
}

I do not know how to limit the time in between calling my function

//let screenWidth = window.screen.width;
//let screenHeight = window.screen.height;
let screenWidth = 800;
let screenHeight = 600;
let assets = {};
let frames = 60;
let score = 0;
let lives = 3;
let player;
// let enemie;
//let enemies;
let bullet;
//let bullets;
let powerup = 0;
let gameOver = true;
function drawScoreBoard() {
textSize(20);
fill('white');
text(`Score: ${score} / Lives: ${lives}`, 20, 40);
}
function preload() {
assets.player = loadImage('assets/Player.png');
assets.enemie = loadImage('assets/Enemie.png');
assets.bulletRight = loadImage('assets/Bullet_Right.png');
assets.bulletLeft = loadImage('assets/Bullet_Left.png');
assets.bulletUp = loadImage('assets/Bullet_Up.png');
assets.bulletDown = loadImage('assets/Bullet_Down.png');
}
function setup() {
bullets = createGroup();
enemies = createGroup();
assets.player.resize(30, 30);
assets.enemie.resize(30, 30);
assets.bulletRight.resize(30, 30);
assets.bulletLeft.resize(30, 30);
assets.bulletUp.resize(30, 30);
assets.bulletDown.resize(30, 30);
createCanvas(screenWidth, screenHeight);
}
function createBullet(){
let numList = [0, 90, 180, 270, 360];
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let randomdirection = numList[Math.floor(Math.random() * numList.length)];
let bullet = createSprite(bulletDirection[(Math.round(player.getDirection()/90))]);
enemie.centerX = random(0, screenWidth);
enemie.setSpeed(random(1,10));
enemie.setDirection(randomdirection);
enemie.setCollider("circle");
bullets.add(bullet);
}
function createPlayer(){
player = createSprite(assets.player);
player.bottom = screenHeight - 20;
player.centerX = screenWidth / 2;
}
function shoot(amountofbulletstobeshot) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
// bullet.direction = player.direction;
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
// console.log('The players current direction right now is: ' + player.getDirection());
}
function shooting() {
if (keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
}
else {
shoot(1);
}
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
function updateplayer() {
//movement
if (keyIsDown) {
if (keyIsDown(KEY.RIGHT_ARROW)) {
player.setVelocity(6, 0);
}
if (keyIsDown(KEY.LEFT_ARROW)) {
player.setVelocity(6, 180);
}
if (keyIsDown(KEY.UP_ARROW)) {
player.setVelocity(6, 270);
}
if (keyIsDown(KEY.DOWN_ARROW)) {
player.setVelocity(6, 90);
}
}
//dont go offscreen
if (player.left < 0) {
player.left = 0;
}
if (player.right > screenWidth) {
player.right = screenWidth;
}
if (player.top < 0) {
player.top = 0;
}
if (player.bottom > screenHeight) {
player.bottom = screenHeight;
}
enemies.overlap(player, HandlePlayerEnemieCollision);
//end up updateplayer
}
function updateEnemie() {
if (frameCount % 1 === 0) {
let directions = ["LEFT", "RIGHT", "UP", "DOWN"];
let direction = random(directions);
if (direction === "LEFT" && enemie.left > 0) {
enemie.centerX -= 5;
}
if (direction === "RIGHT" && enemie.right < screenWidth) {
enemie.centerX += 5;
}
if (direction === "UP" && enemie.top > 0) {
enemie.centerY -= 5;
}
if (direction === "DOWN" && enemie.bottom < screenHeight) {
enemie.centerY += 5;
}
}
}
function createEnemie() {
let directions = [270, 180, 0, 90];
direction = directions[(Math.floor(Math.random() * 5))];
enemies.overlap(bullets, HandleEnemieBulletCollision);
if (frameCount % 60 === 0) {
enemie = createSprite(assets.enemie);
enemie.centerX = Math.floor(Math.random() * 300) + 100;
enemie.centerY = Math.floor(Math.random() * 300) + 100;
enemie.setVelocity(Math.floor(Math.random() * 5) + 1, direction);
enemies.add(enemie);
}
}
function HandleEnemieEdgeCollision(enemie, edge) {
if (enemie.centerY === screenWidth) {
enemie.remove();
}
}
function HandleEnemieBulletCollision(enemie, bullet) {
enemie.remove();
bullet.remove();
score++;
}
function HandlePlayerEnemieCollision(player, enemie) {
enemie.remove();
player.remove();
lives--;
if (lives === 0) {
gameOver = true;
}
createPlayer();
}
/*
function updateEnemie() {
player.setVelocity(7, player.direction);
}
*/
function cheat() {
score = (score + 1000000);
lives = (lives + 1000000);
cheats = 'on';
if (cheats === 'on') {
textSize(50);
fill('yellow');
text('CHEATS ACTIVATED', 400, 300);
}
}
/*
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
*/
function drawGameOverScreen() {
background("black");
textAlign(CENTER);
fill("white");
textSize(40);
text("WELCOME", screenWidth/2, screenHeight/2);
textSize(20);
text("Press SPACE to play!", screenWidth/2, screenHeight/2 + 100);
if (keyWentDown(KEY.SPACE)){
resetGame();
gameOver = false;
}
}
function resetGame(){
score = 0;
lives = 3;
createPlayer();
}
function drawGame() {
background('lightgreen');
drawScoreBoard();
updateplayer();
drawSprites();
shooting();
// updateEnemie();
createEnemie();
}
function draw() {
if (gameOver === true) {
drawGameOverScreen();
} else {
drawGame();
}
}
There is my code, I want to add a time limit for how many seconds it takes until you can shoot again, right now you can just spam and make all of the bullets go in a straight line I need to wait before I let the player shoot again, Thanks! This will help out allot and i neede this in as few minutes as possible.
Use a flag to know when shooting is enabled and disabled. After each shot disable the ability to shoot. Then use a setTimeout to enable the shooting after a certain amount of time.
let shootingEnabled = true;
function tempDisableShooting(duration) {
shootingEnabled = false;
setTimeout(() => {
shootingEnabled = true;
}, duration);
}
function shooting() {
if (shootingEnabled && keyIsDown(KEY.SPACE)) {
if (powerup === 1) {
shoot(3);
} else {
shoot(1);
}
tempDisableShooting(1000); // Disable shooting for 1 second.
}
if (bullet) {
if (bullet.centerX[1] === screenWidth) {
bullets.remove(bullet);
}
}
}
Add property to track the disabled state of the shooting and a constant for the delay time in milliseconds.
let shootDisabled = false;
const shootDelayMS = 300;
Update your shoot function to only shoot if shootDisabled == false, update the shootDisabled to true after each shot, and to triggers a setTimeout which waits shootDelayMS milliseconds before setting shootDisabled to false again.
function shoot(amountofbulletstobeshot) {
if (shootDisabled == false) {
let bulletDirection = [assets.bulletLeft, assets.bulletUp, assets.bulletRight, assets.bulletDown];
let bullet = createSprite(bulletDirection[Math.abs(((Math.round(player.getDirection()/90))))]);
bullets.add(bullet);
bullet.centerX = player.centerX;
bullet.centerY = player.centerY;
bullet.setVelocity(11, player.getDirection());
shootDisabled = true;
setTimeout(() => shootDisabled = false, shootDelayMS );
}
}
one way is the hold the data in two variables: is_shooting, shot_reset.
if(is_shooting){
if(shot_reset>=x){ //x is frame count till able to shoot again)
shot_reset==0;
is_shooting=false;
}else{
shot_reset++
}
}

How can I add a method for rotate the element automatically at page load?

In my index page I have a cube built with css and animated with js, at the moment I rotate the cube by clicking the mouse and drag. I want also at the load of page that the cube automatically rotate random slowly and at the click take the controll. How can I do that, after code my try:
var events = new Events();
events.add = function(obj) {
obj.events = { };
}
events.implement = function(fn) {
fn.prototype = Object.create(Events.prototype);
}
function Events() {
this.events = { };
}
Events.prototype.on = function(name, fn) {
var events = this.events[name];
if (events == undefined) {
this.events[name] = [ fn ];
this.emit('event:on', fn);
} else {
if (events.indexOf(fn) == -1) {
events.push(fn);
this.emit('event:on', fn);
}
}
return this;
}
Events.prototype.once = function(name, fn) {
var events = this.events[name];
fn.once = true;
if (!events) {
this.events[name] = [ fn ];
this.emit('event:once', fn);
} else {
if (events.indexOf(fn) == -1) {
events.push(fn);
this.emit('event:once', fn);
}
}
return this;
}
Events.prototype.emit = function(name, args) {
var events = this.events[name];
if (events) {
var i = events.length;
while(i--) {
if (events[i]) {
events[i].call(this, args);
if (events[i].once) {
delete events[i];
}
}
}
}
return this;
}
Events.prototype.unbind = function(name, fn) {
if (name) {
var events = this.events[name];
if (events) {
if (fn) {
var i = events.indexOf(fn);
if (i != -1) {
delete events[i];
}
} else {
delete this.events[name];
}
}
} else {
delete this.events;
this.events = { };
}
return this;
}
var userPrefix;
var prefix = (function () {
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1],
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
userPrefix = {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
};
})();
function bindEvent(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
function Viewport(data) {
events.add(this);
var self = this;
this.element = data.element;
this.fps = data.fps;
this.sensivity = data.sensivity;
this.sensivityFade = data.sensivityFade;
this.touchSensivity = data.touchSensivity;
this.speed = data.speed;
this.lastX = 0;
this.lastY = 0;
this.mouseX = 0;
this.mouseY = 0;
this.distanceX = 0;
this.distanceY = 0;
this.positionX = 1122;
this.positionY = 136;
this.torqueX = 0;
this.torqueY = 0;
this.down = false;
this.upsideDown = false;
this.previousPositionX = 0;
this.previousPositionY = 0;
this.currentSide = 0;
this.calculatedSide = 0;
bindEvent(document, 'mousedown', function() {
self.down = true;
});
bindEvent(document, 'mouseup', function() {
self.down = false;
});
bindEvent(document, 'keyup', function() {
self.down = false;
});
bindEvent(document, 'mousemove', function(e) {
self.mouseX = e.pageX;
self.mouseY = e.pageY;
});
bindEvent(document, 'touchstart', function(e) {
self.down = true;
e.touches ? e = e.touches[0] : null;
self.mouseX = e.pageX / self.touchSensivity;
self.mouseY = e.pageY / self.touchSensivity;
self.lastX = self.mouseX;
self.lastY = self.mouseY;
});
bindEvent(document, 'touchmove', function(e) {
if(e.preventDefault) {
e.preventDefault();
}
if(e.touches.length == 1) {
e.touches ? e = e.touches[0] : null;
self.mouseX = e.pageX / self.touchSensivity;
self.mouseY = e.pageY / self.touchSensivity;
}
});
bindEvent(document, 'touchend', function(e) {
self.down = false;
});
setInterval(this.animate.bind(this), this.fps);
}
events.implement(Viewport);
Viewport.prototype.animate = function() {
this.distanceX = (this.mouseX - this.lastX);
this.distanceY = (this.mouseY - this.lastY);
this.lastX = this.mouseX;
this.lastY = this.mouseY;
if(this.down) {
this.torqueX = this.torqueX * this.sensivityFade + (this.distanceX * this.speed - this.torqueX) * this.sensivity;
this.torqueY = this.torqueY * this.sensivityFade + (this.distanceY * this.speed - this.torqueY) * this.sensivity;
}
if(Math.abs(this.torqueX) > 1.0 || Math.abs(this.torqueY) > 1.0) {
if(!this.down) {
this.torqueX *= this.sensivityFade;
this.torqueY *= this.sensivityFade;
}
this.positionY -= this.torqueY;
if(this.positionY > 360) {
this.positionY -= 360;
} else if(this.positionY < 0) {
this.positionY += 360;
}
if(this.positionY > 90 && this.positionY < 270) {
this.positionX -= this.torqueX;
if(!this.upsideDown) {
this.upsideDown = true;
this.emit('upsideDown', { upsideDown: this.upsideDown });
}
} else {
this.positionX += this.torqueX;
if(this.upsideDown) {
this.upsideDown = false;
this.emit('upsideDown', { upsideDown: this.upsideDown });
}
}
if(this.positionX > 360) {
this.positionX -= 360;
} else if(this.positionX < 0) {
this.positionX += 360;
}
if(!(this.positionY >= 46 && this.positionY <= 130) && !(this.positionY >= 220 && this.positionY <= 308)) {
if(this.upsideDown) {
if(this.positionX >= 42 && this.positionX <= 130) {
this.calculatedSide = 3;
} else if(this.positionX >= 131 && this.positionX <= 223) {
this.calculatedSide = 2;
} else if(this.positionX >= 224 && this.positionX <= 314) {
this.calculatedSide = 5;
} else {
this.calculatedSide = 4;
}
} else {
if(this.positionX >= 42 && this.positionX <= 130) {
this.calculatedSide = 5;
} else if(this.positionX >= 131 && this.positionX <= 223) {
this.calculatedSide = 4;
} else if(this.positionX >= 224 && this.positionX <= 314) {
this.calculatedSide = 3;
} else {
this.calculatedSide = 2;
}
}
} else {
if(this.positionY >= 46 && this.positionY <= 130) {
this.calculatedSide = 6;
}
if(this.positionY >= 220 && this.positionY <= 308) {
this.calculatedSide = 1;
}
}
if(this.calculatedSide !== this.currentSide) {
this.currentSide = this.calculatedSide;
this.emit('sideChange');
}
}
this.element.style[userPrefix.js + 'Transform'] = 'rotateX(' + this.positionY + 'deg) rotateY(' + this.positionX + 'deg)';
if(this.positionY != this.previousPositionY || this.positionX != this.previousPositionX) {
this.previousPositionY = this.positionY;
this.previousPositionX = this.positionX;
this.emit('rotate');
}
}
var viewport = new Viewport({
element: document.getElementsByClassName('cube')[0],
fps: 20,
sensivity: .1,
sensivityFade: .93,
speed: 0.5,
touchSensivity: 1.5
});
function Cube(data) {
var self = this;
this.element = data.element;
this.sides = this.element.getElementsByClassName('side');
this.viewport = data.viewport;
// this.viewport.on('rotate', function() {
// self.rotateSides();
// });
// this.viewport.on('upsideDown', function(obj) {
// self.upsideDown(obj);
// });
this.viewport.on('sideChange', function() {
self.sideChange();
});
}
// Cube.prototype.rotateSides = function() {
// var viewport = this.viewport;
// if(viewport.positionY > 90 && viewport.positionY < 270) {
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + (viewport.positionX + viewport.torqueX) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + -(viewport.positionX + 180 + viewport.torqueX) + 'deg)';
// } else {
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + (viewport.positionX - viewport.torqueX) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + -(viewport.positionX + 180 - viewport.torqueX) + 'deg)';
// }
// }
// Cube.prototype.upsideDown = function(obj) {
// var deg = (obj.upsideDown == true) ? '180deg' : '0deg';
// var i = 5;
// while(i > 0 && --i) {
// this.sides[i].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + deg + ')';
// }
// }
Cube.prototype.sideChange = function() {
for(var i = 0; i < this.sides.length; ++i) {
this.sides[i].getElementsByClassName('cube-image')[0].className = 'cube-image';
}
this.sides[this.viewport.currentSide - 1].getElementsByClassName('cube-image')[0].className = 'cube-image active';
}
// Cube.prototype.autoMove = function() {
// var viewport = this.viewport;
// this.sides[0].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + Math.floor(Math.random() * 360) + 'deg)';
// this.sides[5].getElementsByClassName('cube-image')[0].style[userPrefix.js + 'Transform'] = 'rotate(' + Math.floor(Math.random() * 360) + 'deg)';
// }
// this.autoMove();
new Cube({
viewport: viewport,
element: document.getElementsByClassName('cube')[0]
});
I tried to make something like this:
Viewport.prototype.autoMove = document.addEventListener('DOMContentLoaded', () => {
this.positionX = 0;
this.positionY = 0;
while (this.positionX <= 1122 && this.positionY <= 136) {
this.element.style[userPrefix.js + 'Transform'] = 'rotateX(' + this.positionY + 'deg) rotateY(' + this.positionX + 'deg)';
this.positionX++;
this.positionY++;
}
})
This is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./assets/css/style.css">
<title>Cube Project</title>
</head>
<body>
<h1 id="theTitle">CUBE</h1>
<div id="wrapper">
<div class="viewport">
<div class="cube">
<div class="side">
<div class="cube-image"><h2><a class="cube-link" href="#">BLA BLA BLA,<br> BLA BLA BLA.</a></h2></div>
</div>
<div class="side">
<div class="cube-image">2</div>
</div>
<div class="side">
<div class="cube-image">3</div>
</div>
<div class="side">
<div class="cube-image">4</div>
</div>
<div class="side">
<div class="cube-image">5</div>
</div>
<div class="side">
<div class="cube-image active">6</div>
</div>
</div>
</div>
</div>
<script src="./assets/js/app.js"></script>
</body>
</html>
Give an animation style to the cube element
#keyframes rotate{
to{ transform: rotate(360deg); }
}
.cube{
animation: rotate 4.5s linear infinite;
}
var randomMoves=serInterval(rotateRandomly,100);
function rotateRandomly() { ... }
on click:
if(randomMoves!=NULL) clearInterval(randomMoves);
randomMoves=NULL;
Of course you should use requestAnimationFrame instead, but this is so simple...

How to do vertical infinite repeating background for a JavaScript game?

I have been looking at the code of this Flappy Bird clone to figure out how to repeat a background image vertically but have had no luck so far.
http://www.codeproject.com/Articles/778727/Build-Flappy-Bird-with-jQuery-and-lines-of-Javascr
I've altered the code so far to be able to scroll down, but the repetition of the bg image stops after around 800pixels of moving down and for the hell of me I cant figure out why!
I have heard that this code is not the best code out there, so if someone has another way to do this I'm all ears.
This is the codepen to preview the nonworking background:
http://codepen.io/tangwei/pen/dpbQPZ
var bird = null, board = null;
var dimPipe = { width:40, height:420 }, cPos = { x: 80, y:100, h:40, w:50 };
var gravity = 0.5, iniSpeed = -7, curSpeed = 0;
var score = 0, noClr = 0, tmStep = 0, state = 0; // 0-not started,1-play,2-over;
(function($) {
$.cssNumber.rotate = true;
$.cssHooks.rotate = {
set : function(el, v) {
if (typeof v === 'string')
v = (v.indexOf("rad") != -1) ? parseInt(v) * 180 / Math.PI : parseInt(v);
v = (~~v);
if (v == ($.data(el, 'rotate') || 0)) return;
el.style["MozTransform"] = el.style["MozTransform"] = el.style["-webkit-transform"]
= el.style["transform"] = " rotate(" + (v % 360) + "deg)";
$.data(el, 'rotate', v);
},
get : function(el, computed) {
return $.data(el, 'rotate') || 0;
}
};
})(jQuery);
function gameOver() {
state = 2;
$(":animated").stop();
if (tmStep) tmStep = window.clearInterval(tmStep);
bird.animate({ top:board.height()-cPos.h, rotate:540}, 1000)
.animate({ top:board.height()-cPos.h}, 500, function() {
$('#score').text(' Score: ' + score);
start();
});
}
function Parallax(elm, tmo) {
elm.animate({top:-1000}, { // play around with this value to determine speed
duration:tmo*50, easing:'linear', //step : PrlxStep,
complete : function() { Parallax(elm, tmo); }
});
}
function BirdStep() {
curSpeed += gravity;
cPos.y = Math.max(cPos.y + curSpeed, 0);
var ang = curSpeed * 5, mh = board.height()-cPos.h, m = -12, lo = 0, actPipe = $('.obs');
bird.css({top: cPos.y, rotate:(ang < -20) ? -20 : (ang > 90) ? 90 : ang});
// if (cPos.y > mh)
// return gameOver();
// for (var i = actPipe.length-1; i >= 0; i--) {
// var s = actPipe[i].style, x = parseInt(s.left), y = parseInt(s.top);
// lo = Math.max(lo, x);
// if (x+dimPipe.width +m < cPos.x || x > cPos.x+cPos.w+m) continue;
// if (y+dimPipe.height+m < cPos.y || y > cPos.y+cPos.h+m) continue;
// return gameOver();
// }
// if (actPipe.length > 3 || lo > 300 || Math.random() >= 0.05 * (1+noClr))
// return;
// var og = cPos.h * 2;
// var oh = og + Math.floor(Math.random() * (mh-og+1));
// var obs = $("<img/><img/>").addClass('c obs').css({left:480, zIndex:3}).css(dimPipe).attr('src', 'vine.png')
// .appendTo(board).animate({left:-50}, Math.max(2000,3500-noClr*50), 'linear', function() {
// $('#score').text(' Score: ' + (score += 1 + Math.floor(++noClr/10)));
// this.remove();
// });
// obs[0].style.top = oh + 'px';
// obs[1].style.top = (oh - og - dimPipe.height) + "px";
}
function onTap() {
if (state > 1) return;
if (state == 0) {
state = 1;
$('#score').text(' Score: ' + (score = 0));
Parallax($('#bGrnd'), 40);
Parallax($('#fGrnd'), 80);
$('#instr').hide();
tmStep = window.setInterval(BirdStep, 30);
}
curSpeed = iniSpeed;
}
function start() {
state = noClr = score = 0; // not started
cPos = { x: 80, y:100, h:40, w:50 };
bird.css({left:cPos.x, top:cPos.y, width:cPos.w, height:cPos.h, rotate:0});
// $('.obs').remove();
$('#instr').show();
}
$(document).ready(function() {
bird = $('#bird');
var evt = (typeof(bird[0].ontouchend) == "function") ? "touchstart" : "mousedown";
board = $('#board').bind(evt, onTap);
start();
setInterval(function(){
var bGrnd = $("#bGrnd");
var curr_height = parseInt(bGrnd.css("height"));
curr_height += 1000;
bGrnd.css("height", curr_height);
},2000)
});

Javascript arrays (Image slider)(bug in Webkit?)

I've got a image slider on my website, it seems to work fine on IE, Firefox and Opera. But it doesn't work on Chrome and Safari. (Example: http://tommy-design.nl/ari/index.php)
<script type="text/javascript">
var data = [
["fotos/DSC_0055 (Large).JPG","Duitse herder","fotos/DSC_0055 (Large).JPG"],
["fotos/DSC_0154 (Large).JPG","Duitse herder","fotos/DSC_0154 (Large).JPG"],
["fotos/DSC_0194 (Large).JPG","Duitse herder","fotos/DSC_0194 (Large).JPG"],
["fotos/SSA41896 (Large).jpg","Duitse herder","fotos/SSA41896 (Large).jpg"],
["fotos/DSC_0143 (Large).JPG","Duitse herder","fotos/DSC_0143 (Large).JPG"]
]
imgPlaces = 4
imgWidth = 230
imgHeight = 122
imgSpacer = 0
dir = 0
newWindow = 1
moz = document.getElementById &&! document.all
step = 1
timer = ""
speed = 10
nextPic = 0
initPos = new Array()
nowDivPos = new Array()
function initHIS3()
{
for (var i = 0;i < imgPlaces+1;i++)
{
newImg=document.createElement("IMG")
newImg.setAttribute("id","pic_"+i)
newImg.setAttribute("src","")
newImg.style.position = "absolute"
newImg.style.width=imgWidth + "px"
newImg.style.height=imgHeight + "px"
newImg.style.border = 0
newImg.alt =""
newImg.i = i
newImg.onclick = function()
{
his3Win(data[this.i][2])
}
document.getElementById("display").appendChild(newImg)
}
containerEL = document.getElementById("container1")
displayArea = document.getElementById("display")
pic0 = document.getElementById("pic_0")
containerBorder = (document.compatMode == "CSS1Compat"?0:parseInt(containerEL.style.borderWidth) * 2)
containerWidth = (imgPlaces * imgWidth) + ((imgPlaces - 1) * imgSpacer)
containerEL.style.width=containerWidth + (!moz?containerBorder:"") + "px"
containerEL.style.height=imgHeight + (!moz?containerBorder:"") + "px"
displayArea.style.width = containerWidth+"px"
displayArea.style.clip = "rect(0," + (containerWidth+"px") + "," + (imgHeight+"px") + ",0)"
displayArea.onmouseover = function()
{
stopHIS3()
}
displayArea.onmouseout = function()
{
scrollHIS3()
}
imgPos = - pic0.width
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
if (dir === 0)
{
imgPos += pic0.width + imgSpacer
}
initPos[i] = imgPos
if (dir === 0)
{
currentImage.style.left = initPos[i]+"px"
}
if (dir === 1)
{
document.getElementById("pic_"+[(imgPlaces-i)]).style.left = initPos[i]+"px"
imgPos += pic0.width + imgSpacer
}
if (nextPic == data.length)
{
nextPic = 0
}
currentImage.src = data[nextPic][0]
currentImage.alt = data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
scrollHIS3()
}
timer = ""
function scrollHIS3()
{
clearTimeout(timer)
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
nowDivPos[i] = parseInt(currentImage.style.left)
if (dir === 0)
{
nowDivPos[i] -= step
}
if (dir === 1)
{
nowDivPos[i] += step
}
if (dir === 0 && nowDivPos[i] <= -(pic0.width + imgSpacer) || dir == 1 && nowDivPos[i] > containerWidth)
{
if (dir === 0)
{
currentImage.style.left = containerWidth + imgSpacer + "px"
}
if (dir === 1)
{
currentImage.style.left = - pic0.width - (imgSpacer * 2) + "px"
}
if (nextPic > data.length-1)
{
nextPic = 0
}
currentImage.src=data[nextPic][0]
currentImage.alt=data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
else
{
currentImage.style.left=nowDivPos[i] + "px"
}
}
timer = setTimeout("scrollHIS3()",speed)
}
function stopHIS3()
{
clearTimeout(timer)
}
function his3Win(loc)
{
if(loc === "")
{
return
}
if(newWindow === 0)
{
location = loc
}
else
{
newin = window.open(loc,'win1','left = 430,top = 340,width = 300 ,height = 300')
newin.focus()
}
}
</script>
I'm almost 100% sure that the problem lies in the array, but I can't seem to figure out what exactly the problem is..
Thanks in advance. :)
Try to use
position:relative;
and moving the first one from left to right / right to left(the others will follow accordingly as relative will tell em to follow the first image )
. i am pretty sure that that will start working on chrome then. as relative position tells it to use different positions. while opening your slider i found some bugs in chrome console : they all have the same left: thats getting changed together.

Categories