Github Pages as Static Image Hosting - javascript

I am trying to use GitHub pages to host static images for a website I am working on. The website randomizes div locations across the page, and it's supposed to use the photos from the repository. Here is the repository that is hosting the images.
The issue is that the images are not loading from the Github pages. Am I not referencing the photos correctly in the Javascript? Here is a photo that shows what the page looks like when I run it. As you can see, none of the images load into the webpage. Not sure if I am referencing the photo incorrectly in the JS, or if I need to add any HTML code to reference the photos. Either way, I would really appreciate any help. :)
HTML:
<!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">
<title>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<h1><b>Issy B. Designs</b></h1><br>
<div class="random"></div>
</body>
</html>
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_OF_IMAGES;
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}

In JavaScript Math.random() returns float between 0 and 1. By multiplying it by 90 you get a float, but all your photos are intigers. And since your pictures start from 10.png it should look like this
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const START_OF_IMAGES = 10;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';

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>

Trying to figure out why balloon pop game is not resetting clickCount

I have followed along with video from video number 76 of the Udemy "last Intro to Programming Course". I have moved code that was included all in one function to another function called "draw" I have reviewed the video multiple times and I cannot see any difference between my code and the video. The goal of the code is to reset the clickCount back to zero. Here is the code. Help would be greatly appreciated everything is working except resetting of the balloon size and clickCount with each timeout:
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let popCount = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute("disabled")
setTimeout(() => {
console.log("it's been 3 seconds")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute("disabled")
clickCount = 0
height = 120
width = 100
draw()
}, 3000)
}
function inflate() {
clickCount++
height += inflationRate
width += inflationRate
if (height >= maxsize) {
console.log("pop the balloon")
popCount++
height = 0
width = 0
}
draw()
}
function draw() {
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = popCount.toString()
}
<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">
<title>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()" >START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped</span>
<span id="pop-count"></span>
</div>
<div id="balloon" class="balloon" ></div>
<script src="main.js"></script>
</body>
</html>
I figured this out by looking at the source tab in dev tools. For whatever reason all of the lines weren't being saved or loaded to Chrome from VSCode. What I did was copy all the code from VSCode and pasted it into Notepad, saved and then refreshed. All is working fine now.

Make compatible two different pieces of code

So, am creating a game where a spaceship moves and must avoid one fireball in order to win. However I would like to have many fireballs and I managed (after hours) to get this following piece of code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<style> img {position: absolute}</style>
<body id="body"></body>
<script>
const fireballArray = [];
function generateFireBallWithAttributes(el, attrs) {
for (var key in attrs) {el.setAttribute(key, attrs[key])}
return el}
function createFireBalls(amount){
for (let i = 0; i <= amount; i++) {
fireballArray.push(
generateFireBallWithAttributes(document.createElement("img"), {
src: "Photo/fireball.png", width: "36"}))}}
createFireBalls(7)
fireballArray.forEach((fireballElement) => {
const fallStartInterval = setInterval(function(){})
document.getElementById("body").appendChild(fireballElement)
const fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 1
fireballElement.style.top = fireball.y + "px"
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + "px"
fireball.y = 0}}
fireballElement.style.left = fireball.x + "px"
let fireInterval = setInterval(fireLoop, 1000 / ((Math.random() * (125 - 75)) + 75))})
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
</script>
</html>
Source: https://stackoverflow.com/questions/63328402/add-multiple-images-video-game-js
So I would like that someone could try to put together those two pieces of code (you can also give me another solution for code n°1).
I know it is not a very good question but I really need to end this game so if anyone of you can help me it would be REALLY appreciated. Thanks.
Ps: As previously said you can give me another solution for adding fireballs

pdf.js with text selection

How to make the text in a PDF selectable?
Have tried here. The PDF is written fine, but no text selection
https://github.com/mozilla/pdf.js
https://github.com/mozilla/pdf.js/blob/master/web/text_layer_builder.css
https://github.com/mozilla/pdf.js/blob/master/web/text_layer_builder.js
'use strict';
PDFJS.getDocument('file.pdf').then(function(pdf){
var page_num = 1;
pdf.getPage(page_num).then(function(page){
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var canvasOffset = $(canvas).offset();
var $textLayerDiv = $('#text-layer').css({
height : viewport.height+'px',
width : viewport.width+'px',
top : canvasOffset.top,
left : canvasOffset.left
});
page.render({
canvasContext : context,
viewport : viewport
});
page.getTextContent().then(function(textContent){
var textLayer = new TextLayerBuilder({
textLayerDiv : $textLayerDiv.get(0),
pageIndex : page_num - 1,
viewport : viewport
});
textLayer.setTextContent(textContent);
textLayer.render();
});
});
});
<body>
<div>
<canvas id="the-canvas" style="border:1px solid black;"></canvas>
<div id="text-layer" class="textLayer"></div>
</div>
</body>
On pdf.js version 2.8.61, the checked answer does no more work, as renderTextLayer() is integrated to pdf.js, no more outside source is required, neither jQuery.
The following code will make PDF text selectable. It loads the following PDF document as example, please replace it with your own:
https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf
It uses mainly two html elements:
<canvas id="the-canvas"></canvas>
<div class="textLayer"></div>
canvas for the non selectable document for display, .textLayer div for selectable text. Text on .textLayer div is all transparent, so invisible, it provides only the selection effect.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<script src="//mozilla.github.io/pdf.js/build/pdf.js" crossorigin="anonymous"></script>
<link href="//mozilla.github.io/pdf.js/web/viewer.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#the-canvas {
border: 1px solid black;
direction: ltr;
}
</style>
</head>
<body>
<h1>PDF.js Previous/Next example</h1>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas"></canvas>
<div class="textLayer"></div>
<script>
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = '//raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
//scale = 0.8,
scale = 1,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* #param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
}).then(function() {
// Returns a promise, on resolving it will return text contents of the page
return page.getTextContent();
}).then(function(textContent) {
// Assign CSS to the textLayer element
var textLayer = document.querySelector(".textLayer");
textLayer.style.left = canvas.offsetLeft + 'px';
textLayer.style.top = canvas.offsetTop + 'px';
textLayer.style.height = canvas.offsetHeight + 'px';
textLayer.style.width = canvas.offsetWidth + 'px';
// Pass the data to the method for rendering of text over the pdf canvas.
pdfjsLib.renderTextLayer({
textContent: textContent,
container: textLayer,
viewport: viewport,
textDivs: []
});
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
</script>
</body>
</html>
Your javascript code is perfect.
You just need to include the UI utilities that Text Layer Builder depends on:
https://github.com/mozilla/pdf.js/blob/master/web/ui_utils.js
Or in HTML:
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/ui_utils.js"></script>
If you run your code (without ui_utils) and check the debug console,
you will see ReferenceError: CustomStyle is not defined.
A quick search in PDFjs's repo will show you it is defined in ui_utils.js.
Here is my minimal but complete code for your reference.
I am using PDFjs's demo pdf here.
Note that in production you should not link to raw.github.
<!DOCTYPE html><meta charset="utf-8">
<link rel="stylesheet" href="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/text_layer_builder.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/ui_utils.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/text_layer_builder.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<body>
<div>
<canvas id="the-canvas" style="border:1px solid black;"></canvas>
<div id="text-layer" class="textLayer"></div>
</div>
<script>
'use strict';
PDFJS.getDocument('file.pdf').then(function(pdf){
var page_num = 1;
pdf.getPage(page_num).then(function(page){
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('#the-canvas')[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var canvasOffset = $(canvas).offset();
var $textLayerDiv = $('#text-layer').css({
height : viewport.height+'px',
width : viewport.width+'px',
top : canvasOffset.top,
left : canvasOffset.left
});
page.render({
canvasContext : context,
viewport : viewport
});
page.getTextContent().then(function(textContent){
console.log( textContent );
var textLayer = new TextLayerBuilder({
textLayerDiv : $textLayerDiv.get(0),
pageIndex : page_num - 1,
viewport : viewport
});
textLayer.setTextContent(textContent);
textLayer.render();
});
});
});
</script>
After hours of struggling with this I found this article to be very helpful about selecting text and using pdf.js without node.
Custom PDF Rendering in JavaScript with Mozilla’s PDF.Js
Hello you have created canvas in your HTML content.
Canvas will not support text selection so you need to change the canvas to another way.

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