Admob Phonegap build Stuck - javascript

Ok I have an application on the market for testing purposes and Im trying to implement admob ads I have my account for banner ads and everything the only thing is that I dont know how to set it up I need help please this is the sample application. Thank you
Mostly what i need i need to show banner ads on my title screen game screen and game over screen Ive tried several tutorials none seem to get me anywhere so thats why i decided maybe here one of you can help Me with this.
This is the html file----------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8-8">
<meta name="viewport" content="user-scalable=0, initial-scale=1,minimum-scale=1, maximum-scale=1, width=device-width, minimal-ui=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script type="text/javascript" src="js/phaser.js"></script>
<script src="js/stateTitle.js"></script>
<script src="js/characters.js"></script>
<style>
body {
padding: 0px;
margin: 0px;
background: black;
c
}
</style>
</head>
<body>
<script src="js/stateOver.js"></script>
<script src="js/main.js"></script>
</body>
</body>
</html>
----------------------------------------------------------------------------_
Main.js
var score =0;
var highscore =0;
var highScoreText;
var scoreText;
var MainState = {
//load the game assets before the game starts
preload: function () { /////////////////////////////preload
this.load.image('background', 'assets/city.png');
this.load.image('bird', 'assets/bird.png');
game.load.image('pipe', 'assets/pipe.png');
},
//executed after everything is loaded
create: function () {
this.background = this.game.add.sprite(0, 0, 'background');
highScoreText = this.game.add.text(600, 40, 'HS: ' + highscore, {
font: '25px Arial',
fill: 'black'
});
/////Bird///////////////////////////////////////////////////
this.bird = this.game.add.sprite(100, 200, 'bird');
game.physics.startSystem(Phaser.Physics.ARCADE);
game.physics.arcade.enable(this.bird);
this.bird.body.gravity.y = 1000;
var spaceKey = game.input.keyboard.addKey(
Phaser.Keyboard.SPACEBAR);
game.input.onDown.add(this.jump, this); //////touch screen jump
spaceKey.onDown.add(this.jump, this);
this.bird.body.collideWorldBounds=true;
this.bird.body.immovable= true;
///////////////////////////////////////////////////////Pipes
this.pipes = game.add.group();
//timer
this.timer = game.time.events.loop(1400, this.addRowOfPipes, this); /////////////timer for pipes
///////////////////////////////////////////////////////Score
this.score = -1;
this.labelScore = game.add.text(20, 20, "0",
{ font: "30px Arial", fill: "black" });
},
// this is execated multiple times per second
update: function () { //////////////////////////////////////////////////update
if (this.bird.y < 0 || this.bird.y > 480)
game.state.start("StateOver");
///Collision
game.physics.arcade.overlap(
this.bird, this.pipes, this.restartGame, null, this);
////////////////////////////////////////////////////////////////////////// Highscore counter
highScoreText.text = 'HS: ' + this.currentHighScore;
{
if (this.score > this.currentHighScore)
{
this.currentHighScore = this.score;
}
}
},
jump: function () {
//this is for so the bird wount fly once dead
if (this.bird.alive == false)
return;
///sound
///this.jumpSound.play();
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
// Jump Animation
var animation = game.add.tween(this.bird);
// Change the angle of the bird to -20° in 100 milliseconds
animation.to({angle: -20}, 100);
// And start the animation
animation.start();
game.add.tween(this.bird).to({angle: -20}, 100).start();
},
restartGame: function () {
// Start the 'main' state, which restarts the game
game.state.start(game.state.current);
///Hit pipe Null
game.physics.arcade.overlap(
this.bird, this.pipes, this.hitPipe, null, this);
},
addRowOfPipes: function() {
var hole = Math.floor(Math.random() * 5) + 1; ///Math.floor(Math.random() * 5) + 1;
for (var i = 0; i < 10 ; i++) ///// (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1) ///// if (i != hole && i != hole + 1)
this.addOnePipe(440, i * 50 ); ///// 640 starting point of pipe 240 point of down ////this.addOnePipe(480, i * 60 + 10);
///Score for pipes
this.score += 1;
this.labelScore.text = this.score;
},
addOnePipe: function(x, y) {
var pipe = game.add.sprite(x, y, 'pipe');
this.pipes.add(pipe);
game.physics.arcade.enable(pipe);
pipe.body.velocity.x = -200;
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
hitPipe: function() {
// If the bird has already hit a pipe, do nothing
// It means the bird is already falling off the screen
if (this.bird.alive == false)
return;
else {
game.state.start("StateOver");
}
// Set the alive property of the bird to false
this.bird.alive = false;
// Prevent new pipes from appearing
game.time.events.remove(this.timer);
// Go through all the pipes, and stop their movement
this.pipes.forEach(function(p){
p.body.velocity.x = 0;
}, this);
},
};
// Initilate the Phaser Framework
var game = new Phaser.Game(480, 640, Phaser.AUTO);
game.state.add("main", MainState);
game.state.add("stateTitle", stateTitle);
game.state.add("StateOver", StateOver);
game.state.add("characters", characters);
game.state.start("stateTitle");
-----------------------------------------------------------------------------
Game over screen stateover.js
var StateOver={
preload:function()
{
game.load.spritesheet('button', 'assets/button.png', 215, 53, 8);
game.load.image("title", "assets/title.png");
game.load.image("game", "assets/extra/gameover.png");
},
create:function()
{
this.title = game.add.tileSprite(0, game.height-640,game.width, 640, 'title');
this.title.autoScroll(-100,0);
this.btnPlayAgain=game.add.button(110,400,'button',this.playAgain,this,2,3,2);
this.btnMainMenu=game.add.button(110,300,'button',this.mainMenu,this,4,5,4);
this.btnStore=game.add.button(110,200,'button',this.Store,this,6,7,6);
this.game.add.sprite (118, 100, "game");
highScoreText = this.game.add.text(130, 150, 'HS: ' + highscore, {
font: '25px Arial',
fill: 'black'
});
},
playAgain:function()
{
game.state.start("main");
},
mainMenu:function()
{
game.state.start("stateTitle");
},
Store:function()
{
game.state.start("characters");
},
update:function()
{
highScoreText.text = 'HIGHSCORE: ' + localStorage.getItem("highscore");
{
if (this.score > localStorage.getItem("highscore"))
{
localStorage.setItem("highscore", this.score);
}
}
},
};
This is the main title screen
var stateTitle={
preload:function()
{
game.load.image("logo", "assets/extra/Logo.png");
game.load.image("title", "assets/title.png");
game.load.spritesheet('button', 'assets/button.png', 215, 53, 8);
},
create:function()
{
this.title = game.add.tileSprite(0, game.height-640,game.width, 640, 'title');
this.title.autoScroll(-100,0);
this.btnStart=game.add.button(110,400,'button',this.startGame,this,0,1,1);
this.btnStore=game.add.button(110,480,'button',this.Store,this,6,7,6);
this.logo = game.add.sprite(60, 150, 'logo');
},
startGame:function()
{
game.state.start("main");
},
Store:function()
{
game.state.start("characters");
},
update:function()
{
},
};
Html with sample
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8-8">
<meta name="viewport" content="user-scalable=0, initial-scale=1,minimum-scale=1, maximum-scale=1, width=device-width, minimal-ui=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script type="text/javascript" src="js/phaser.js"></script>
<script src="js/stateTitle.js"></script>
<script src="js/characters.js"></script>
<style>
body {
padding: 0px;
margin: 0px;
background: black;
c
}
</style>
</head>
<body>
<script src="js/stateOver.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
function onDeviceready() {
admob.createBannerView({publisherId: "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB"});
}
document.addEventListener('deviceready', onDeviceready, false);
</script>
</body>
</html>

Firstly add admob plugin then just add below lines to your html file:
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if (AdMob)
AdMob.prepareInterstitial({
adId : 'ca-app-pub-xxx/yyy',
autoShow : false
});
if (AdMob)
AdMob.createBanner({
adId : 'ca-app-pub-xxx/yyy',
position : AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow : true,
overlap : true
});
}
</script>
You can change the place of the banner; use TOP_CENTER (I am not sure about this) instead of BOTTOM_CENTER.

Ok SOOOOO many tries alone I was able to fix this by simply inserting the extra needed plugins. Internet connection etc. BOOOOOOOOOOOOOOM Fixed any questions ask.

Related

I want to convert paper.js Examples from paperscript to javascript

I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!
The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>

How to detect overlap in Phaser.js?

I am new to Phaserjs, and I am trying to make a shooting game. I want the damage function to fire when a bullet touches plane2, that is the green plane. Can somone please tell me what am I doing wrong here?
Here is my code:
var config = {
type: Phaser.AUTO,
width: 800,
height: 800,
parent:"game",
physics: {
default: 'arcade',
arcade: {
debugging:true,
gravity: {y: 0}
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var plane1
var plane2
var hp;
var botHp;
function preload (){
this.load.setBaseURL('https://shoot.abaanshanid.repl.co/assets');
this.load.image("bg", "bg.jpg");
this.load.image("plane1", "plane1.png");
this.load.image("plane2", "plane2.png");
this.load.image("bullet", "bullet.png");
}
function create (){
this.background = this.add.image(400, 400, "bg");
plane1 = this.physics.add.sprite(400,700,"plane1");
plane2 = this.physics.add.sprite(400,100,"plane2");
plane1.enableBody = true;
}
function update(){
keys = this.input.keyboard.createCursorKeys();
if (keys.left.isDown) {
plane1.x = plane1.x - 7.5;
}else if(keys.right.isDown){
plane1.x = plane1.x + 7.5;
}else if(keys.space.isDown){
var bullet = this.physics.add.sprite(plane1.x,600,"bullet");
bullet.enableBody = true;
setInterval(function(){
bullet.y = bullet.y - 25;
},50);
this.physics.overlap(bullet,plane2,this.damage);
}
}
function damage(){
console.log("less HP")
}
var game = new Phaser.Game(config);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser-arcade-physics.min.js"></script>
</head>
<body>
<div id="game"></div>
<script defer src="script.js"></script>
</body>
</html>
Here is the link to the game if needed https://shoot.abaanshanid.repl.co/
This works:
this.physics.add.overlap(bullet,plane2,damage);
but its kinda laggy. Id try to destroy bullet on impact and i also found:
this.physics.add.collider(bullet,plane2,damage);

Baffled by NaN - HTML CANVAS JS

I'm trying to create a timer within an object - however when trying to increment the counter by the time that's passed I'm getting a NaN error. The error stops if I replace the deltaTime argument with a constant, but then the jump time would vary depending upon the end users machine and work load.
class Actor {
constructor() {
this.jumpCounter = 0
this.jumpTimer = function (deltaTime) {
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}
}
}
let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext("2d");
var lastTime = 0;
const GAME_WIDTH = 600;
const GAME_HEIGHT = 600;
actor = new Actor;
function gameLoop(timestamp) {
let deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.fillStyle = 'rgba(155, 200, 155, 0.3)'
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
actor.jumpTimer(deltaTime)
requestAnimationFrame(gameLoop);
}
gameLoop();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Sandbox</title>
<style>
#gameScreen {
border: 1px solid;
}
</style>
</head>
<body>
<canvas id="gameScreen" width="600" height="600"></canvas>
<script></script>
</body>
</html>
As the error resulted from there being on timestamp on the first run through of the code this fixed the issue:
this.jumpTimer = function (deltaTime) {
if (!deltaTime) return;
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}

Drag and drop using Raphael.js has laggy performance with more than 10 draggable elements

I'm making a simple HTML5 app, that will be wrapped to be used on Android, iOS and web browsers. In my app I need a set of points to be dragged and sorted in a certain way, I'm using raphael.js for the animations and movememts and it works fine with 3 or 4 circles, but when I use more the laggy performance appears (mobile browser). I also need the app to be able to draw lines on freehand, like a marker, and the code i'm using refers to drag to, so the performance is awful. The interesting part is that the first moves work great, as i move more elements the performance drops down drastically. It works fine in the pc browser, but works fine for 3 or 4 movements on the mobie browser.
Is there any way to make drag and drop run fast and smooth with large quantity of elements?
Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Raphaël · Drag-n-drop</title>
<link rel="stylesheet" href="demo.css" type="text/css" media="screen">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-icon-precomposed" href="/Raphael.png">
<link rel="stylesheet" href="demo-print.css" type="text/css" media="print">
<style>
#background {
width: 100%;
height: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}
.stretch {
width:100%;
height:100%;
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="raphael-min.js"></script>
<script>
window.onload = function () {
var y = $(window).height();
var x = $(window).width();
y=y/30;
var posX=y;
var posY=y;
var posX2=x-y;
var R = Raphael(0, 0, "100%", "100%");
var nJ=10
var jugador=new Array();
var rival=new Array();
crearJugadores(nJ);
crearRivales(nJ);
function crearJugadores(nJ) {
nJ=nJ;
for (var i=0;i<nJ;i++)
{
jugador[i]= R.circle(posX, posY, y).attr({fill: "hsb(0, 1, 1)", stroke: "none", opacity: .5});
posY=posY+(2*y);
};
};
function crearRivales(nJ) {
posX=x-y;
posY=y;
nJ=nJ;
for (var i=0;i<nJ;i++)
{
rival[i]= R.circle(posX, posY, y).attr({fill: "#214dcf", stroke: "none", opacity: .5});
posY=posY+(2*y);
};
};
var start = function () {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.animate({r: (1.5*y), opacity: .3}, 100, ">");
},
move = function (dx, dy) {
this.attr({cx: this.ox + dx, cy: this.oy + dy});
},
up = function () {
this.animate({r: y, opacity: 1}, 500, ">");
};
R.set(rival).drag(move, start, up);
R.set(jugador).drag(move, start, up);
initDrawing(R);
};
var g_masterPathArray;
var g_masterDrawingBox;
var g_masterPaper;
function initDrawing(R) {
g_masterPaper = R;
var masterBackground = g_masterPaper.rect(0,0,"100%","100%");
masterBackground.attr({fill:"blue", opacity: 0});
masterBackground.mousemove(function (event) {
var evt = event;
var IE = document.all?true:false;
var x, y;
if (IE) {
x = evt.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = evt.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
else {
x = evt.pageX;
y = evt.pageY;
}
// subtract paper coords on page
this.ox = x;
this.oy = y;
});
var start = function () {
g_masterPathArray = new Array();
},
move = function (dx, dy) {
if (g_masterPathArray.length == 0) {
g_masterPathArray[0] = ["M",this.ox,this.oy];
g_masterDrawingBox = g_masterPaper.path(g_masterPathArray);
g_masterDrawingBox.attr({stroke: "#000000","stroke-width": 3});
}
else
g_masterPathArray[g_masterPathArray.length] =
["L",this.ox,this.oy];
g_masterDrawingBox.attr({path: g_masterPathArray});
},
up = function () {
;
};
masterBackground.drag(move, start, up);
masterBackground.toBack();
}
</script>
</head>
<body>
<div id="background">
<img src="cancha.jpg" class="stretch" alt="" />
</div>
<div id="holder"></div>
</body>
</html>
Any ideas??
Thanks

HTML5 canvas game static solid elements

I'm writing a canvas game with easeljs. Almost everything is working correctly in this project, only problem is I can't add static objects to the field.
Here is the link my demo: http://insidejs.com/game/
I don't want to enter to the colored areas with shopping cart. Player should turn around these areas. This game illustrates what I need to do.: http://www.kokogames.com/free-games/91/racing-games/138/e-racer.htm
Thanks.
My Project:
<!DOCTYPE html>
<!--[if IE 7]> <html class="no-js ie7"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="tr"><!--<![endif]-->
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Game</title>
<!-- css -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/screen.css" rel="stylesheet" type="text/css" />
<!-- css -->
<!-- javascript -->
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/easeljs-0.6.1.min.js"></script>
<script type="text/javascript">
var CANVAS, STAGE, Shopping, GAME;
$(function () {
window.Shopping= {
Game: {}
};
GAME = Shopping.Game;
GAME = new Application();
CANVAS = document.getElementById("game");
STAGE = new createjs.Stage(CANVAS);
GAME.init();
});
var Application = function () {
};
Application.prototype = {
vehicle: null,
vehicleImg: new Image(),
map: null,
mapImg: new Image(),
TURN_FACTOR: 3,
MAX_THRUST: 1,
MAX_VELOCITY: 10,
KEYCODE_UP: 38,
KEYCODE_LEFT: 37,
KEYCODE_RIGHT: 39,
KEYCODE_DOWN: 40,
RIGHT_KEY: false,
LEFT_KEY: false,
UP_KEY: false,
DOWN_KEY: false,
map: null,
init: function () {
GAME.mapImg.src = "assets/images/map.jpg";
GAME.mapImg.name = 'map';
GAME.mapImg.onload = GAME.loadImage();
GAME.vehicleImg.src = "assets/images/vehicle.png";
GAME.vehicleImg.name = 'vehicle';
GAME.vehicleImg.onload = GAME.loadImage();
if (!createjs.Ticker.hasEventListener("tick")) {
createjs.Ticker.addEventListener("tick", GAME.tick);
}
$(document).keydown(GAME.handleKeyDown);
$(document).keyup(GAME.handleKeyUp);
},
loadImage: function () {
GAME.vehicle = new createjs.Bitmap(GAME.vehicleImg);
GAME.vehicle.x = CANVAS.width / 2;
GAME.vehicle.y = CANVAS.height / 2;
GAME.vehicle.width = 100;
GAME.vehicle.height = 69;
GAME.vehicle.regX = GAME.vehicle.width / 2;
GAME.vehicle.regY = GAME.vehicle.height / 2;
GAME.map = new createjs.Bitmap(GAME.mapImg);
GAME.map.scaleX = 1;
GAME.map.scaleY = 1;
GAME.map.width = 3000;
GAME.map.height = 2000;
GAME.map.regX = GAME.map.width / 2;
GAME.map.regY = GAME.map.height / 2;
GAME.map.x = CANVAS.width / 2;
GAME.map.y = CANVAS.height / 2 - 300;
GAME.map.speed = 0;
GAME.map.vX = 0;
GAME.map.vY = 0;
STAGE.addChild(GAME.map);
STAGE.addChild(GAME.vehicle);
STAGE.update();
},
//game listener
tick: function (event) {
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= GAME.TURN_FACTOR;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += GAME.TURN_FACTOR;
}
if (GAME.UP_KEY) {
GAME.accelarate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
if (GAME.DOWN_KEY) {
GAME.decelerate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
STAGE.update(event);
},
handleKeyDown: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = true;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = true;
break;
case GAME.KEYCODE_UP:
e.preventDefault();
GAME.UP_KEY = true;
break;
case GAME.KEYCODE_DOWN:
e.preventDefault();
GAME.DOWN_KEY = true;
break;
}
},
handleKeyUp: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = false;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = false;
break;
case GAME.KEYCODE_UP:
GAME.UP_KEY = false;
break;
case GAME.KEYCODE_DOWN:
GAME.DOWN_KEY = false;
break;
}
},
accelarate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX -= Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY -= Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
},
decelerate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX += Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY += Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
}
//class end
};
</script>
<!-- javascript -->
</head>
<body>
<div id="page">
<canvas id="game" width="640" height="480"></canvas>
</div>
</body>
</html>
To make a collision detection work for your game you will need to make quite some changes to your project:
Currently you have one big JPG as a map, which is not a good idea, if you try to have objects collide with other objects.
1) If you are willing to split up the big JPG map(probably quickest acceptable solution): You can use one big grey JPG als the floor and place single green Bitmaps on top of that floor. Then you can use the Collision Detection suggested by #WiredPrairie (https://github.com/olsn/Collision-Detection-for-EaselJS) - doing the collision check this way should be about 3-4lines of code (+the work of splitting up your current map.jpg).
2) If you want to keep that JPG as map: I suggest you either create custom rectangles for the green areas and check every frame if the shopping cart is inside such a rectangle. Another option would be to implement a physics library like Box2D (I know, this will take some time to get into Box2D or other libraries, and I'm guessing you are looking for a quick solution, but trust me: It'll be worth it)
As a non-related hint: For projects like yours it's really worth taking a look at Box2D or other physic engines, once you get the hang of how it works, it's really a big help to use a physics library ;-)

Categories