Related
I'm making a game in Phaser which looks like that:
player has to catch the eggs, so the eggs (which are made from gameState.eggs = this.physics.add.group();) have a certain velocity while on the ramp, but then once they're off the ramp, i want to authomatically setVelocity() to one with 0 for x coordinate, instead of just shooting across the screen.
Here's my egg generating function:
function eggGen() {
let num = Math.random();
let xCoord, yCoord, eggDirection, eggAnimation, velocityX
if (num < .5) {
xCoord = 100;
eggDirection = 'eggLeft';
eggAnimation = 'rollingLeft'
velocityX = this.velocityX;
if (num < .25) {
yCoord = 232;
} else {
yCoord = 382;
}
} else {
xCoord = 700;
eggDirection = 'eggRight';
eggAnimation = 'rollingRight';
velocityX = -(this.velocityX)
if (num < .75) {
yCoord = 232;
} else {
yCoord = 382;
}
}
let egg = gameState.eggs.create(xCoord, yCoord, eggDirection).setVelocity(velocityX, this.velocityY).setScale(.6);
if (egg.x > 220 && egg.x < 580) {
egg.setVelocity(0, this.velocityY);
}
egg.anims.play(eggAnimation);
}
the last conditional is what i hoped would do the magic, but it doesn't do anything. To clarify, eggGen function is called inside this.time.addEvent();
Without knowing your code (and assuming arcade physics is used), I would:
Just check in the update function, of the scene, if a egg is "on the ramp" and has a x-velocity of 0
function update(){
// ...
gameState.eggs.getChildren().forEach(egg => {
if(egg.velocity.x > 0 && (egg.x > 220 || egg.x < 580)) {
// ... stop velocity.x or set the whole velocity new
egg.velocity.x = 0;
}
});
// ...
}
Here a mini Demo:
It just covers the basics
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 300,
height: 183,
physics: {
default: 'arcade',
arcade: {
debug: true,
}
},
scene: {
create,
update
},
banner: false
};
let objectGroup;
function create () {
objectGroup = this.physics.add.group();
this.time.addEvent({ delay: 500, callback: createObject, callbackScope: this, loop: true });
}
function createObject(){
let spawnLeft = Phaser.Math.Between(0, 1);
let obj = this.add.rectangle(spawnLeft ? 0 : config.width, 0, 10, 10, 0xff0000);
this.physics.add.existing(obj);
objectGroup.add(obj);
obj.body.setVelocity((spawnLeft ? 1 : -1) * 75, 30);
}
function update(){
if(!objectGroup)
return;
objectGroup.getChildren().forEach(obj =>{
if(obj.body.velocity.x > 0 && (obj.x > 100 && obj.x < 150) || (obj.x > config.width - 150 && obj.x < config.width - 100) ){
// Just to keep the same speed, even after changing direction
let speed = obj.body.velocity.length();
obj.body.velocity.x = 0;
obj.body.velocity.y = speed;
}
});
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
This is a game where the monkey moves around the platforms collecting coins. I want to have the monkey shoot a banana when the down arrow and left arrow are pressed.
How would I create the bullet?
I have the keypress for the shooting and it calls shootR or shootL depending on which arrow is pressed. What I need is to create the projectile and have it move to the right or left(not affected by gravity). Can I get some help creating this projectile as var proj = projs.create(x, y, 'proj'); is not working. I am good at coding with js and phaser is new to me so help would be greatly appreciated.
var config = {
type: Phaser.AUTO,
width: 1900,
height: 1000,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var main = document.getElementById("startBtn")
var heading = document.getElementById("header")
var gameOver
var platforms;
var score = 0;
var scoreText;
var leafAm = 0
var leafText
var gunAm = 0
var ammoAm = 0
var ammoText
var monkeyType = "monkey"
var delay = 0
function start() {
game = new Phaser.Game(config);
main.innerHTML = ''
heading.innerHTML += '<h1 class="header2" onclick="shop()"><u>Click To Access Shop</u></h1>'
}
function preload() {
this.load.image('Background', 'assets/Background.jpg');
this.load.image('ground', 'assets/platform.png');
this.load.image('coin', 'assets/coin.png');
this.load.image('redCoin', 'assets/redCoin.png');
this.load.spritesheet('monkey', 'assets/monkey.png', { frameWidth: 600, frameHeight: 720 });
this.load.spritesheet('proj', 'assets/bullet.png', { frameWidth: 200, frameHeight: 200 });
}
function create() {
this.add.image(500, 275, 'Background').setScale(3);
platforms = this.physics.add.staticGroup();
platforms.create(200, 650, 'ground').setScale(0.15).refreshBody();
platforms.create(600, 400, 'ground').setScale(0.15).refreshBody();
platforms.create(1600, 650, 'ground').setScale(0.15).refreshBody();
platforms.create(750, 100, 'ground').setScale(0.15).refreshBody();
platforms.create(850, 750, 'ground').setScale(0.15).refreshBody();
platforms.create(100, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(400, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(700, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1000, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1300, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1600, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1900, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1800, 800, 'ground').setScale(0.15).refreshBody();
platforms.create(250, 250, 'ground').setScale(0.15).refreshBody();
platforms.create(1000, 500, 'ground').setScale(0.15).refreshBody();
platforms.create(1150, 220, 'ground').setScale(0.15).refreshBody();
player = this.physics.add.sprite(100, 450, 'monkey').setScale(0.075);
this.physics.add.collider(player, platforms);
player.setBounce(0.2);
player.setCollideWorldBounds(true);
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('monkey', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{ key: 'monkey', frame: 4 }],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('monkey', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'shoot',
frames: this.anims.generateFrameNumbers('proj', { start: 0, end: 3 }),
framerate: 15,
repeat: -1
})
coins = this.physics.add.group({
key: 'coin',
repeat: 10,
setXY: { x: 12, y: 0, stepX: 150 }
});
coins.children.iterate(function (child) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
child.setScale(0.05)
});
this.physics.add.collider(coins, platforms);
this.physics.add.overlap(player, coins, collectCoin, null, this);
redCoins = this.physics.add.group();
this.physics.add.collider(redCoins, platforms);
this.physics.add.collider(player, redCoins, hitredCoin, null, this);
projs = this.physics.add.group()
this.physics.add.collider(projs, platforms)
this.physics.add.collider(projs, redCoins, shootredCoin, null, this)
scoreText = this.add.text(16, 16, 'Score: 0ā“', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
ammoText = this.add.text(16, 66, 'Ammo: 0š', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
leafText = this.add.text(16, 116, 'Shields: 0š', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
}
function update() {
cursors = this.input.keyboard.createCursorKeys();
if (cursors.down.isDown && cursors.left.isDown && delay == 0) {
shootL()
} else if (cursors.down.isDown && cursors.right.isDown && delay == 0) {
shootR()
}
if (cursors.left.isDown) {
player.setVelocityX(-240);
player.anims.play('left', true);
}
else if (cursors.right.isDown) {
player.setVelocityX(240);
player.anims.play('right', true);
}
else {
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-330);
}
}
function collectCoin(player, coin) {
coin.disableBody(true, true);
score += 1;
scoreText.setText('Score: ' + score + 'ā“');
if (coins.countActive(true) === 0) {
coins.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
var x = Phaser.Math.Between(0, 800);
var redCoin = redCoins.create(x, 16, 'redCoin').setScale(0.05);
redCoin.setBounce(1);
redCoin.setCollideWorldBounds(true);
redCoin.setVelocity(Phaser.Math.Between(-300, 300), 20);
}
}
function shootR(player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
// proj.setVelocityX(-240);
// player.anims.play('shoot', true);
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + 'š');
delay = 1
this.time.delayedCall(3000, delayer, null, this);
}
function shootL(player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + 'š');
delay = 1
this.time.delayedCall(3000, delayer, null, this);
}
function hitredCoin(player, redCoin) {
if (leafAm > 0) {
leafAm -= 1
leafText.setText('Shields: ' + leafAm + 'š');
redCoin.disableBody(true, true);
var x = Phaser.Math.Between(0, 800);
var redCoin = redCoins.create(x, 16, 'redCoin').setScale(0.05);
redCoin.setBounce(1);
redCoin.setCollideWorldBounds(true);
redCoin.setVelocity(Phaser.Math.Between(-300, 300), 20);
} else {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
gameOver = true;
this.time.delayedCall(3000, restart, null, this);
}
}
function shootredCoin(projs, redCoin) {
redCoin.disableBody(true, true);
projs.disableBody(true, true);
}
function restart() {
score = 0
var leafAm = 0
var gunAm = 0
var ammoAm = 0
this.scene.stop();
this.scene.start();
}
function shop() {
main.innerHTML = `<button class="shopBackground"></button>`
main.innerHTML += `<button class="shop1">Shop</button>`
main.innerHTML += `<button class="shop2">Warning: Shop Fast, you can still die</button>`
main.innerHTML += `<button class="shop3" onclick = "buy1()">Banana Gun...ā“100.00<br>(Ability to shoot bananas)<br>click here to buy</button>`
main.innerHTML += `<button class="shop4" onclick = "buy2()">Leaf Shield...ā“30.00<br>(Protection from 1 hit)<br>click here to buy</button>`
main.innerHTML += `<button class="shop5" onclick = "buy3()">Bananas...ā“10.00<br>(Extra ammo, gun comes with 1)<br>click here to buy</button>`
main.innerHTML += `<button class="shop6">ā“ is score</button>`
main.innerHTML += `<button class="shop7" onclick="main.innerHTML = ''">Back To Game</button>`
main.innerHTML += `<img src="/assets/banana1.png" class="banana1">`
main.innerHTML += `<img src="/assets/banana2.png" class="banana2">`
main.innerHTML += `<img src="/assets/leaf.png" class="leaf">`
}
function buy1() {
if (score > 99 && gunAm < 1) {
gunAm += 1
ammoAm += 1
score -= 100
scoreText.setText('Score: ' + score + 'ā“');
alert("You have bought a gun \nClick the down arrow and either left or right to shoot\nShooting costs ammo but bullets detroy the red orbs\nEnjoy and good luck")
} else if (gunAm > 0) {
alert("You already have one")
} else {
alert("Not enough score")
}
}
function buy2() {
if (score > 29) {
leafAm += 1
score -= 30
scoreText.setText('Score: ' + score + 'ā“');
leafText.setText('Shields: ' + leafAm + 'š');
} else {
alert("Not enough score")
}
}
function buy3() {
if (score > 9) {
ammoAm += 1
score -= 10
scoreText.setText('Score: ' + score + 'ā“');
ammoText.setText('Ammo: ' + ammoAm + 'š');
;
} else {
alert("Not enough score")
}
}
function delayer() {
delay = 0
}
Any Help Or Ideas On This Would Be Appreciated.
There is also some HTML and CSS but those parts aren't affecting it or at least they shouldn't be
There are somethings to unpack here,
Btw.: usually on stackoverflow you should only post the essential code: https://stackoverflow.com/help/minimal-reproducible-example this makes helping easy
But back to your question:
First of all, the functions shootR and shootL don't work because, they are defined with parameters, but they are not passed. So the player parameter is overloading the global player variable (btw. the global player variable is never declared with var, let or const)
function definitions:
function shootR(player, redCoin, proj)
...
functions being called:
...
if (cursors.down.isDown && cursors.left.isDown && delay == 0) {
shootL()
} else if (cursors.down.isDown && cursors.right.isDown && delay == 0) {
shootR()
}
...
Quick fix: pass the player parameter, example: shootR(player)
Second the this in the shootR and shootL functions, are not pointing to the right object.
Quick fix: Pass the scene to the function, example: shootR(this, player) and alter the functions to:
function shootL(scene, player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + 'š');
delay = 1
scene.time.delayedCall(3000, delayer, null, scene);
}
third to "remove the gravity", just use
Quick fix: proj.body.setAllowGravity(false); in the shootR and shootL (here is the link to the documentation ) functions,
And Last just add the velocity for the bullet proj.setVelocityX()
btw.: the code could be improved using classes and their properties, I would suggest looking at the phaser examples
https://phaser.io/examples/v3/view/scenes/scene-from-class and/or https://phaser.io/examples/v3/view/scenes/scene-from-es6-class on how to use classes for scene, this could remove many problems. And you would not need to use global varibales or pass so many parameters.
I have added a javascript function in Wordpress. Here is the code for this function:
/*
* CraftMap
* author: Marcin Dziewulski
* web: http://www.jscraft.net
* email: info#jscraft.net
* license: http://www.jscraft.net/licensing.html
*/
(function($) {
$.fn.craftmap = function(options) {
var D = {
cookies: false,
fullscreen: false,
container: {
name: 'imgContent'
},
image: {
width: 1475,
height: 1200,
name: 'imgMap'
},
map: {
position: 'center'
},
marker: {
name: 'marker',
center: true,
popup: true,
popup_name: 'popup',
onClick: function(marker, popup){},
onClose: function(marker, popup){}
},
controls: {
init: true,
name: 'controls',
onClick: function(marker){}
},
preloader: {
init: true,
name: 'preloader',
onLoad: function(img, dimensions){}
}
}; // default settings
var S = $.extend(true, D, options);
return this.each(function(){
alert("?");
var M = $(this),
IMG = M.find('.'+S.image.name),
P = {
init: function(){
this._container.init();
if (S.fullscreen) {
this.fullscreen.init();
this.fullscreen.resize();
}
this._globals.init();
if (S.preloader.init) this.preloader.init();
this.map.init();
this.marker.init();
if (S.controls.init) this.controls.init();
},
_container: {
init: function(){
P._container.css();
P._container.wrap();
},
css: function(){
var max = {
width: '100%',
height: '100%'
};
IMG.css(max);
var css = {
position: 'relative',
overflow: 'hidden',
cursor: 'move'
}
M.css(css);
},
wrap: function(){
var css = {
zIndex: '1',
position: 'absolute',
width: S.image.width,
height: S.image.height
}
M.wrapInner($('<div />').addClass(S.container.name).css(css));
}
},
_globals: {
init: function(){
C = M.find('.'+S.container.name),
MARKER = C.find('.'+S.marker.name),
md = false, mx = 0, my = 0, ex = 0, ey = 0, delta = 0, mv = [], interval = 0,
D = {
w: M.width(),
h: M.height()
},
I = {
w: C.width(),
h: C.height()
}
if (S.controls.init){
CONTROLS = $('.'+S.controls.name).find('a');
}
}
},
_mouse: {
get: function(e){
var x = e.pageX,
y = e.pageY;
return {'x': x, 'y': y}
},
update: function(e){
var mouse = P._mouse.get(e),
x = mouse.x,
y = mouse.y,
movex = x-mx,
movey = y-my,
top = ey+movey,
left = ex+movex,
check = P.map.position.check(left, top),
css = {
top: check.y,
left: check.x
}
C.css(css);
if (S.cookies){
P.cookies.create('position', check.x + ',' + check.y, 7);
}
},
decelerate: function(e){
var l = mv.length, timer = 0;
if (l){
var tc = 20;
interval = setInterval(function(){
var position = C.position(), left = position.left, top = position.top,
remain = (tc-timer)/tc,
last = l-1,
xd = (mv[last].x-mv[0].x)/l,
yd = (mv[last].y-mv[0].y)/l,
vx = xd*remain,
vy = yd*remain,
coords = P.map.position.check(vx+left, vy+top),
css = {
left: coords.x,
top: coords.y
};
C.css(css);
++timer;
if (timer == tc){
clearInterval(interval);
timer = 0;
}
}, 40);
}
},
wheel: {
init: function(e){
M.handle = function(e){
e.preventDefault();
if (!e) {
e = window.event;
}
if (e.wheelDelta) {
delta = e.wheelDelta/120;
if (window.opera) {
delta = -delta;
}
} else if (e.detail) {
delta = -e.detail/3;
}
}
if (window.addEventListener){
window.addEventListener('DOMMouseScroll', M.handle, false);
}
window.onmousewheel = document.onmousewheel = M.handle;
},
remove: function(){
if (window.removeEventListener){
window.removeEventListener('DOMMouseScroll', M.handle, false);
}
window.onmousewheel = document.onmousewheel = null;
}
}
},
fullscreen: {
init: function(){
var win = $(window), w = win.width(), h = win.height(),
css = {
width: w,
height: h
}
M.css(css);
},
resize: function(){
$(window).resize(function(){
P.fullscreen.init();
D = {
w: M.width(),
h: M.height()
}
});
}
},
cookies: {
create: function(name, value, days) {
if (days) {
var date = new Date(), set = date.getTime() + (days * 24 * 60 * 60 * 1000);
date.setTime(set);
var expires = '; expires=' + date.toGMTString();
} else {
var expires = '';
}
document.cookie = name+'='+value+expires+'; path=/';
},
erase: function(name) {
cookies.create(name, '', -1);
},
read: function(name) {
var e = name + '=',
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' '){
c = c.substring(1, c.length);
}
if (c.indexOf(e) == 0){
return c.substring(e.length,c.length);
}
}
return null;
}
},
preloader: {
init: function(){
var img = new Image(),
src = IMG.attr('src');
P.preloader.create();
$(img).addClass(S.image.name).attr('src', src).load(function(){
var t = $(this),
css = {
width: this.width,
height: this.height
}
t.css(css);
IMG.remove();
P.preloader.remove();
S.preloader.onLoad.call(this, t, css);
}).appendTo(C);
},
create: function(){
var css = {
position: 'absolute',
zIndex: '10',
top: '0',
left: '0',
width: '100%',
height: '100%'
}
M.append($('<div />').addClass(S.preloader.name).css(css));
},
remove: function(){
M.find('.'+S.preloader.name).fadeOut(400, function(){
var t = $(this);
t.remove();
});
}
},
map: {
init: function(){
P.map.position.set();
P.map.move();
},
position: {
set: function(){
if (S.cookies){
if (typeof P.cookies.read('position') != 'null') {
var position = P.cookies.read('position').split(','),
x = position[0],
y = position[1];
} else {
var x = (D.w-I.w)/2,
y = (D.h-I.h)/2;
}
} else {
var position = S.map.position;
switch (position){
case 'center':
var x = (D.w-I.w)/2,
y = (D.h-I.h)/2;
break;
case 'top_left':
var x = 0,
y = 0;
break;
case 'top_right':
var x = D.w-I.w,
y = 0;
break;
case 'bottom_left':
var x = 0,
y = D.h-I.h;
break;
case 'bottom_right':
var x = D.w-I.w,
y = D.h-I.h;
break;
default:
var coords = position.split(' '),
x = -(coords[0]),
y = -(coords[1]),
coords = P.map.position.check(x, y),
x = coords.x,
y = coords.y;
}
}
var css = { top: y, left: x }
C.css(css);
},
check: function(x, y){
if (y < (D.h-I.h)){
y = D.h-I.h;
} else if (y > 0){
y = 0;
}
if (x < (D.w-I.w)){
x = D.w-I.w;
} else if (x>0){
x = 0;
}
return {'x': x, 'y': y}
}
},
move: function(){
C.bind({
mousedown: function(e){
md = true;
var mouse = P._mouse.get(e);
mx = mouse.x,
my = mouse.y;
var el = C.position();
ex = el.left,
ey = el.top;
mv = [];
clearInterval(interval);
P._mouse.update(e);
return false;
},
mousemove: function(e){
if (md) {
P._mouse.update(e);
var mouse = P._mouse.get(e),
coords = {
x: mouse.x,
y: mouse.y
}
mv.push(coords);
if (mv.length > 15){
mv.pop();
}
}
return false;
},
mouseup: function(e){
if (md) md = false;
P._mouse.decelerate(e);
return false;
},
mouseout: function(){
if (md) md = false;
P._mouse.wheel.remove();
return false;
},
mouseover: function(e){
P._mouse.wheel.init(e);
return false;
},
mousewheel: function(e){
P._zoom.init(e);
}
});
}
},
_zoom: {
init: function(e){}
},
marker: {
init: function(){
P.marker.set();
P.marker.open();
P.marker.close();
},
set: function(){
MARKER.each(function(){
var t = $(this), position = t.attr('data-coords').split(',');
x = parseInt(position[0]), y = parseInt(position[1]),
css = {
position: 'absolute',
zIndex: '2',
top: y,
left: x
}
t.css(css);
}).wrapInner($('<div />').addClass(S.marker.name+'Content').hide());
},
open: function(){
MARKER.live('click', function(){
var t = $(this), id = t.attr('id'), marker = S.marker, w = t.width(), h = t.height(),
position = t.position(), x = position.left, y = position.top, id = t.attr('id'),
html = t.find('.'+marker.name+'Content').html();
if (marker.center){
var cy = -y+D.h/2-h/2,
cx = -x+D.w/2-w/2,
c = P.map.position.check(cx, cy),
animate = {
top: c.y,
left: c.x
};
C.animate(animate);
}
if (marker.popup){
$('.'+marker.popup_name).remove();
var css = {
position:'absolute',
zIndex:'3'
}
t.after(
$('<div />').addClass(marker.popup_name+' '+id).css(css).html(html).append(
$('<a />').addClass('close')
)
);
var POPUP = t.next('.'+marker.popup_name),
pw = POPUP.innerWidth(),
ph = POPUP.innerHeight(),
x0 = 0, y0 = 0;
if (x-pw < 0){
x0 = x;
} else if (x+pw/2 > I.w){
x0 = x-pw+w;
} else {
x0 = x-(pw/2-w/2);
}
if (y-ph < 0){
y0 = y+h+h/1.5;
} else {
y0 = y-ph-h/1.5;
}
if (x-pw < 0 && y-ph < 0){
x0 = x+w*2;
y0 = y-h/2;
} else if (y-ph < 0 && x+pw/2 > I.w){
x0 = x-pw-w/2;
y0 = y-h/2;
} else if (y+ph > I.h && x+pw/2 > I.w){
x0 = x-pw+w;
y0 = y-ph-h/2;
} else if (y+ph > I.h && x-pw < 0){
x0 = x;
y0 = y-ph-h/2;
}
var css = {
left: x0,
top: y0
}
POPUP.css(css);
}
P.controls.active.set(id);
marker.onClick.call(this, t, POPUP);
return false;
});
},
close: function(){
C.find('.close').live('click', function(){
var t = $(this), popup = t.parents('.'+S.marker.popup_name), marker = popup.prev('.'+S.marker.name);
popup.remove();
P.controls.active.remove();
S.marker.onClose.call(this, marker, popup);
return false;
});
}
},
controls: {
init: function(){
P.controls.set();
},
set: function(){
CONTROLS.click(function(){
var t = $(this), rel = t.attr('rel');
div = C.find('.'+ S.marker.name).filter('#'+rel);
div.trigger('click');
S.controls.onClick.call(this, div);
return false;
});
},
active: {
set: function(id){
if (S.controls.init){
CONTROLS.removeClass('active').filter(function(){
return this.rel == id;
}).addClass('active');
}
},
remove: function(){
if (S.controls.init) {
CONTROLS.removeClass('active');
}
}
}
}
}
P.init();
});
};
}(jQuery));
The problem is that the return in never called. How can I fix this problem? I have seen that this script works with jQuery version 1.7 or 1.8. So I told wordpress to load jquery 1.8.
I've created a new js file and I'm loading it using wordpress's function: wp_enqueue_script. So everything should work fine.
The return function is never called. What should I do/change in order to make it work.
In function setupGameData() I have parametars for 2 cars. In first car speed is 3.00 and second car speed is 3.50. If you click on button "Watch race" you can see first car 3.00 is faster than second car 3.50. How to repair code to see 3.50 is faster than 3.00.
/*jslint plusplus: true, sloppy: true, indent: 4 */
(function () {
"use strict";
// this function is strict...
}());
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// Globals
var canvas = null,
ctx = null,
background = null,
car_sprite = null,
game_data = null,
CAR_WIDTH = 170,
CAR_HEIGHT = 37,
STEP_COUNT_MILLISECONDS = 1000 / 30,
RACE_LENGTH = 20,
RACE_FINISH_LINE_X = 770,
iTime = 0,
iFinishPlace = 1,
random_graph;
function clearCanvas() {
// clear canvas
ctx.clearRect(0, 0, canvas.height, canvas.width);
}
function drawBackground() {
clearCanvas();
ctx.drawImage(background, 0, -400);
loadCarSprite();
}
function loadBackground() {
// Load the timer
background = new Image();
background.src = 'http://www.upslike.net/imgdb/race-scence-f7bf19.png';
background.onload = drawBackground;
}
function setupGameData() {
var json =
{
cars:
[
{
"colour": 'blue',
"x": 0,
"y": 50,
"spritex": 0,
"spritey": 0,
"graph": null,
"step": 77,
"position": null,
"speed": 3.00,
"speed_late": 0.28 },
{
"colour": 'red',
"x": 0,
"y": 110,
"spritex": 0,
"spritey": 37,
"graph": null,
"step": 39,
"position": null,
"speed": 3.50,
"speed_late": 0.48 }
],
graphs:
[
[0,5,10,20,40,60,70],
[0,10,20,30,40,50,60],
[0,20,39,40,50,55,58],
[0,10,20,30,40,50,55],
[0,25,45,47,49,50,52],
[0,10,20,29,38,45,50],
[0,15,20,25,30,40,45],
[0,2,4,8,20,30,40],
[0,5,10,15,20,25,30],
[0,1,3,14,15,22,30],
[0,5,11,14,17,22,25],
[0,20,30,44,67,72,90],
[0,2,7,24,47,52,65],
[0,2,9,20,40,52,70]
]
};
random_graph = Math.floor( Math.random() * json.graphs.length );
return json;
}
function drawCar(car) {
// Draw the car onto the canvas
ctx.drawImage(car_sprite,
car.spritex, car.spritey,
CAR_WIDTH, CAR_HEIGHT,
car.x-70 + car.step, car.y,
CAR_WIDTH, CAR_HEIGHT);
drawText(car);
}
function drawCars() {
var iCarCounter;
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
drawCar(game_data.cars[iCarCounter]);
}
}
function initCar(current_car) {
current_car.graph = random_graph;
}
function initGameState() {
var iCarCounter;
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
initCar(game_data.cars[iCarCounter]);
}
}
function getPositionAtTime(graph_index, percentageElapsed, current_car) {
var graph = game_data.graphs[graph_index],
iNumberOfGraphPoints = graph.length,
iGraphPosition = null,
iFloor = null,
iCeil = null,
p = null;
position = null;
graph = graph.map( function( val, i ) {
if ( i === 0 ) {
return val;
}
var car_speed = undefined === current_car.speed ? 1 : current_car.speed,
car_speed_late = undefined === current_car.speed_late ? car_speed : current_car.speed_late;
return ( i < Math.floor( graph.length / 2 ) ) ? car_speed : car_speed_late;
});
iGraphPosition = (iNumberOfGraphPoints / 100) * percentageElapsed;
iFloor = Math.floor(iGraphPosition);
iCeil = Math.ceil(iGraphPosition);
if(iGraphPosition === iFloor) {
position = graph[iFloor];
} else if(iGraphPosition === iCeil) {
position = graph[iCeil];
} else {
p = (graph[iCeil] - graph[iFloor]) / 100;
position = ((iGraphPosition - iFloor) * 100) * p + graph[iFloor];
}
return position;
}
function redrawRoadSection() {
ctx.drawImage(background, 0, 400, 1000, 200, 0, 0, 1000, 200);
}
function graphPosToScreenPos() {
return (900 / 100) * (position / 60 * 100);
}
function updateDebugWindow() {
// Debug window
var time = document.getElementById('time');
if(time !== null) {
time.value = iTime / 1000;
}
}
function drawText(current_car) {
if(current_car.position !== null) {
ctx.strokeStyle = "black";
ctx.font = "normal 12px Facebook Letter Faces";
ctx.strokeText(current_car.position, RACE_FINISH_LINE_X + current_car.step + 110, current_car.y + 25);
}
}
function moveCar(iCarCounter) {
var current_car = game_data.cars[iCarCounter],
seconds = iTime / 1000,
percentageElapsed = (seconds / RACE_LENGTH) * 100,
a = 20,
velocity = 2,
position = getPositionAtTime(current_car.graph, percentageElapsed,current_car);
if(current_car.x < RACE_FINISH_LINE_X) {
current_car.x = graphPosToScreenPos(position) + (velocity * seconds) + (1/2 * a * Math.pow(seconds, 2));
}
else {
current_car.x = RACE_FINISH_LINE_X;
if(current_car.position === null) {
current_car.position = iFinishPlace++;
}
}
drawCar(current_car);
}
function initCars() {
game_data = setupGameData();
initGameState();
drawCars();
}
function stopLoop() {
iTime = 0;
iFinishPlace = 1;
}
function startRace() {
var iCarCounter;
redrawRoadSection();
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
moveCar(iCarCounter);
}
updateDebugWindow();
if(iFinishPlace > 4) {
stopLoop();
} else {
iTime += STEP_COUNT_MILLISECONDS;
requestAnimFrame(startRace);
}
}
function startLoop() {
stopLoop();
requestAnimFrame(startRace);
}
function loadCarSprite() {
// Load the timer
car_sprite = new Image();
car_sprite.src = 'http://www.upslike.net/imgdb/car-scene-53401b.png';
car_sprite.onload = initCars;
}
function draw() {
// Main entry point got the motion canvas example
canvas = document.getElementById('motion');
// Canvas supported?
if (canvas.getContext) {
ctx = canvas.getContext('2d');
loadBackground();
} else {
alert("Canvas not supported!");
}
}
<script>
window.onload = function() {
draw();
}
</script>
<center><canvas id="motion" width="1000px" height="200px"></canvas></center>
<div style="position: absolute; top: 0px; left:65px;">
<div id="alerter" class="hid">
<input id="loop" onclick="javascript:initCars(); startLoop();" type="button" class="prikaz" value="Watch race">
</div>
</div>
</br>
CodePen
First thing I would do is use console.log in your car movement function to see what speed is, to me it looks like your car speed is being converted to an int instead of a double so your speed 3.50 is 3.00.
Also in your moveCar function you are setting the velocity to 2 and using that in your function, shouldn't you be using your speed variable?
It is also depend on speed late(Json). If you increase blue car 'speed late' then blue car speed is fast. And increase red car 'speed late' then red car speed is fast.
/*jslint plusplus: true, sloppy: true, indent: 4 */
(function () {
"use strict";
// this function is strict...
}());
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// Globals
var canvas = null,
ctx = null,
background = null,
car_sprite = null,
game_data = null,
CAR_WIDTH = 170,
CAR_HEIGHT = 37,
STEP_COUNT_MILLISECONDS = 1000 / 30,
RACE_LENGTH = 20,
RACE_FINISH_LINE_X = 770,
iTime = 0,
iFinishPlace = 1,
random_graph;
function clearCanvas() {
// clear canvas
ctx.clearRect(0, 0, canvas.height, canvas.width);
}
function drawBackground() {
clearCanvas();
ctx.drawImage(background, 0, -400);
loadCarSprite();
}
function loadBackground() {
// Load the timer
background = new Image();
background.src = 'http://www.upslike.net/imgdb/race-scence-f7bf19.png';
background.onload = drawBackground;
}
function setupGameData() {
var json =
{
cars:
[
{
"colour": 'blue',
"x": 0,
"y": 50,
"spritex": 0,
"spritey": 0,
"graph": null,
"step": 77,
"position": null,
"speed": 3.55,
"speed_late": 1 },
{
"colour": 'red',
"x": 0,
"y": 110,
"spritex": 0,
"spritey": 37,
"graph": null,
"step": 39,
"position": null,
"speed": 3.55,
"speed_late": 19 }
],
graphs:
[
[0,5,10,20,40,60,70],
[0,10,20,30,40,50,60],
[0,20,39,40,50,55,58],
[0,10,20,30,40,50,55],
[0,25,45,47,49,50,52],
[0,10,20,29,38,45,50],
[0,15,20,25,30,40,45],
[0,2,4,8,20,30,40],
[0,5,10,15,20,25,30],
[0,1,3,14,15,22,30],
[0,5,11,14,17,22,25],
[0,20,30,44,67,72,90],
[0,2,7,24,47,52,65],
[0,2,9,20,40,52,70]
]
};
random_graph = Math.floor( Math.random() * json.graphs.length );
return json;
}
function drawCar(car) {
// Draw the car onto the canvas
ctx.drawImage(car_sprite,
car.spritex, car.spritey,
CAR_WIDTH, CAR_HEIGHT,
car.x-70 + car.step, car.y,
CAR_WIDTH, CAR_HEIGHT);
drawText(car);
}
function drawCars() {
var iCarCounter;
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
drawCar(game_data.cars[iCarCounter]);
}
}
function initCar(current_car) {
current_car.graph = random_graph;
}
function initGameState() {
var iCarCounter;
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
initCar(game_data.cars[iCarCounter]);
}
}
function getPositionAtTime(graph_index, percentageElapsed, current_car) {
var graph = game_data.graphs[graph_index],
iNumberOfGraphPoints = graph.length,
iGraphPosition = null,
iFloor = null,
iCeil = null,
p = null;
position = null;
graph = graph.map( function( val, i ) {
if ( i === 0 ) {
return val;
}
var car_speed = undefined === current_car.speed ? 1 : current_car.speed,
car_speed_late = undefined === current_car.speed_late ? car_speed : current_car.speed_late;
return ( i < Math.floor( graph.length / 2 ) ) ? car_speed : car_speed_late;
});
iGraphPosition = (iNumberOfGraphPoints / 100) * percentageElapsed;
iFloor = Math.floor(iGraphPosition);
iCeil = Math.ceil(iGraphPosition);
if(iGraphPosition === iFloor) {
position = graph[iFloor];
} else if(iGraphPosition === iCeil) {
position = graph[iCeil];
} else {
p = (graph[iCeil] - graph[iFloor]) / 100;
position = ((iGraphPosition - iFloor) * 100) * p + graph[iFloor];
}
return position;
}
function redrawRoadSection() {
ctx.drawImage(background, 0, 400, 1000, 200, 0, 0, 1000, 200);
}
function graphPosToScreenPos() {
return (900 / 100) * (position / 60 * 100);
}
function updateDebugWindow() {
// Debug window
var time = document.getElementById('time');
if(time !== null) {
time.value = iTime / 1000;
}
}
function drawText(current_car) {
if(current_car.position !== null) {
ctx.strokeStyle = "black";
ctx.font = "normal 12px Facebook Letter Faces";
ctx.strokeText(current_car.position, RACE_FINISH_LINE_X + current_car.step + 110, current_car.y + 25);
}
}
function moveCar(iCarCounter) {
var current_car = game_data.cars[iCarCounter],
seconds = iTime / 1000,
percentageElapsed = (seconds / RACE_LENGTH) * 100,
a = 20,
velocity = 2,
position = getPositionAtTime(current_car.graph, percentageElapsed,current_car);
if(current_car.x < RACE_FINISH_LINE_X) {
current_car.x = graphPosToScreenPos(position) + (velocity * seconds) + (1/2 * a * Math.pow(seconds, 2));
}
else {
current_car.x = RACE_FINISH_LINE_X;
if(current_car.position === null) {
current_car.position = iFinishPlace++;
}
}
drawCar(current_car);
}
function initCars() {
game_data = setupGameData();
initGameState();
drawCars();
}
function stopLoop() {
iTime = 0;
iFinishPlace = 1;
}
function startRace() {
var iCarCounter;
redrawRoadSection();
for(iCarCounter = 0; iCarCounter < game_data.cars.length; iCarCounter++) {
moveCar(iCarCounter);
}
updateDebugWindow();
if(iFinishPlace > 4) {
stopLoop();
} else {
iTime += STEP_COUNT_MILLISECONDS;
requestAnimFrame(startRace);
}
}
function startLoop() {
stopLoop();
requestAnimFrame(startRace);
}
function loadCarSprite() {
// Load the timer
car_sprite = new Image();
car_sprite.src = 'http://www.upslike.net/imgdb/car-scene-53401b.png';
car_sprite.onload = initCars;
}
function draw() {
// Main entry point got the motion canvas example
canvas = document.getElementById('motion');
// Canvas supported?
if (canvas.getContext) {
ctx = canvas.getContext('2d');
loadBackground();
} else {
alert("Canvas not supported!");
}
}
<script>
window.onload = function() {
draw();
}
</script>
<center><canvas id="motion" width="1000px" height="200px"></canvas></center>
<div style="position: absolute; top: 0px; left:65px;">
<div id="alerter" class="hid">
<input id="loop" onclick="javascript:initCars(); startLoop();" type="button" class="prikaz" value="Watch race">
</div>
</div>
</br>
'speed late':1
'speed_late':19
good luck:
I found this code on the internet. I pasted into my notepad++ and then changed these two files to match the ones that I created on my desktop.
<script src='C:/Users/home-1/Desktop/Box2dWeb-2.1.a.3.js'></script>
<script src='C:/Users/home-1/Desktop/example5.js'></script>
I have the script tag in the html file but I have tried it in the code and in the file and neither of them seem to work.
For some reason the page does not work. I would like to know what is different with this page and why it does not work.
Box2dWeb-2.1.a.3.js
and then created the example5.js file and have it also on my desktop. This should show a canvas along with several objects that you can drop and drag on the screen.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Joint</title>
<script src='C:/Users/home-1/Desktop/Box2dWeb-2.1.a.3.js'></script>
<script src='C:/Users/home-1/Desktop/example5.js'></script>
<style>
canvas
{
background-color:black;
}
</style>
</head>
<body>
<canvas id='b2dCanvas' width='1024' height='500'>Broswer does not
support Canvas Tag</canvas>
<script>
(function() {
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var Physics = window.Physics = function(element,scale) {
var gravity = new b2Vec2(0,9.8);
this.world = new b2World(gravity, true);
this.element = element;
this.context = element.getContext("2d");
this.scale = scale || 20;
this.dtRemaining = 0;
this.stepAmount = 1/60;
};
Physics.prototype.debug = function() {
this.debugDraw = new b2DebugDraw();
this.debugDraw.SetSprite(this.context);
this.debugDraw.SetDrawScale(this.scale);
this.debugDraw.SetFillAlpha(0.3);
this.debugDraw.SetLineThickness(1.0);
this.debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(this.debugDraw);
};
Physics.prototype.step = function(dt) {
this.dtRemaining += dt;
while(this.dtRemaining > this.stepAmount) {
this.dtRemaining -= this.stepAmount;
this.world.Step(this.stepAmount,
10, // velocity iterations
10);// position iterations
}
if(this.debugDraw) {
this.world.DrawDebugData();
} else {
var obj = this.world.GetBodyList();
this.context.clearRect(0,0,this.element.width,this.element.height);
this.context.save();
this.context.scale(this.scale,this.scale);
while(obj) {
var body = obj.GetUserData();
if(body)
{
body.draw(this.context);
}
obj = obj.GetNext();
}
this.context.restore();
}
};
Physics.prototype.click = function(callback) {
var self = this;
function handleClick(e) {
e.preventDefault();
var point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
self.world.QueryPoint(function(fixture) {
callback(fixture.GetBody(),
fixture,
point);
},point);
}
this.element.addEventListener("mousedown",handleClick);
this.element.addEventListener("touchstart",handleClick);
};
Physics.prototype.dragNDrop = function() {
var self = this;
var obj = null;
var joint = null;
function calculateWorldPosition(e) {
return point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
}
this.element.addEventListener("mousedown",function(e) {
e.preventDefault();
var point = calculateWorldPosition(e);
self.world.QueryPoint(function(fixture) {
obj = fixture.GetBody().GetUserData();
},point);
});
this.element.addEventListener("mousemove",function(e) {
if(!obj) { return; }
var point = calculateWorldPosition(e);
if(!joint) {
var jointDefinition = new Box2D.Dynamics.Joints.b2MouseJointDef();
jointDefinition.bodyA = self.world.GetGroundBody();
jointDefinition.bodyB = obj.body;
jointDefinition.target.Set(point.x,point.y);
jointDefinition.maxForce = 100000;
jointDefinition.timeStep = self.stepAmount;
joint = self.world.CreateJoint(jointDefinition);
}
joint.SetTarget(new b2Vec2(point.x,point.y));
});
this.element.addEventListener("mouseup",function(e) {
obj = null;
if(joint) {
self.world.DestroyJoint(joint);
joint = null;
}
});
};
Physics.prototype.collision = function() {
this.listener = new Box2D.Dynamics.b2ContactListener();
this.listener.PostSolve = function(contact,impulse) {
var bodyA = contact.GetFixtureA().GetBody().GetUserData(),
bodyB = contact.GetFixtureB().GetBody().GetUserData();
if(bodyA.contact) { bodyA.contact(contact,impulse,true) }
if(bodyB.contact) { bodyB.contact(contact,impulse,false) }
};
this.world.SetContactListener(this.listener);
};
var Body = window.Body = function(physics,details) {
this.details = details = details || {};
// Create the definition
this.definition = new b2BodyDef();
// Set up the definition
for(var k in this.definitionDefaults) {
this.definition[k] = details[k] || this.definitionDefaults[k];
}
this.definition.position = new b2Vec2(details.x || 0, details.y || 0);
this.definition.linearVelocity = new b2Vec2(details.vx || 0, details.vy || 0);
this.definition.userData = this;
this.definition.type = details.type == "static" ? b2Body.b2_staticBody :
b2Body.b2_dynamicBody;
// Create the Body
this.body = physics.world.CreateBody(this.definition);
// Create the fixture
this.fixtureDef = new b2FixtureDef();
for(var l in this.fixtureDefaults) {
this.fixtureDef[l] = details[l] || this.fixtureDefaults[l];
}
details.shape = details.shape || this.defaults.shape;
switch(details.shape) {
case "circle":
details.radius = details.radius || this.defaults.radius;
this.fixtureDef.shape = new b2CircleShape(details.radius);
break;
case "polygon":
this.fixtureDef.shape = new b2PolygonShape();
this.fixtureDef.shape.SetAsArray(details.points,details.points.length);
break;
case "block":
default:
details.width = details.width || this.defaults.width;
details.height = details.height || this.defaults.height;
this.fixtureDef.shape = new b2PolygonShape();
this.fixtureDef.shape.SetAsBox(details.width/2,
details.height/2);
break;
}
this.body.CreateFixture(this.fixtureDef);
};
Body.prototype.defaults = {
shape: "block",
width: 4,
height: 4,
radius: 1
};
Body.prototype.fixtureDefaults = {
density: 2,
friction: 1,
restitution: 0.2
};
Body.prototype.definitionDefaults = {
active: true,
allowSleep: true,
angle: 0,
angularVelocity: 0,
awake: true,
bullet: false,
fixedRotation: false
};
Body.prototype.draw = function(context) {
var pos = this.body.GetPosition(),
angle = this.body.GetAngle();
context.save();
context.translate(pos.x,pos.y);
context.rotate(angle);
if(this.details.color) {
context.fillStyle = this.details.color;
switch(this.details.shape) {
case "circle":
context.beginPath();
context.arc(0,0,this.details.radius,0,Math.PI*2);
context.fill();
break;
case "polygon":
var points = this.details.points;
context.beginPath();
context.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++) {
context.lineTo(points[i].x,points[i].y);
}
context.fill();
break;
case "block":
context.fillRect(-this.details.width/2,
-this.details.height/2,
this.details.width,
this.details.height);
default:
break;
}
}
if(this.details.image) {
context.drawImage(this.details.image,
-this.details.width/2,
-this.details.height/2,
this.details.width,
this.details.height);
}
context.restore();
}
var physics,
lastFrame = new Date().getTime();
window.gameLoop = function() {
var tm = new Date().getTime();
requestAnimationFrame(gameLoop);
var dt = (tm - lastFrame) / 1000;
if(dt > 1/15) { dt = 1/15; }
physics.step(dt);
lastFrame = tm;
};
function init() {
var img = new Image();
// Wait for the image to load
img.addEventListener("load", function() {
physics = window.physics = new Physics(document.getElementById("b2dCanvas"));
physics.collision();
// Create some walls
new Body(physics, { color: "red", type: "static", x: 0, y: 0, height: 50, width: 0.5 });
new Body(physics, { color: "red", type: "static", x:51, y: 0, height: 50, width: 0.5});
new Body(physics, { color: "red", type: "static", x: 0, y: 0, height: 0.5, width: 120 });
new Body(physics, { color: "red", type: "static", x: 0, y:25, height: 0.5, width: 120 });
new Body(physics, { image: img, x: 5, y: 8 });
new Body(physics, { image: img, x: 13, y: 8 });
new Body(physics, { color: "blue", x: 8, y: 3 });
new Body(physics, { color: "gray", shape: "circle", radius: 4, x: 5, y: 20 });
new Body(physics, { color: "pink", shape: "polygon",
points: [ { x: 0, y: 0 }, { x: 0, y: 4 },{ x: -10, y: 0 } ],
x: 20, y: 5 });
physics.dragNDrop();
requestAnimationFrame(gameLoop);
});
img.src = "images/bricks.jpg";
}
window.addEventListener("load",init);
}());
// Lastly, add in the `requestAnimationFrame` shim, if necessary. Does nothing
// if `requestAnimationFrame` is already on the `window` object.
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
</script>
</body>
</html>
Below is what the code is supposed to produce on the screen. I was wanting to use this one as an example but have not been able to get it to work.
This is how I have the files currently:
<script src='Box2dWeb-2.1.a.3.js'></script>
<script src='example5.js'></script>
You need a file:/// prefix for both of them, e.g. file:///C:\Users\home-1\Desktop\example5.js; Iād just use a relative path, though.
Assuming the file is on your desktop too,
<script src="Box2dWeb-2.1.a.3.js"></script>
<script src="example5.js"></script>
Much more portable.