I'm using the latest phaser.io version, but I'm getting a error which is probably related to these lines:
Phaser.Rectangle.contains(e.body, game.input.activePointer.x, game.input.activePointer.y);
and
shapesprite.body.setSize(30, 30, 0, 0);
I have commented out the line above, and it somewhat works, but then I get this error:
Game.js:195 Uncaught TypeError: Cannot read property 'setSize' of null
And I guess my sprite has 18 sections to read through.
Here is the sprite image. The left column is the unclicked state, and then right column is the clicked state
My code:
gameObj.Game = function (game) {
//step 1
var myTime;
var gameSeconds; //total game seconds
var timerSeconds = "0"; //current timer in seconds
var secondsLeft; //total game seconds - current timer second
var points;
var pointsShow;
};
var tile_size = 69;
gameObj.Game.prototype = {
create: function () {
var border = this.add.sprite(this.world.centerX, this.world.centerY, 'border');
border.anchor.setTo(0.5, 0.5);
var stroke = this.add.sprite(this.world.centerX + 30, this.world.centerX - 450, 'stroke');
points = 0;
gameObj.finalScore = points;
var currentTarg = this.add.sprite(this.world.centerX + 200, this.world.centerX - 125, 'currenttarget');
this.shapes = this.add.group();
this.shapes.createMultiple(36, 'shapesprite');
this.shapes.setAll('inputEnabled', true);
this.shapes.setAll('input.useHandCursor', true);
var progressbackground = this.add.sprite(this.world.centerX + 90, this.world.centerX - 380, 'progressbg');
var myPercentStyle = {
font: "400 24px Architects Daughter",
fill: "#000",
align: "center"
};
pointsShow = this.add.text(this.world.centerX + 195, this.world.centerX - 300, points + '%', myPercentStyle);
var myProgress = "Progress of \nShape Painting"
var myProgressStyle = {
font: "400 18px Architects Daughter",
fill: "#000",
align: "center"
};
var myProgressShow = this.add.text(this.world.centerX + 160, this.world.centerX - 360, myProgress, myProgressStyle);
var currentTargText = "Mix colors and make a:"
var currentTargStyle = {
font: "400 18px Architects Daughter",
fill: "#000",
align: "center"
};
var currentTargShow = this.add.text(this.world.centerX + 135, this.world.centerX - 220, currentTargText, currentTargStyle);
var targetBg = this.add.sprite(this.world.centerX + 140, this.world.centerX - 190, 'targetbg');
var timerbackground = this.add.sprite(this.world.centerX + 90, this.world.centerY + 120, 'timerbg');
var myTimeText = "Time until Art Show:";
var myTimeTextStyle = {
font: "400 24px Architects Daughter",
fill: "#000",
align: "center"
};
var myTimeShow = this.add.text(this.world.centerX + 110, this.world.centerX + 35, myTimeText, myTimeTextStyle);
var myTime = "2:00"
var myTimeStyle = {
font: "400 35px Architects Daughter",
fill: "#000",
align: "center"
};
myTimerShow = this.add.text(this.world.centerX + 190, this.world.centerX + 70, myTime, myTimeStyle);
tmpWinnerBtn = this.add.button(100, 200, 'btn_winner', this.winnerFun, this, 1, 0, 2);
tmpWinnerBtn.anchor.setTo(0.5, 0.5);
tmpLoserBtn = this.add.button(200, 200, 'btn_loser', this.loserFun, this, 1, 0, 2);
tmpLoserBtn.anchor.setTo(0.5, 0.5);
//timevars
tmpPointsBtn = this.add.button(300, 100, 'points_btn', this.pointsIncrease, this, 1, 0, 2);
gameSeconds = 120;
timerSeconds = 0;
secondsLeft = 0;
//create timer object
timerObj = this.game.time.create(false);
//set a timer event to occur every 1 second
timerObj.loop(1000, this.updateTimer, this);
//start the timer running
timerObj.start();
// this.combo_s = this.game.add.audio('combo');
this.clicked = false;
this.count = 0;
this.moves = 0;
this.type = -1;
this.deleted_shapes = [];
this.pos_i = -1;
this.pos_j = -1;
this.offset_x = 120;
this.offset_y = 150;
this.next_time = 0;
score = 0;
//this.width=69;
this.build_world();
},
update: function () {
this.shapes.forEachAlive(function (e) {
if (e.scale.x == 2) e.kill();
}, this);
if (game.input.activePointer.isDown && game.time.now > this.next_time) {
this.clicked = true;
this.try_select_a_shapesp();
}
if (game.input.activePointer.isUp && this.clicked) {
if (this.count > 1) {
this.remove_selected_shapes();
this.move_shapes_down();
this.add_missing_shapes();
} else
this.unselect_all_shapes();
//this.next_time = game.time.now + 300;
this.count = 0;
this.clicked = false;
this.type = -1;
this.pos_i = -1;
this.pos_j = -1;
}
},
build_world: function () {
for (var i = 0; i < 6; i++)
for (var j = 0; j < 6; j++)
this.add_shapesp(i, j, true);
},
add_shapesp: function (i, j, type) {
var shapesprite = this.shapes.getFirstExists(false);
var r = rand(3);
if (r == 1) shapesprite.frame = 2;
else if (r == 3) shapesprite.frame = 6;
else if (r == 2) shapesprite.frame = 4;
// else if (r == 2) shapesprite.frame = 4;
// else if (r == 3) shapesprite.frame = 6;
// else if (r == 4) shapesprite.frame = 8;
// else if (r == 5) shapesprite.frame = 10;
// // else if (r == 6) shapesprite.frame = 12;
// else if (r == 7) shapesprite.frame = 14;
// // else if (r == 8) shapesprite.frame = 16;
// else if (r == 9) shapesprite.frame = 18;
// // else if (r == 10) shapesprite.frame = 20;
// else if (r == 11) shapesprite.frame = 22;
// // else if (r == 12) shapesprite.frame = 24;
// else if (r == 13) shapesprite.frame = 26;
// else if (r == 14) shapesprite.frame = 28;
// // else if (r == 15) shapesprite.frame = 30;
// else if (r == 16) shapesprite.frame = 32;
// else if (r == 17) shapesprite.frame = 34;
// else if (r == 18) shapesprite.frame = 36;
shapesprite.anchor.setTo(0.5, 0.5);
shapesprite.selected = false;
shapesprite.pos_i = i;
shapesprite.pos_j = j;
shapesprite.move_y = 0;
shapesprite.move_x = 1;
shapesprite.body.setSize(30, 30, 0, 0);
shapesprite.alpha = 1;
shapesprite.scale.setTo(5, 1);
shapesprite.alive2 = true;
shapesprite.reset(this.offset_x + j * tile_size, this.offset_y + i * tile_size);
if (type)
this.game.add.tween(shapesprite.scale).delay(j * 100 + 1).to({
x: 1,
y: 1
}, 400).start();
else
this.game.add.tween(shapesprite.scale).delay(400).to({
x: 1,
y: 1
}, 400).start();
},
try_select_a_shapesp: function (e) {
this.shapes.forEachAlive(function (e) {
var bool = Phaser.Rectangle.contains(e.body, game.input.activePointer.x, game.input.activePointer.y);
if (e.selected || !bool) {
//console.log('hi');
return;
}
if (this.type == -1)
this.type = e.frame;
if (this.type == e.frame && this.in_range(e))
this.select_a_shapesp(e);
else
this.unselect_all_shapes();
}, this);
},
select_a_shapesp: function (e) {
e.selected = true;
e.frame += 1;
this.count += 1;
this.pos_j = e.pos_j;
this.pos_i = e.pos_i;
// this.increase_bar();
},
remove_selected_shapes: function (e) {
this.shapes.forEachAlive(function (e) {
if (!e.selected)
return;
this.game.add.tween(e.scale).to({
x: 2,
y: 2
}, 300).start();
this.game.add.tween(e).to({
alpha: 0
}, 300).start();
this.deleted_shapes.push({
i: e.pos_i,
j: e.pos_j
});
e.alive2 = false;
}, this);
},
unselect_all_shapes: function () {
this.count = 0;
this.shapes.forEachAlive(function (e) {
if (e.selected) {
e.selected = false;
e.frame -= 1;
}
}, this);
this.clear_bar();
},
move_shapes_down: function () {
for (var i = 0; i < this.deleted_shapes.length; i++) {
var tmp_i = this.deleted_shapes[i].i;
var tmp_j = this.deleted_shapes[i].j;
this.shapes.forEachAlive(function (e) {
if (!e.selected && e.pos_j == tmp_j && e.pos_i < tmp_i)
e.move_y += tile_size;
}, this);
}
this.shapes.forEachAlive(function (e) {
if (e.move_y == 0)
return;
var coef = e.move_y / tile_size;
e.pos_i += coef;
this.add.tween(e).delay(100).to({
y: e.y + e.move_y
}, 100 * coef).start();
e.move_y = 0;
}, this);
this.deleted_shapes = [];
},
add_missing_shapes: function () {
var min = [6, 6, 6, 6, 6, 6];
this.shapes.forEachAlive(function (e) {
if (e.pos_i < min[e.pos_j] && e.alive2)
min[e.pos_j] = e.pos_i;
}, this);
for (var i = 0; i < 6; i++)
for (var j = 0; j < min[i]; j++)
this.add_shapesp(j, i, false);
},
update_score_and_labels: function () {
this.clear_bar();
this.game.state.start('End');
},
in_range: function (d) {
if (this.pos_j == -1) return true;
return (this.pos_j - 1 == d.pos_j && this.pos_i == d.pos_i) ||
(this.pos_j + 1 == d.pos_j && this.pos_i == d.pos_i) ||
(this.pos_j == d.pos_j && this.pos_i - 1 == d.pos_i) ||
(this.pos_j == d.pos_j && this.pos_i + 1 == d.pos_i);
},
clear_bar: function () {
this.game.add.tween(this.progress).to({
}, 300).start();
},
add_tuto: function () {
this.tuto = this.game.add.button(0, 0, 'tuto', this.remove_tuto, this);
},
updateTimer: function () {
//console.log('hola');
timerSeconds++;
if (timerSeconds <= gameSeconds) {
secondsLeft = gameSeconds - timerSeconds;
//
displayMin = Math.floor(secondsLeft / 60) % 60;
displaySec = Math.floor(secondsLeft) % 60;
//
if (displayMin < 10) {
displayMin = "" + displayMin;
}
if (displaySec < 10) {
displaySec = "0" + displaySec;
}
myTimerShow.setText(displayMin + ":" + displaySec);
} else {
timerSeconds = 0;
this.loserFun();
}
},
pointsIncrease: function () {
//console.log("increase");
gameObj.finalScore += 10;
points = gameObj.finalScore;
pointsShow.setText(points + "%");
if (points == 100) {
this.game.state.start('Winner');
}
},
winnerFun: function () {
gameObj.finalTime = timerSeconds;
this.state.start('Winner');
},
loserFun: function () {
gameObj.finalTime = timerSeconds;
this.state.start('Loser');
}
};
No-where in your code do you enable physics on the shapesprites. They won't have a body you can access until you do this first:
Here's one way of doing it: http://phaser.io/examples/v2/arcade-physics/group-vs-self
Related
//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++
}
}
i have an laravel project and just implemented some scripts in it
and i keep gettinf this error
Uncaught SyntaxError: Identifier 'Player' has already been declared
at player.js:1
Uncaught SyntaxError: Identifier 'canvas' has already been declared
at tetris.js:1
i only get this error while working with laravel because the code works in a normal html file.
this is my javascript:
player.js
class Player
{
constructor()
{
this.pos = {x:0,y:0};
this.matrix = null;
this.score = 0;
}
}
tetris.jsconst canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#cbc7ca';
context.strokeRect(0,0, canvas.width, canvas.height);
function arenaSweep() {
let rowCount = 1
outer: for(let y = arena.length - 1; y > 0; --y) {
for(let x = 0; x < arena[y].length; ++x) {
if(arena[y][x] === 0){
continue outer;
}
}
const row = arena.splice(y, 1)[0].fill(0);
arena.unshift(row);
++y;
player.score += rowCount * 10;
rowCount *= 2;
}
}
function collide(arena, player){
const [m, o] = [player.matrix, player.pos];
for(let y = 0; y < m.length; ++y) {
for(let x = 0; x < m[y].length; ++x){
if(m[y][x] !== 0 &&
(arena[y + o.y] &&
arena[y + o.y][x + o.x]) !== 0)
return true;
}
}
return false;
}
function createMatrix(w, h){
const matrix = [];
while( h--) {
matrix.push(new Array(w).fill(0));
}
return matrix
}
function draw() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(arena, {x:0, y:0});
drawMatrix(player.matrix, player.pos );
}
function createPiece(type) {
if( type === 'T'){
return [
[0,0,0],
[1,1,1],
[0,1,0],
];
}
else if(type === 'O'){
return [
[2,2],
[2,2]
];
}
else if( type === 'L'){
return [
[0,3,0],
[0,3,0],
[0,3,3],
];
}
else if( type === 'J'){
return [
[0,4,0],
[0,4,0],
[4,4,0],
];
}
else if( type === 'I'){
return [
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
];
}
else if( type === 'Z'){
return [
[6,6,0],
[0,6,6],
[0,0,0],
];
}
else if( type === 'S'){
return [
[0,7,7],
[7,7,0],
[0,0,0],
];
}
}
function drawMatrix(matrix, offset){
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
context.fillStyle = colors[value];
context.fillRect(x + offset.x,
y + offset.y,
1,1);
}
});
});
}
function merge(arena, player) {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
function playerDrop() {
player.pos.y++;
if(collide(arena, player)) {
player.pos.y--;
merge(arena,player);
playerReset();
arenaSweep();
updateScore();
}
dropCounter = 0;
}
function playerMove(dir) {
player.pos.x += dir;
if(collide(arena, player)) {
player.pos.x -= dir;
}
}
function playerReset() {
const pieces = 'ILJOSZ';
player.matrix = createPiece(pieces[pieces.length * Math.random() | 0]);
player.pos.y = 0;
player.pos.x = (arena[0].length / 2 | 0) -
(player.matrix[0].length / 2 | 0);
if(collide(arena,player)) {
arena.forEach(row => row.fill(0));
player.score = 0;
playerReset();
}
}
function playerRotate(dir){
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
while (collide(arena, player)) {
player.pos.x += offset;
offset = -(offset +(offset > 0 ? 1 : -1 ));
if(offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
function rotate(matrix, dir){
for(let y = 0; y < matrix.length;++y) {
for(let x = 0; x < y; ++x) {
[
matrix[x][y],
matrix[y][x],
] = [
matrix[y][x],
matrix[x][y],
];
}
}
if(dir > 0){
matrix.forEach(row => row.reverse());
}else{
matrix.reverse();
}
}
let dropCounter = 0;
let dropInterval = 1000;
let lasttime = 0;
function update(time = 0) {
const deltaTime = time - lasttime;
lasttime = time;
dropCounter += deltaTime;
if(dropCounter > dropInterval){
playerDrop();
}
draw();
requestAnimationFrame(update);
}
function updateScore() {
document.getElementById('score').innerText = player.score;
}
const colors =[
null,
'purple',
'yellow',
'orange',
'blue',
'cyan',
'red',
'green',
];
const arena = createMatrix(12, 20);
const player = new Player;
document.addEventListener('keydown', event => {
if (event.keyCode === 37){
playerMove(-1);
}
else if(event.keyCode === 39){
playerMove(1);
}
else if(event.keyCode === 40){
playerDrop();
}
else if(event.keyCode === 90) {
playerRotate(-1);
}
else if(event.keyCode === 88) {
playerRotate(1);
}
})
playerReset();
updateScore();
update();
this is my blade template:
#section('content')
<div id="score">0</div>
<canvas id="tetris" width="240" height="400"></canvas>
<script type="application/javascript" src="{{asset('js/player.js')}}"></script>
<script type="application/javascript" src="{{asset('js/tetris.js')}}"></script>
#endsection`
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) {
...
...
...
}
}
On my HTML page, I need to have a line with text that rolls "infinitely" on the page, e.g.
"Hello World ... Hello World ... Hello World ... Hello World ..."
Sort of like a ticker tape, but with the same text's beginning rolling into its end w/o a gap.
I've tried using animation: marquee CSS style, I can get the text roll, then jump back, then roll again, but that's not what I need.
Is this possible with CSS? JS would be OK, if there is a working solution.
Try here "text rolling" working with text & images and mouse effects(js+css)
http://www.dynamicdrive.com/dynamicindex2/crawler/index.htm
Are you open to using a lib that does this?
This one here: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/ does a good job.
$(document).ready(function() {
new Marquee('example', {
// once or continuous
continuous: true,
// 'rtl' or 'ltr'
direction: 'rtl',
// pause between loops
delayAfter: 1000,
// when to start
delayBefore: 0,
// scroll speed
speed: 0.5,
// loops
loops: -1
});
});
////////////////////////////// LIBRARY BELOW ///////
// See: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/
/*
Vanilla Javascript Marquee
Version: 0.1.0
Author: Robert Bossaert <https://github.com/robertbossaert>
Example call:
new Marquee('element');
new Marquee('element', {
direction: 'rtl',
});
*/
var Marquee = function(element, defaults) {
"use strict";
var elem = document.getElementById(element),
options = (defaults === undefined) ? {} : defaults,
continuous = options.continuous || true, // once or continuous
delayAfter = options.delayAfter || 1000, // pause between loops
delayBefore = options.delayBefore || 0, // when to start
direction = options.direction || 'ltr', // ltr or rtl
loops = options.loops || -1,
speed = options.speed || 0.5,
timer = null,
milestone = 0,
marqueeElem = null,
elemWidth = null,
self = this,
ltrCond = 0,
loopCnt = 0,
start = 0,
process = null,
constructor = function(elem) {
// Build html
var elemHTML = elem.innerHTML,
elemNode = elem.childNodes[1] || elem;
elemWidth = elemNode.offsetWidth;
marqueeElem = '<div>' + elemHTML + '</div>';
elem.innerHTML = marqueeElem;
marqueeElem = elem.getElementsByTagName('div')[0];
elem.style.overflow = 'hidden';
marqueeElem.style.whiteSpace = 'nowrap';
marqueeElem.style.position = 'relative';
if (continuous === true) {
marqueeElem.innerHTML += elemHTML;
marqueeElem.style.width = '200%';
if (direction === 'ltr') {
start = -elemWidth;
}
} else {
ltrCond = elem.offsetWidth;
if (direction === 'rtl') {
milestone = ltrCond;
}
}
if (direction === 'ltr') {
milestone = -elemWidth;
} else if (direction === 'rtl') {
speed = -speed;
}
self.start();
return marqueeElem;
}
this.start = function() {
process = window.setInterval(function() {
self.play();
});
};
this.play = function() {
// beginning
marqueeElem.style.left = start + 'px';
start = start + speed;
if (start > ltrCond || start < -elemWidth) {
start = milestone;
loopCnt++;
if (loops !== -1 && loopCnt >= loops) {
marqueeElem.style.left = 0;
}
}
}
this.end = function() {
window.clearInterval(process);
}
// Init plugin
marqueeElem = constructor(elem);
}
body {
background: #edf3f9;
color: #3f4f5f;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
width: 800px;
}
header {
border-bottom: 2px solid #3f4f5f;
padding: 6.25em 0 3.95em;
text-align: center;
width: 100%;
}
header h1 {
margin: 0 0 10px;
}
.example {
padding: 3em 0;
}
h2 {
text-align: center;
}
pre {
background: #f5f2f0;
color: #000;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
line-height: 26px;
padding: 1em;
text-shadow: 0 1px white;
white-space: pre-wrap;
}
pre span.string {
color: #690;
}
pre span.number {
color: #905;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
The quick brown fox ran over to the bar to drink some water. He walked up to the bar tender and said: blah blah blah.
</div>
Here is a demo based upon the lib that Dreamer posted.
I didn't like how it set inline styles on the element or how it used cookies to store past settings so I removed that in the crawler.js code.
This is a pretty old library (ie5 is mentioned (!)) but it seems to do the trick.
$(function() {
marqueeInit({
uniqueid: 'mycrawler',
style: {
},
inc: 5, //speed - pixel increment for each iteration of this marquee's movement
mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
moveatleast: 2,
neutral: 150,
persist: true,
savedirection: true
});
});
//////////////// CRAWLER.JS FOLLOWS ///////////
/* Text and/or Image Crawler Script v1.53 (c)2009-2012 John Davenport Scheuer
as first seen in http://www.dynamicdrive.com/forums/
username: jscheuer1 - This Notice Must Remain for Legal Use
updated: 4/2011 for random order option, more (see below)
*/
/* Update 4/2011 to v1.5 - Adds optional random property. Set it to true to use.
Fixes browser crash from empty crawlers, ad and image blocking software/routines.
Fixes behavior in some IE of breaking script if an image is missing.
Adds alt attributes to images without them to aid in diagnosis of missing/corrupt
images. This may be disabled with the new optional noAddedAlt property set to true.
Internal workings enhanced for greater speed of execution, less memory usage.
*/
/* Update 11/2011 - Detect and randomize td elements within a single table with a single tr */
// updated 7/2012 to 1.51 for optional integration with 3rd party initializing scripts -
// ref: http://www.dynamicdrive.com/forums/showthread.php?p=278161#post278161
// updated 8/2012 to 1.52 for greater compatibility with IE in Quirks Mode
/* Update 10/2012 to v1.53 - Adds optional persist property to have the crawler remember its
position and direction page to page and on page reload. To enable it in the marqueeInit set
persist: true,
*/
///////////////// No Need to Edit - Configuration is Done in the On Page marqueeInit call(s) /////////////////
function marqueeInit(config) {
if (!document.createElement) return;
marqueeInit.ar.push(config);
marqueeInit.run(config.uniqueid);
}
(function() {
if (!document.createElement) return;
if (typeof opera === 'undefined') {
window.opera = false;
}
marqueeInit.ar = [];
document.write('<style type="text/css">.marquee{white-space:nowrap;overflow:hidden;visibility:hidden;}' +
'#marq_kill_marg_bord{border:none!important;margin:0!important;}<\/style>');
var c = 0,
tTRE = [/^\s*$/, /^\s*/, /\s*$/, /[^\/]+$/],
req1 = {
'position': 'relative',
'overflow': 'hidden'
},
defaultconfig = {
style: { //default style object for marquee containers without configured style
'margin': '0 auto'
},
direction: 'left',
inc: 2, //default speed - pixel increment for each iteration of a marquee's movement
mouse: 'pause' //default mouseover behavior ('pause' 'cursor driven' or false)
},
dash, ie = false,
oldie = 0,
ie5 = false,
iever = 0;
/*#cc_on #*/
/*#if(#_jscript_version >= 5)
ie = true;
try{document.documentMode = 2000}catch(e){};
iever = Math.min(document.documentMode, navigator.appVersion.replace(/^.*MSIE (\d+\.\d+).*$/, '$1'));
if(iever < 6)
oldie = 1;
if(iever < 5.5){
Array.prototype.push = function(el){this[this.length] = el;};
ie5 = true;
dash = /(-(.))/;
String.prototype.encamel = function(s, m){
s = this;
while((m = dash.exec(s)))
s = s.replace(m[1], m[2].toUpperCase());
return s;
};
}
#end #*/
if (!ie5) {
dash = /-(.)/g;
function toHump(a, b) {
return b.toUpperCase();
};
String.prototype.encamel = function() {
return this.replace(dash, toHump);
};
}
if (ie && iever < 8) {
marqueeInit.table = [];
window.attachEvent('onload', function() {
marqueeInit.OK = true;
var i = -1,
limit = marqueeInit.table.length;
while (++i < limit)
marqueeInit.run(marqueeInit.table[i]);
});
}
function intable(el) {
while ((el = el.parentNode))
if (el.tagName && el.tagName.toLowerCase() === 'table')
return true;
return false;
};
marqueeInit.run = function(id) {
if (ie && !marqueeInit.OK && iever < 8 && intable(document.getElementById(id))) {
marqueeInit.table.push(id);
return;
}
if (!document.getElementById(id))
setTimeout(function() {
marqueeInit.run(id);
}, 300);
else
new Marq(c++, document.getElementById(id));
}
function trimTags(tag) {
var r = [],
i = 0,
e;
while ((e = tag.firstChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
while ((e = tag.lastChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
if ((e = tag.firstChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[1], '');
if ((e = tag.lastChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[2], '');
while ((e = tag.firstChild))
r[i++] = tag.removeChild(e);
return r;
}
function randthem(tag) {
var els = oldie ? tag.all : tag.getElementsByTagName('*'),
i = els.length,
childels = [];
while (--i > -1) {
if (els[i].parentNode === tag) {
childels.push(els[i]);
}
}
childels.sort(function() {
return 0.5 - Math.random();
});
i = childels.length;
while (--i > -1) {
tag.appendChild(childels[i]);
}
}
function Marq(c, tag) {
var p, u, s, a, ims, ic, i, marqContent, cObj = this;
this.mq = marqueeInit.ar[c];
if (this.mq.random) {
if (tag.getElementsByTagName && tag.getElementsByTagName('tr').length === 1 && tag.childNodes.length === 1) {
randthem(tag.getElementsByTagName('tr')[0]);
} else {
randthem(tag);
}
}
for (p in defaultconfig)
if ((this.mq.hasOwnProperty && !this.mq.hasOwnProperty(p)) || (!this.mq.hasOwnProperty && !this.mq[p]))
this.mq[p] = defaultconfig[p];
this.mq.style.width = !this.mq.style.width || isNaN(parseInt(this.mq.style.width)) ? '100%' : this.mq.style.width;
if (!tag.getElementsByTagName('img')[0])
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? tag.offsetHeight + 3 + 'px' : this.mq.style.height;
else
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? 'auto' : this.mq.style.height;
u = this.mq.style.width.split(/\d/);
this.cw = this.mq.style.width ? [parseInt(this.mq.style.width), u[u.length - 1]] : ['a'];
marqContent = trimTags(tag);
tag.className = tag.id = '';
tag.removeAttribute('class', 0);
tag.removeAttribute('id', 0);
if (ie)
tag.removeAttribute('className', 0);
tag.appendChild(tag.cloneNode(false));
tag.className = ['marquee', c].join('');
tag.style.overflow = 'hidden';
this.c = tag.firstChild;
this.c.appendChild(this.c.cloneNode(false));
this.c.style.visibility = 'hidden';
a = [
[req1, this.c.style],
[this.mq.style, this.c.style]
];
for (i = a.length - 1; i > -1; --i)
for (p in a[i][0])
if ((a[i][0].hasOwnProperty && a[i][0].hasOwnProperty(p)) || (!a[i][0].hasOwnProperty))
a[i][1][p.encamel()] = a[i][0][p];
this.m = this.c.firstChild;
if (this.mq.mouse === 'pause') {
this.c.onmouseover = function() {
cObj.mq.stopped = true;
};
this.c.onmouseout = function() {
cObj.mq.stopped = false;
};
}
this.m.style.position = 'absolute';
this.m.style.left = '-10000000px';
this.m.style.whiteSpace = 'nowrap';
if (ie5) this.c.firstChild.appendChild((this.m = document.createElement('nobr')));
if (!this.mq.noAddedSpace)
this.m.appendChild(document.createTextNode('\xa0'));
for (i = 0; marqContent[i]; ++i)
this.m.appendChild(marqContent[i]);
if (ie5) this.m = this.c.firstChild;
ims = this.m.getElementsByTagName('img');
if (ims.length) {
for (ic = 0, i = 0; i < ims.length; ++i) {
ims[i].style.display = 'inline';
if (!ims[i].alt && !this.mq.noAddedAlt) {
ims[i].alt = (tTRE[3].exec(ims[i].src)) || ('Image #' + [i + 1]);
if (!ims[i].title) {
ims[i].title = '';
}
}
ims[i].style.display = 'inline';
ims[i].style.verticalAlign = ims[i].style.verticalAlign || 'top';
if (typeof ims[i].complete === 'boolean' && ims[i].complete)
ic++;
else {
ims[i].onload = ims[i].onerror = function() {
if (++ic === ims.length)
cObj.setup(c);
};
}
if (ic === ims.length)
this.setup(c);
}
} else this.setup(c)
}
Marq.prototype.setup = function(c) {
if (this.mq.setup) return;
this.mq.setup = this;
var s, w, cObj = this,
exit = 10000;
if (this.c.style.height === 'auto')
this.c.style.height = this.m.offsetHeight + 4 + 'px';
this.c.appendChild(this.m.cloneNode(true));
this.m = [this.m, this.m.nextSibling];
if (typeof this.mq.initcontent === 'function') {
this.mq.initcontent.apply(this.mq, [this.m]);
}
if (this.mq.mouse === 'cursor driven') {
this.r = this.mq.neutral || 16;
this.sinc = this.mq.inc;
this.c.onmousemove = function(e) {
cObj.mq.stopped = false;
cObj.directspeed(e)
};
if (this.mq.moveatleast) {
this.mq.inc = this.mq.moveatleast;
if (this.mq.savedirection) {
if (this.mq.savedirection === 'reverse') {
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.direction === 'right' ? 'left' : 'right';
};
} else {
this.mq.savedirection = this.mq.direction;
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.savedirection;
};
}
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.mq.inc = cObj.mq.moveatleast;
};
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.slowdeath();
};
}
this.w = this.m[0].offsetWidth;
this.m[0].style.left = 0;
this.c.id = 'marq_kill_marg_bord';
this.m[0].style.top = this.m[1].style.top = Math.floor((this.c.offsetHeight - this.m[0].offsetHeight) / 2 - oldie) + 'px';
this.c.id = '';
this.c.removeAttribute('id', 0);
this.m[1].style.left = this.w + 'px';
s = this.mq.moveatleast ? Math.max(this.mq.moveatleast, this.sinc) : (this.sinc || this.mq.inc);
while (this.c.offsetWidth > this.w - s && --exit) {
w = isNaN(this.cw[0]) ? this.w - s : --this.cw[0];
if (w < 1 || this.w < Math.max(1, s)) {
break;
}
this.c.style.width = isNaN(this.cw[0]) ? this.w - s + 'px' : --this.cw[0] + this.cw[1];
}
this.c.style.visibility = 'visible';
this.runit();
}
Marq.prototype.slowdeath = function() {
var cObj = this;
if (this.mq.inc) {
this.mq.inc -= 1;
this.timer = setTimeout(function() {
cObj.slowdeath();
}, 100);
}
}
Marq.prototype.runit = function() {
var cObj = this,
d = this.mq.direction === 'right' ? 1 : -1;
if (this.mq.stopped || this.mq.stopMarquee) {
setTimeout(function() {
cObj.runit();
}, 300);
return;
}
if (this.mq.mouse != 'cursor driven')
this.mq.inc = Math.max(1, this.mq.inc);
if (d * parseInt(this.m[0].style.left) >= this.w)
this.m[0].style.left = parseInt(this.m[1].style.left) - d * this.w + 'px';
if (d * parseInt(this.m[1].style.left) >= this.w)
this.m[1].style.left = parseInt(this.m[0].style.left) - d * this.w + 'px';
this.m[0].style.left = parseInt(this.m[0].style.left) + d * this.mq.inc + 'px';
this.m[1].style.left = parseInt(this.m[1].style.left) + d * this.mq.inc + 'px';
setTimeout(function() {
cObj.runit();
}, 30 + (this.mq.addDelay || 0));
}
Marq.prototype.directspeed = function(e) {
e = e || window.event;
if (this.timer) clearTimeout(this.timer);
var c = this.c,
w = c.offsetWidth,
l = c.offsetLeft,
mp = (typeof e.pageX === 'number' ?
e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - l,
lb = (w - this.r) / 2,
rb = (w + this.r) / 2;
while ((c = c.offsetParent)) mp -= c.offsetLeft;
this.mq.direction = mp > rb ? 'left' : 'right';
this.mq.inc = Math.round((mp > rb ? (mp - rb) : mp < lb ? (lb - mp) : 0) / lb * this.sinc);
}
Marq.prototype.contains = function(e) {
if (e && e.relatedTarget) {
var c = e.relatedTarget;
if (c === this.c) return true;
while ((c = c.parentNode))
if (c === this.c) return true;
}
return false;
}
function resize() {
for (var s, w, m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
s = m.mq.moveatleast ? Math.max(m.mq.moveatleast, m.sinc) : (m.sinc || m.mq.inc);
m.c.style.width = m.mq.style.width;
m.cw[0] = m.cw.length > 1 ? parseInt(m.mq.style.width) : 'a';
while (m.c.offsetWidth > m.w - s) {
w = isNaN(m.cw[0]) ? m.w - s : --m.cw[0];
if (w < 1) {
break;
}
m.c.style.width = isNaN(m.cw[0]) ? m.w - s + 'px' : --m.cw[0] + m.cw[1];
}
}
}
}
function unload() {
for (var m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].persist && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
m.cookie.set(m.mq.uniqueid, m.m[0].style.left + ':' + m.m[1].style.left + ':' + m.mq.direction);
}
}
}
if (window.addEventListener) {
window.addEventListener('resize', resize, false);
window.addEventListener('unload', unload, false);
} else if (window.attachEvent) {
window.attachEvent('onresize', resize);
window.attachEvent('onunload', unload);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="marquee" id="mycrawler">
Those confounded friars dully buzz that faltering jay. An appraising tongue acutely causes our courageous hogs. Their fitting submarines deftly break your approving improvisations. Her downcast taxonomies actually box up those disgusted turtles.
</div>
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)
});