Html 5 canvas cars speed - javascript

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:

Related

Error in JS function, and I can't figure out why

I am working on a simple JS platformer. Here is my code:
/*
TODO:
[X] 1. Add content to 'Game.Sprite.EditSpriteVel' (Function)
[] 2. Figure out a way to make a hitbox that can tell which way it hit
[X] 3. Find some game SFX
*/
var Game = {
Canvas: null,
Ctx: null,
Start: function(){
Game.Setup();
Game.Tick();
},
Keyup: function(e){
if(e.key == 'ArrowUp' && Game.World.Sprite.inJump === false){
Game.Keys.up = false;
}
if(e.key == 'ArrowLeft'){
Game.Keys.left = false;
}
if(e.key == 'ArrowRight'){
Game.Keys.right = false;
}
},
Paused: false,
Keydown: function(e){
if(e.key == 'ArrowUp' && Game.World.Sprite.inJump === false){
Game.Keys.up = true;
Game.World.Sprite.inJump = true
Game.World.Sprite.yVel = -Game.World.Sprite.jumpPower;
}
if(e.key == 'ArrowLeft'){
Game.Keys.left = true;
}
if(e.key == 'ArrowRight'){
Game.Keys.right = true;
}
},
Setup: function(){
Game.Canvas = document.createElement('Canvas');
Game.Canvas.width = 600;
Game.Canvas.height = 600;
Game.Canvas.style.border = '1px solid black';
document.body.appendChild(Game.Canvas);
Game.Ctx = Game.Canvas.getContext('2d');
},
Tick: function(){
if(!Game.Paused){
Game.Ctx.clearRect(0, 0, 600, 600);
Game.World.Platforms.Render();
Game.World.RenderSprite();
Game.World.EditSpriteVel();
Game.World.MoveSprite();
Game.World.ScreenBounds();
Game.World.CheckSpriteHealth();
}
requestAnimationFrame(Game.Tick);
},
Keys: {
up: false,
left: false,
right: false
},
World: {
Platforms: {
Index: [[{x: 200, y: 200, w: 200, h: 200}, {x: 100, y: 100, w: 100, h: 100}]],
Render: function(){
for(var i = 0; i < Game.World.Platforms.Index[Game.World.Map].length; i++){
Game.Ctx.fillStyle = 'grey';
Game.Ctx.fillRect(Game.World.Platforms.Index[Game.World.Map][i].x, Game.World.Platforms.Index[Game.World.Map][i].y, Game.World.Platforms.Index[Game.World.Map][i].w, Game.World.Platforms.Index[Game.World.Map][i].h);
}
},
},
Map: 0,
Level: {
StartingCoords: [{x: 300, y: 0}]
},
ResetLevel: function(){
Game.World.Sprite.x = Game.World.Level.StartingCoords[Game.World.Map].x
Game.World.Sprite.y = Game.World.Level.StartingCoords[Game.World.Map].y
Game.World.Sprite.xVel = 0;
Game.World.Sprite.yVel = 0;
Game.World.Sprite.inJump = false
},
CheckSpriteHealth: function(){
if(Game.World.Sprite.health <= 0){
Game.World.Sprite.health = 100
Game.World.Sprite.lives--;
Game.World.ResetLevel();
}
if(Game.World.Sprite.lives < 0){
Game.World.Map = 0;
Game.World.ResetLevel();
Game.World.Sprite.lives = 3
}
},
ScreenBounds: function(){
if(Game.World.Sprite.x < 0){
Game.World.Sprite.x = 0
Game.World.Sprite.xVel = 0
}
if(Game.World.Sprite.x > 600 - Game.World.Sprite.size){
Game.World.Sprite.x = 600 - Game.World.Sprite.size
Game.World.Sprite.xVel = 0
}
if(Game.World.Sprite.y > 600 - Game.World.Sprite.size){
Game.World.Sprite.health = 0
}
if(Game.World.Sprite.y < 0){
Game.World.Sprite.y = 0
Game.World.Sprite.yVel = 0
}
},
Sprite: {
x: 300,
xVel: 0,
y: 0,
yVel: 0,
size: 15,
inJump: false,
health: 100,
jumpPower: 7.5,
acc: 0.95,
fri: 0.1,
grav: 0.15,
lives: 3,
oldX: 0,
oldY: 0
},
MoveSprite: function(){
var hitting = [];
for(var i = 0; i < Game.World.Platforms.length; i++){
if(Game.World.Sprite.x + Game.World.Sprite.size > Game.World.Platforms[i].x && Game.World.Sprite.x < Game.World.Platforms[i].x + Game.World.Platforms[i].w && Game.World.Sprite.y + Game.World.Sprite.size > Game.World.Platforms[i].y && Game.World.Sprite.y < Game.World.Platforms[i].y){
hitting.push(Game.World.Platforms[i])
}
}
Game.World.Sprite.x += Game.World.Sprite.xVel;
Game.World.Sprite.y += Game.World.Sprite.yVel;
console.log(hitting)
},
RenderSprite: function(){
Game.Ctx.fillStyle = 'lightgrey';
Game.Ctx.fillRect(Game.World.Sprite.x, Game.World.Sprite.y, Game.World.Sprite.size, Game.World.Sprite.size);
},
EditSpriteVel: function(){
if(Game.Keys.left){
Game.World.Sprite.xVel -= Game.World.Sprite.acc;
}
if(Game.Keys.right){
Game.World.Sprite.xVel += Game.World.Sprite.acc;
}
Game.World.Sprite.xVel *= (1 - Game.World.Sprite.fri)
if(Game.World.Sprite.yVel < 7.5){
Game.World.Sprite.yVel += Game.World.Sprite.grav
}else{
Game.World.Sprite.yVel = 7.5;
}
}
}
};
document.onkeydown = function(e){ Game.Keydown(e); };
document.onkeyup = function(e){ Game.Keyup(e); };
Game.Start();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Game</title>
</head>
<body>
</body>
</html>
However, the Game.World.MoveSprite function isn't doing its job. I made it to detect which platform the sprite was hitting, however, the function isn't working and I can't figure out why. I want the function to push the platform's (The one that is hitting) specs (in ```JSON format) into an array for further use. Thanks.

Tinder like function, appcelerator

I tried to re create a Tinder like function.
I found this code :
var win = Titanium.UI.createWindow({
backgroundColor: "#ffffff",
title: "win"
});
// animations
var animateLeft = Ti.UI.createAnimation({
left: -520,
transform: Ti.UI.create2DMatrix({rotate: 60}),
opacity: 0,
duration: 300
});
var animateRight = Ti.UI.createAnimation({
left: 520,
transform: Ti.UI.create2DMatrix({rotate: -60}),
opacity: 0,
duration: 300
});
var curX = 0;
win.addEventListener('touchstart', function (e) {
curX = parseInt(e.x, 10);
});
win.addEventListener('touchmove', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// Subtracting current position to starting horizontal position
var coordinates = parseInt(e.x, 10) - curX;
// Defining coordinates as the final left position
var matrix = Ti.UI.create2DMatrix({rotate: -(coordinates / 10)});
var animate = Ti.UI.createAnimation({
left: coordinates,
transform: matrix,
duration: 20
});
e.source.animate(animate);
e.source.left = coordinates;
});
win.addEventListener('touchend', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// No longer moving the window
if (e.source.left >= 75) {
e.source.animate(animateRight);
} else if (e.source.left <= -75) {
e.source.animate(animateLeft);
} else {
// Repositioning the window to the left
e.source.animate({
left: 0,
transform: Ti.UI.create2DMatrix({rotate: 0}),
duration: 300
});
}
});
for (var i = 0; i < 10; i++) {
var wrap = Ti.UI.createView({
"id": 'oferta',
"width": 320,
"height": 400,
"backgroundColor": (i % 2 == 0 ? "red" : "blue")
});
var text = Ti.UI.createLabel({
text: "row: " + i,
color: "black"
});
wrap.add(text);
win.add(wrap);
}
win.open();
But there's a weird behaviour.
Indeed, When I took the wrap view from the top, everythnig is OK but if I put my finger on the bottom on the wrap view, the image becomes crazy..
Try the code and You will see strange behaviour.
I use Titanium SDK 5.2.2
and iOS 9.3.1 on an iPhone 6.
Here s a video showing the weird thing: http://tinypic.com/player.php?v=x37d5u%3E&s=9#.Vx_zDaOLQb0
(Sorry for the video size)
Thanks for your help
Use this code to convert pxToDp and vice versa:
Put following code in your lib folder and include it
with require("measurement")
instead of require("alloy/measurement")
var dpi = Ti.Platform.displayCaps.dpi, density = Ti.Platform.displayCaps.density;
exports.dpToPX = function(val) {
switch (density) {
case "xxxhigh":
return 5 * val;
case "xxhigh":
return 4 * val;
case "xhigh":
return 3 * val;
case "high":
return 2 * val;
default:
return val;
}
};
exports.pxToDP = function(val) {
switch (density) {
case "xxxhigh":
return 5 / val;
case "xxhigh":
return 4 / val;
case "xhigh":
return val / 3;
case "high":
return val / 2;
default:
return val;
}
};
exports.pointPXToDP = function(pt) {
return {
x: exports.pxToDP(pt.x),
y: exports.pxToDP(pt.y)
};
};
Many thanks to all !!! It works using this code ::
var win = Titanium.UI.createWindow({
backgroundColor: "#ffffff",
title: "win"
});
// animations
var animateLeft = Ti.UI.createAnimation({
left: -520,
transform: Ti.UI.create2DMatrix({rotate: 60}),
opacity: 0,
duration: 300
});
var animateRight = Ti.UI.createAnimation({
left: 520,
transform: Ti.UI.create2DMatrix({rotate: -60}),
opacity: 0,
duration: 300
});
Ti.include('measurement.js');
var curX = 0;
var wrap = [];
var topWrap = 100; //(Titanium.Platform.displayCaps.platformHeight - 400) / 2;
var leftWrap = 50; //(Titanium.Platform.displayCaps.platformWidth - 320) / 2;
for (var i = 0; i < 10; i++) {
wrap[i] = Ti.UI.createView({
"id": 'oferta',
"width": Titanium.Platform.displayCaps.platformWidth - 100,
"height": Titanium.Platform.displayCaps.platformHeight - 300,
image:(i % 2 == 0 ? 'principale.png' : 'principale1.png'),
"backgroundColor": (i % 2 == 0 ? "red" : "blue"),
top:topWrap,
left:leftWrap,
});
wrap[i].addEventListener('touchstart', function (e) {
// curX = parseInt(e.x, 10);
curX = pxToDP(parseInt(e.x, 10));
// curY = pxToDP(parseInt(e.Y, 10));
});
wrap[i].addEventListener('touchmove', function (e) {
// Subtracting current position to starting horizontal position
// var coordinates = parseInt(e.x, 10) - curX;
// Defining coordinates as the final left position
var coordinatesX = pxToDP(parseInt(e.x, 10)) - curX;
//var coordinatesY = pxToDP(parseInt(e.y, 10)) - curY;
var matrix = Ti.UI.create2DMatrix({rotate: -(coordinatesX / 10)});
var animate = Ti.UI.createAnimation({
left: coordinatesX,
// top: coordinatesY,
transform: matrix,
duration: 10
});
e.source.animate(animate);
e.source.left = coordinatesX;
// e.source.top = coordinatesY;
});
wrap[i].addEventListener('touchend', function (e) {
// No longer moving the window
if (e.source.left >= 75) {
e.source.animate(animateRight);
} else if (e.source.left <= -75) {
e.source.animate(animateLeft);
} else {
// Repositioning the window to the left
e.source.animate({
left: leftWrap,
transform: Ti.UI.create2DMatrix({rotate: 0}),
duration: 300
});
}
});
win.add(wrap);
}
win.open();
And the measurement.js file is :
var dpi = Ti.Platform.displayCaps.dpi, density = Ti.Platform.displayCaps.density;
function dpToPX(val) {
switch (density) {
case "xxxhigh":
return 5 * val;
case "xxhigh":
return 4 * val;
case "xhigh":
return 3 * val;
case "high":
return 2 * val;
default:
return val;
}
};
function pxToDP(val) {
switch (density) {
case "xxxhigh":
return 5 / val;
case "xxhigh":
return 4 / val;
case "xhigh":
return val / 3;
case "high":
return val / 2;
default:
return val;
}
};
function pointPXToD(pt) {
return {
x: pxToDP(pt.x),
y: pxToDP(pt.y)
};
};
You have to convert px to dp.
var measurement = require('alloy/measurement');
win.addEventListener('touchstart', function (e) {
curX = measurement.pxToDP(parseInt(e.x, 10));
Ti.API.info("touchstart curX: " + curX);
});
...
win.addEventListener('touchmove', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// Subtracting current position to starting horizontal position
var coordinates = measurement.pxToDP(parseInt(e.x, 10)) - curX;
...

Jquery return not loaded in Wordpress

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.

Why is this index html not displaying the game on my desk top?

I found this game online and am trying to get it to run from my desktop. Is there something special that a person has to do with the URL's or images to make the file recognize were everything is running and located at. I have all of the files and .png files in one folder and on the same level.
I would think that I should see the game on the screen. It is like a left to right horizontal scroll-er with enemy ships that come out of the right side of the screen and the main ship is on the right side of the screen. (Similar to that of the old style defender game)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div id="game-over-overlay"></div>
<div id="game-over">
<h1>GAME OVER</h1>
<button id="play-again">Play Again</button>
</div>
<div class="wrapper">
<div id="instructions">
<div>
move with <span class="key">arrows</span> or <span class="key">wasd</span>
</div>
<div>
shoot with <span class="key">space</span>
</div>
</div>
<div id="score"></div>
</div>
<script type="text/javascript" src="resources.js"></script>
<script type="text/javascript" src="input.js"></script>
<script type="text/javascript" src="sprite.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
sprite.js
(function() {
function Sprite(url, pos, size, speed, frames, dir, once) {
this.pos = pos;
this.size = size;
this.speed = typeof speed === 'number' ? speed : 0;
this.frames = frames;
this._index = 0;
this.url = url;
this.dir = dir || 'horizontal';
this.once = once;
};
Sprite.prototype = {
update: function(dt) {
this._index += this.speed*dt;
},
render: function(ctx) {
var frame;
if(this.speed > 0) {
var max = this.frames.length;
var idx = Math.floor(this._index);
frame = this.frames[idx % max];
if(this.once && idx >= max) {
this.done = true;
return;
}
}
else {
frame = 0;
}
var x = this.pos[0];
var y = this.pos[1];
if(this.dir == 'vertical') {
y += frame * this.size[1];
}
else {
x += frame * this.size[0];
}
ctx.drawImage(resources.get(this.url),
x, y,
this.size[0], this.size[1],
0, 0,
this.size[0], this.size[1]);
}
};
window.Sprite = Sprite;
resources.js
(function() {
var resourceCache = {};
var loading = [];
var readyCallbacks = [];
// Load an image url or an array of image urls
function load(urlOrArr) {
if(urlOrArr instanceof Array) {
urlOrArr.forEach(function(url) {
_load(url);
});
}
else {
_load(urlOrArr);
}
}
function _load(url) {
if(resourceCache[url]) {
return resourceCache[url];
}
else {
var img = new Image();
img.onload = function() {
resourceCache[url] = img;
if(isReady()) {
readyCallbacks.forEach(function(func) { func(); });
}
};
resourceCache[url] = false;
img.src = url;
}
}
function get(url) {
return resourceCache[url];
}
function isReady() {
var ready = true;
for(var k in resourceCache) {
if(resourceCache.hasOwnProperty(k) &&
!resourceCache[k]) {
ready = false;
}
}
return ready;
}
function onReady(func) {
readyCallbacks.push(func);
}
window.resources = {
load: load,
get: get,
onReady: onReady,
isReady: isReady
};
input.js
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
apps.js
// A cross-browser requestAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = (now - lastTime) / 1000.0;
update(dt);
render();
lastTime = now;
requestAnimFrame(main);
};
function init() {
terrainPattern = ctx.createPattern(resources.get('terrain.png'), 'repeat');
document.getElementById('play-again').addEventListener('click', function() {
reset();
});
reset();
lastTime = Date.now();
main();
}
resources.load([
'sprites.png',
'terrain.png'
]);
resources.onReady(init);
// Game state
var player = {
pos: [0, 0],
sprite: new Sprite('sprites.png', [0, 0], [39, 39], 16, [0, 1])
};
var bullets = [];
var enemies = [];
var explosions = [];
var lastFire = Date.now();
var gameTime = 0;
var isGameOver;
var terrainPattern;
var score = 0;
var scoreEl = document.getElementById('score');
// Speed in pixels per second
var playerSpeed = 200;
var bulletSpeed = 500;
var enemySpeed = 100;
// Update game objects
function update(dt) {
gameTime += dt;
handleInput(dt);
updateEntities(dt);
// It gets harder over time by adding enemies using this
// equation: 1-.993^gameTime
if(Math.random() < 1 - Math.pow(.993, gameTime)) {
enemies.push({
pos: [canvas.width,
Math.random() * (canvas.height - 39)],
sprite: new Sprite('sprites.png', [0, 78], [80, 39],
6, [0, 1, 2, 3, 2, 1])
});
}
checkCollisions();
scoreEl.innerHTML = score;
};
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
if(input.isDown('SPACE') && !isGameOver && Date.now() - lastFire > 100) {
var x = player.pos[0] + player.sprite.size[0] / 2;
var y = player.pos[1] + player.sprite.size[1] / 2;
bullets.push({ pos: [x, y],
dir: 'forward',
sprite: new Sprite('sprites.png', [0, 39], [18, 8]) });
bullets.push({ pos: [x, y],
dir: 'up',
sprite: new Sprite('sprites.png', [0, 50], [9, 5]) });
bullets.push({ pos: [x, y],
dir: 'down',
sprite: new Sprite('sprites.png', [0, 60], [9, 5]) });
lastFire = Date.now();
}
}
function updateEntities(dt) {
// Update the player sprite animation
player.sprite.update(dt);
// Update all the bullets
for(var i=0; i<bullets.length; i++) {
var bullet = bullets[i];
switch(bullet.dir) {
case 'up': bullet.pos[1] -= bulletSpeed * dt; break;
case 'down': bullet.pos[1] += bulletSpeed * dt; break;
default:
bullet.pos[0] += bulletSpeed * dt;
}
// Remove the bullet if it goes offscreen
if(bullet.pos[1] < 0 || bullet.pos[1] > canvas.height ||
bullet.pos[0] > canvas.width) {
bullets.splice(i, 1);
i--;
}
}
// Update all the enemies
for(var i=0; i<enemies.length; i++) {
enemies[i].pos[0] -= enemySpeed * dt;
enemies[i].sprite.update(dt);
// Remove if offscreen
if(enemies[i].pos[0] + enemies[i].sprite.size[0] < 0) {
enemies.splice(i, 1);
i--;
}
}
// Update all the explosions
for(var i=0; i<explosions.length; i++) {
explosions[i].sprite.update(dt);
// Remove if animation is done
if(explosions[i].sprite.done) {
explosions.splice(i, 1);
i--;
}
}
}
// Collisions
function collides(x, y, r, b, x2, y2, r2, b2) {
return !(r <= x2 || x > r2 ||
b <= y2 || y > b2);
}
function boxCollides(pos, size, pos2, size2) {
return collides(pos[0], pos[1],
pos[0] + size[0], pos[1] + size[1],
pos2[0], pos2[1],
pos2[0] + size2[0], pos2[1] + size2[1]);
}
function checkCollisions() {
checkPlayerBounds();
// Run collision detection for all enemies and bullets
for(var i=0; i<enemies.length; i++) {
var pos = enemies[i].pos;
var size = enemies[i].sprite.size;
for(var j=0; j<bullets.length; j++) {
var pos2 = bullets[j].pos;
var size2 = bullets[j].sprite.size;
if(boxCollides(pos, size, pos2, size2)) {
// Remove the enemy
enemies.splice(i, 1);
i--;
// Add score
score += 100;
// Add an explosion
explosions.push({
pos: pos,
sprite: new Sprite('sprites.png',
[0, 117],
[39, 39],
16,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
null,
true)
});
// Remove the bullet and stop this iteration
bullets.splice(j, 1);
break;
}
}
if(boxCollides(pos, size, player.pos, player.sprite.size)) {
gameOver();
}
}
}
function checkPlayerBounds() {
// Check bounds
if(player.pos[0] < 0) {
player.pos[0] = 0;
}
else if(player.pos[0] > canvas.width - player.sprite.size[0]) {
player.pos[0] = canvas.width - player.sprite.size[0];
}
if(player.pos[1] < 0) {
player.pos[1] = 0;
}
else if(player.pos[1] > canvas.height - player.sprite.size[1]) {
player.pos[1] = canvas.height - player.sprite.size[1];
}
}
// Draw everything
function render() {
ctx.fillStyle = terrainPattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Render the player if the game isn't over
if(!isGameOver) {
renderEntity(player);
}
renderEntities(bullets);
renderEntities(enemies);
renderEntities(explosions);
};
function renderEntities(list) {
for(var i=0; i<list.length; i++) {
renderEntity(list[i]);
}
}
function renderEntity(entity) {
ctx.save();
ctx.translate(entity.pos[0], entity.pos[1]);
entity.sprite.render(ctx);
ctx.restore();
}
// Game over
function gameOver() {
document.getElementById('game-over').style.display = 'block';
document.getElementById('game-over-overlay').style.display = 'block';
isGameOver = true;
}
// Reset game to original state
function reset() {
document.getElementById('game-over').style.display = 'none';
document.getElementById('game-over-overlay').style.display = 'none';
isGameOver = false;
gameTime = 0;
score = 0;
enemies = [];
bullets = [];
player.pos = [50, canvas.height / 2];
app.css
html, body {
margin: 0;
padding: 0;
background-color: #151515;
}
canvas {
display: block;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper {
width: 512px;
margin: 0 auto;
margin-top: 2em;
}
#instructions {
float: left;
font-family: sans-serif;
color: #757575;
}
#score {
float: right;
color: white;
font-size: 2em;
}
.key {
color: #aaffdd;
}
#game-over, #game-over-overlay {
margin: auto;
width: 512px;
height: 480px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#game-over-overlay {
background-color: black;
opacity: .5;
}
#game-over {
height: 200px;
text-align: center;
color: white;
}
#game-over h1 {
font-size: 3em;
font-family: sans-serif;
}
#game-over button {
font-size: 1.5em;
}
Here is the original game link
http://jlongster.com/Making-Sprite-based-Games-with-Canvas
If someone could put up a fiddle to see why it is not working it would be most appreciated.
Errors from the console
Uncaught SyntaxError: Unexpected end of input resources.js:61
Uncaught SyntaxError: Unexpected end of input input.js:43
Uncaught SyntaxError: Unexpected end of input sprite.js:54
Uncaught SyntaxError: Unexpected end of input app.js:302
Are you running this on a webserver? The way that you phrased it makes me think you you downloaded those files and just double-clicked index.html.
You need to download something like https://www.apachefriends.org/index.html and start the Apache service up, then put your files in the /xampp/htdocs/ folder... then goto
http://localhost/index.html
to get it to load.

Why is this file not running the javascript that is in example5.js?

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.

Categories