I'm working on creating a video game using Javascript and my knowledge is pretty basic. I'm trying to create a function that will be used to create all the sprites as well as print them to a canvas, but when I try to print them nothing works. I'm not entirely sure what the issue is or if I'm doing the whole thing wrong entirely. Below is my current code.
//Gets canvas and context
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//Creates all attributes of sprite
function sprite(imageName, imageX, imageY, imageHeight, imageWidth){
this.imageName = imageName;
this.imageX = imageX;
this.imageY = imageY;
this.imageHeight = imageHeight;
this.imageWidth = imageWidth;
this.draw = function(){
character = new Image();
character.src = "../Images/" + this.imageName + ".png";
character.onload = function(){
context.drawImage(character, this.imageX, this.imageY, this.imageWidth, this.imageHeight);
}
};
this.getHeight = function(){
return this.imageHeight;
};
this.getWidth = function(){
return this.imageWidth;
};
this.getX = function(){
return this.imageX;
};
this.getY = function(){
return this.imageY;
};
this.moveUpX = function(e){
this.imageX = (this.imageX + e);
};
this.moveUpY = function(f){
this.imageY = (this.imageY + e);
};
this.moveBackX = function(e){
this.imageX = (this.imageX - e);
};
this.moveBackY = function(f){
this.imageY = (this.imageY - e);
};
this.changeImage = function(a){
this.imageName = a;
};
this.getImage = function(){
return imageName;
};
this.changeX = function(b){
this.imageX = b;
};
this.changeY = function(c){
this.imageY = c;
};
}
//Creates Sprite
sprites[0] = new sprite('mySprite', 0, 0, 36, 51);
sprites[0].draw();
Your sprites var is undefined. You need to define that first
var sprites = []; // add this line
sprites[0] = new sprite('mySprite', 0, 0, 36, 51);
sprites[0].draw();
Related
I am trying to recieve data of multiple JSON files. I have the data I need, but multiple times, even though I use a return statement. I need the data from the getData() function. Which needs to progress to the loadImage() function. I have no clue why the code returns the same multiple times.
Thanks in advance.
My Chrome Developer Console:
My Directory Structure:
My code:
// var defaultHairData = require(['json!../character/hair/data.json'], function(data) {
// console.log("1", data);
// });
// var defaultHeadData = require("../character/head/data.json");
// var defaultLeftArmData = require("../character/leftArm/data.json");
// var defaultLegsData = require("../character/legs/data.json");
// var defaultRightArmData = require("../character/rightArm/data.json");
// var defaultTorsoData = require("../character/torso/data.json");
// var defaultHairImage = require("../character/hair/0/hair.png");
// var defaultHeadImage = require("../character/head/0/head.png");
// var defaultLeftArmImage = require("../character/leftArm/0/leftArm.png");
// var defaultLeftArmJumpImage = require("../character/leftArm_jump/0/leftArm_jump.png"); // Jump!
// var defaultLegsImage = require("../character/legs/0/legs.png");
// var defaultLegsJumpImage = require("../character/legs_jump/0/legs_jump.png"); // Jump!
// var defaultRightArmImage = require("../character/rightArm/0/rightArm.png");
// var defaultRightArmJumpImage = require("../character/rightArm_jump/0/rightArm_jump.png"); // Jump!
// var defaultTorsoImage = require("../character/torso/0/torso.png");
var character = {
name: "Homie",
jumping: false
}
var totalResources = 9;
var loadedResources = 0;
var fps = 30;
var characterXPos = 245;
var characterYPos = 185;
var characterEyesOpenTime = 0;
var characterMaxEyesHeight = 14;
var characterCursiveEyeHeight = characterMaxEyesHeight;
var characterTimeBetweenBlinks = 4000;
var characterBlinkUpdateTime = 200;
var characterBlinkTimer = setInterval(updateBlink, characterBlinkUpdateTime);
var FPSInterval = setInterval(updateFPS, 1000);
var characterCanvas;
var characterCanvasContext;
var breathAmount = 0;
var breathMax = 2;
var breathIncrease = 0.1;
var breathDirection = 1;
var breathInterval = setInterval(updateBreathing, 1000 / fps);
var cursiveFPS = 0;
var framesDrawn = 0;
window.defaultHairData = {};
function updateFPS() {
cursiveFPS = framesDrawn;
framesDrawn = 0;
}
// This is where I need the data from \/
function getData(characterPart) {
var xhr = new XMLHttpRequest();
xhr.open("GET", `./character/${characterPart}/data.json`);
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
console.log("Yoink", window.defaultData);
return window.defaultData = JSON.parse(xhr.response);
} else {
throw new Error(`Could not get file with the name "data.json" in the directory "${characterPart}".`);
}
}
xhr.send();
}
async function prepareCharacterCanvas(canvasContainer, canvasWidth, canvasHeight) {
characterCanvas = document.createElement('canvas');
characterCanvas.setAttribute('width', canvasWidth);
characterCanvas.setAttribute('height', canvasHeight);
characterCanvas.setAttribute('id', 'gameCanvas');
canvasContainer.appendChild(characterCanvas);
if (typeof G_vmlCanvasManager != 'undefined') {
characterCanvas = G_vmlCanvasManager.initElement(characterCanvas);
};
characterCanvasContext = characterCanvas.getContext('2d');
characterCanvas.width = characterCanvas.width;
characterCanvasContext.fillText("Loading...", 40, 140);
// This is where the data needs to come from
await getData("hair");
await getData("head");
await getData("leftArm");
await getData("legs");
await getData("rigthArm");
await getData("torso");
loadImage(`${defaultData.filename}`);
loadImage(`${defaultHeadData.filename}`);
loadImage(`${defaultLeftArmData.filename}`);
loadImage(`${defaultLegsData.filename}`);
loadImage(`${defaultRightArmData.filename}`);
loadImage(`${defaultTorsoData.filename}`);
}
function loadImage(datatags, picture) {
var generateButtons = Boolean;
if (datatags.filename !== picture.name) {
throw new Error("Datatag 'filename' must be the same as the picture name!");
} else {
if (datatags.fileExtension !== "png") {
throw new Error("Datatag 'fileExtension' must be png!");
} else {
if (datatags.customizeable === false) {
generateButtons = false;
} else {
generateButtons = true;
}
if (generateButtons === true) {
// Generate buttons here!
}
if (datatags.changesIfJumping === true) {
// Load normal image first here
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
}
pic.src = `../character/${datatags.filename}/0/${datatags.filename}.png`;
// Load image if jumping next
var jumpingPic = new Image();
jumpingPic.onload = function() {
resourceIsLoaded();
}
jumpingPic.src = `../character/${datatags.filename}_jump/0/${datatags.filename}_jump.png`;
}
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
}
pic.src = `../character/${datatags.filename}/0/${datatags.filename}.png`;
}
}
var pic = new Image();
pic.onload = function() {
resourceIsLoaded();
};
pic.src = `${pic}`;
};
function resourceIsLoaded() {
loadedResources += 1;
if (loadedResources === totalResources) {
setInterval(redrawCharacter(), 1000 / userFPS);
};
};
function redrawCharacter() {
var x = characterXPos;
var y = characterYPos;
var jumpHeight = 45;
characterCanvas.width = characterCanvas.width;
if (character.jumping === true) {
drawEyes(x + 40, y + 29, 100 - breathAmount, 4);
y -= jumpHeight;
characterCanvasContext.drawImage("leftArm_jump", x + 40, y - 42 - breathAmount);
characterCanvasContext.drawImage("legs_jump", x, y - 6);
characterCanvasContext.drawImage("rightArm_jump", x - 35, y - 42 - breathAmount);
} else {
drawEyes(x + 40, y + 29, 160 - breathAmount, 6);
characterCanvasContext.drawImage("leftArm", x + 40, y - 42 - breathAmount);
characterCanvasContext.drawImage("legs", x, y);
characterCanvasContext.drawImage("rightArm", x - 15, y - 42 - breathAmount);
};
characterCanvasContext.drawImage("torso", x, y - 50);
characterCanvasContext.drawImage("head", x - 10, y - 125 - breathAmount);
characterCanvasContext.drawImage("hair", x - 37, y - 138 - breathAmount);
characterCanvasContext.drawEyes(x + 47, y - 68 - breathAmount, 8, characterCursiveEyeHeight);
characterCanvasContext.drawEyes(x + 58, y - 68 - breathAmount, 8, characterCursiveEyeHeight);
};
function drawEyes(centerX, centerY, width, height) {
characterCanvasContext.beginPath();
characterCanvasContext.moveTo(centerX, centerY - height / 2);
characterCanvasContext.bezierCurveTo(
centerX + width / 2, centerY - height - 2,
centerX + width / 2, centerY + height / 2,
centerX, centerY + height / 2);
characterCanvasContext.bezierCurveTo(
centerX - width / 2, centerY + height / 2,
centerX - width / 2, centerY - height / 2,
centerX, centerY - height / 2);
characterCanvasContext.fillStyle = "black";
characterCanvasContext.fill();
characterCanvasContext.closePath();
};
function updateBreathing() {
if (breathDirection === 1) {
breathAmount -= breathIncrease;
if (breathAmount < -breathMax) {
breathDirection = -1;
};
} else {
breathAmount += breathIncrease;
if (breathAmount > breathMax) {
breathDirection = 1;
};
};
};
function updateBlink() {
characterEyesOpenTime += characterBlinkUpdateTime;
if (characterEyesOpenTime >= characterTimeBetweenBlinks) {
blink();
};
};
function blink() {
characterCursiveEyeHeight -= 1;
if (characterCursiveEyeHeight <= 0) {
characterEyesOpenTime = 0;
characterCursiveEyeHeight = characterMaxEyesHeight;
} else {
setTimeout(blink, 10);
};
};
function jump() {
if (character.jumping === false) {
character.jumping = true;
setTimeout(land, 500);
};
};
function land() {
character.jumping = false;
}
The JSON file structure:
{
"filename": "legs",
"fileExtension": "png",
"changesIfJumping": true,
"customizeable": true
}
Use more modern way - fetch instead xhr
async function getData(characterPart) {
try {
let response = await fetch(`./character/${characterPart}/data.json`);
return response.json()
} catch (e) {
throw new Error(`Could not get file with the name "data.json" in the directory "${characterPart}".`);
}
}
// TEST
async function start() {
window.defaultData = await getData('xxx');
}
start();
I am making a javascript game, using Canvas. It works well superficially, but "Uncaught TypeError: game_state.Update is not a function" keeps going. I cannot know the reason for all day...How can I solve the problem?
error image1, error image2
Suspected files are below.
gfw.js
function onGameInit()
{
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
//resourcePreLoading
resourcePreLoader.AddImage("/.c9/img/title_background.png");
resourcePreLoader.AddImage("/.c9/img/title_start_off.png");
resourcePreLoader.AddImage("/.c9/img/title_start_on.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_off.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_on.png");
resourcePreLoader.AddImage("/.c9/img/game_background_sky.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
game_state = TitleState;
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
GameFramework.js
window.addEventListener("mousedown", onMouseDown, false);
window.addEventListener("mouseup", onMouseUp, false);
var GAME_FPS;
var game_state;
function onMouseDown(e)
{
if(game_state.onMouseDown != undefined)
game_state.onMouseDown(e);
// alert("x:" + inputSystem.mouseX + " y:" + inputSystem.mouseY);
}
function onMouseUp(e)
{
if(game_state.onMouseUp != undefined)
game_state.onMouseUp(e);
}
function ChangeGameState(nextGameState)
{
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function GameUpdate()
{
timerSystem.Update();
**game_state.Update();**
debugSystem.UseDebugMode();
}
function GameRender()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
game_state.Render();
if(debugSystem.debugMode)
{
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
game_state = after_loading_state;
GameUpdate();
GameRender();
frameCounter.countFrame();
}
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/img/title_background.png");
this.imgButtonStartOff = resourcePreLoader.GetImage("/.c9/img/title_start_off.png");
this.imgButtonStartOn = resourcePreLoader.GetImage("/.c9/img/title_start_on.png");
this.imgButtonRankingOff = resourcePreLoader.GetImage("/.c9/img/title_ranking_off.png");
this.imgButtonRankingOn = resourcePreLoader.GetImage("/.c9/img/title_ranking_on.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackground, 0, 0);
//drawing button
if(inputSystem.mouseX > 170 && inputSystem.mouseX < 170+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonStartOn, 170, 480);
this.flagButtonStart = true;
}
else
{
Context.drawImage(this.imgButtonStartOff, 170, 480);
this.flagButtonStart = false;
}
if(inputSystem.mouseX > 420 && inputSystem.mouseX < 420+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonRankingOn, 420, 480);
this.flagButtonRanking = true;
}
else
{
Context.drawImage(this.imgButtonRankingOff, 420, 480);
this.flagButtonRanking = false;
}
};
TitleState.prototype.Update = function()
{
};
TitleState.prototype.onMouseDown = function()
{
if(this.flagButtonStart)
ChangeGameState(new PlayGameState());
after_loading_state = PlayGameState;
game_state = PlayGameState;
if(this.flagButtonRanking)
ChangeGameState();
};
RS_PlayGame.js
function PlayGameState()
{
this.imgBackgroundSky = resourcePreLoader.GetImage("/.c9/img/game_background_sky.png");
}
PlayGameState.prototype.Init = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Update = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
As mentioned by the others, in the onMouseDown method you are assigning after_loading_state and game_state to PlayGameState which is a function and not an object. So later on when you want to access the Update method, it simply doesn't exist, because it is defined over the object prototype and not the function. You might want to do something like this so that you also avoid instantiating (calling) PlayGameState multiple times:
game_state = new PlayGameState();
ChangeGameState(game_state);
after_loading_state = game_state;
I am making a game where it's about clicking on the nearest yellow dot from the green dot.
I got a list named dots.
You can check out my codepen to see the code I'm using.
My problem is that when you're playing the game, sometimes some of the yellow dots are too close to each other. So I am thinking if it's possible to make a collision-detection or something else, to check if the yellow dots collides?
Here is a picture of my game...
I made a red circle around the problem:
The link to my codepen project: /lolkie02/pen/PJVOdy?editors=0010
If you wanna try the game, it only works through iPhone or Android browser since I made the buttons etc. 'touchstart' in the javascript.
function getDistance(obj1, obj2) {
return Math.floor(
Math.sqrt(Math.pow(obj1.cx - obj2.cx, 2) + Math.pow(obj1.cy - obj2.cy, 2))
);
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function comparator(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
function difference(source, toRemove) {
return source.filter(function(value) {
return toRemove.indexOf(value) == -1;
});
}
////////////////
// global vars
////////////////
var svg = document.getElementById("svg");
var dotMatrix = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle"
);
var lineMatrix = document.createElementNS("http://www.w3.org/2000/svg", "line");
var screenW = window.innerWidth;
var screenH = window.innerHeight;
var totalDist = document.getElementById("distance");
////////////////
// line constructor
////////////////
function Line(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "line");
this.class = "line";
this.update = function(x1, y1, x2, y2) {
this.el.setAttribute("x1", x1 || this.x1);
this.el.setAttribute("y1", y1 || this.y1);
this.el.setAttribute("x2", x2 || this.x2);
this.el.setAttribute("y2", y2 || this.y2);
this.setAttr("class", this.class);
};
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
this.append = function() {
svg.insertBefore(this.el, svg.firstChild);
};
}
////////////////
// dot constructor
////////////////
function Dot(r, cx, cy) {
this.r = r;
this.cx = cx;
this.cy = cy;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "circle");
this.class = "dot";
this.update = function() {
this.el.setAttribute("r", this.r);
this.el.setAttribute("cx", this.cx);
this.el.setAttribute("cy", this.cy);
this.setAttr("class", this.class);
};
// activates a dot
this.activate = function() {
for (i = 0; i < dots.num; i++) {
dots.list[i].setAttr("data-selected", "false");
}
this.setAttr("data-selected", "true");
};
this.visited = function() {
this.setAttr("data-visited", "true");
};
// sets attribute to element
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
// gets attribute to element
this.getAttr = function(attr) {
return this.el.getAttribute(attr);
};
// appends element to svg and attaches event listeners
this.append = function() {
svg.appendChild(this.el);
this.el.addEventListener("touchstart", this.onClick);
};
// on click on element
this.onClick = function(event) {
//gets the id and the coords of the dot
var thisId = Number(event.target.getAttribute("data-id").substr(3, 2));
var thisCx = dots.list[thisId].cx;
var thisCy = dots.list[thisId].cy;
// calculates the distance between dots
var distances = [];
for (i = 0; i < dots.num; i++) {
distances[i] = [i, getDistance(dots.selected, dots.list[i])];
}
distances.sort(comparator);
distances.splice(0, 1);
var distancesLeft = [];
for (i = 0; i < distances.length; i++) {
if (dots.left.includes(distances[i][0])) {
distancesLeft.push(distances[i][0]);
}
}
//if the element is the nearest
if (thisId == distancesLeft[0] && dots.left.includes(thisId)) {
// calculates distances
var newDistance = getDistance(dots.list[thisId], dots.selected);
app.score.update(1); // punteggio x numero di poi
// app.score.update(newDistance); punteggio x distanza
//sets the active class to the selected dot
dots.list[thisId].activate();
dots.list[thisId].visited();
// creates the line
lines.list.push(
new Line(
dots.selected.cx,
dots.selected.cy,
dots.list[thisId].cx,
dots.list[thisId].cy
)
);
lines.list[lines.list.length - 1].update();
lines.list[lines.list.length - 1].append();
// creates the preview line
//TODO: eliminare le vecchie preline che rimangono vive
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(thisCx, thisCy, mouseX, mouseY);
});
//saves the selected dots coordinates
dots.selected.id = thisId;
dots.selected.cx = thisCx;
dots.selected.cy = thisCy;
//removes the dot from the list of remaining dots
for (i = 0; i < dots.left.length; i++) {
if (dots.left[i] === thisId) {
dots.left.splice(i, 1);
}
}
if (dots.left.length == 0) {
app.end(true);
}
} else {
app.end(false);
}
};
}
////////////////
// lines group
////////////////
var lines = {
list: []
};
////////////////
// dots group
////////////////
var dots = {};
dots.num = 20;
dots.list = [];
dots.start = 0;
dots.selected = {};
dots.selected.id = dots.start;
dots.left = [];
dots.preline;
////////////////
// app
////////////////
var app = {};
app.level = 2;
app.score = {};
app.score.number = 0;
app.score.el = document.getElementById("score");
app.score.update = function(score) {
app.score.number += score;
app.score.el.textContent = app.score.number;
};
app.score.reset = function() {
app.score.number = 0;
app.score.update(0);
};
app.results = function(points) {
if (points == "reset") {
sessionStorage.setItem("results", 0);
} else {
if (!sessionStorage.getItem("results")) {
sessionStorage.setItem("results", points);
} else {
var newscore = points;
sessionStorage.setItem("results", newscore);
}
}
};
app.launchScreen = function(lastScore, title, description, btnText) {
app.launchScreen.el = document.getElementById("launch-screen");
app.launchScreen.el.setAttribute("class", "is-visible");
var launchScreenTitle = document.getElementById("launch-screen__title");
launchScreenTitle.textContent = title;
var launchScreenDescription = document.getElementById(
"launch-screen__description"
);
launchScreenDescription.textContent = description;
app.launchScreen.btn = document.getElementById("start-btn");
app.launchScreen.btn.textContent = btnText;
app.launchScreen.btn.addEventListener("touchstart", function lauch() {
app.launchScreen.el.setAttribute("class", "");
app.start(app.level);
document.getElementById("score2").style.display = "block";
app.launchScreen.btn.removeEventListener("touchstart", lauch);
});
};
app.preline = new Line(0, 0, 200, 200);
app.preline.setAttr("id", "preline");
app.start = function(dotsNum) {
dots.num = dotsNum;
for (i = 0; i < dots.num; i++) {
var cx = getRandomArbitrary(45, screenW - 45);
var cy = getRandomArbitrary(45, screenH - 45);
dots.list[i] = new Dot(14, cx, cy);
dots.list[i].setAttr("data-id", "id-" + i);
dots.list[i].setAttr(
"style",
"animation-delay:" + i / 10 + "s; transform-origin: " + cx + 'px ' + cy + 'px;');
dots.list[i].update();
dots.list[i].append();
dots.left.push(i);
if (i == dots.start) {
dots.selected.cx = dots.list[dots.start].cx;
dots.selected.cy = dots.list[dots.start].cy;
dots.list[dots.start].setAttr("class", "dot dot--starting");
dots.left.splice(i, 1);
}
// adds the preline
app.preline.update(
dots.selected.cx,
dots.selected.cy,
dots.selected.cx,
dots.selected.cy
);
app.preline.append();
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(dots.selected.cx, dots.selected.cy, mouseX, mouseY);
});
}
// sets starting point
dots.list[dots.start].setAttr("data-selected", "true");
};
app.end = function(win) {
if (win) {
app.level += 2;
app.results(app.score.number);
} else {
app.level = 2;
}
dots.list = [];
dots.selected = {};
dots.left.length = 0;
svg.innerHTML = "";
if (win) {
app.launchScreen(
app.score.number,
"", //"Sådan!",
"", //"Din score er nu: " + sessionStorage.getItem("results") + ' Det næste level vil blive endnu hårdere.',
"NÆSTE LEVEL"
);
} else {
app.launchScreen(
0,
"", //"ARGH!",
"", //"Din endelige score blev: " + sessionStorage.getItem("results"),
"PRØV IGEN"
);
app.results("reset");
app.score.reset();
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number = 0;
score2.innerHTML = number;
document.getElementById("score2").style.display = "none";
}
};
app.launchScreen(
0,
"STIFINDER",
"Find den tætteste gule prik",
"SPIL"
);
$('.btn').on('touchstart',function(e,data) {
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number++;
score2.innerHTML = number;
});
Use Pythagorean theorem to determine whether the distance of the centers of two dots are closer (or equal) to the sum of their radii - in that case you have collision.
My answer to the similar question :https://stackoverflow.com/a/46973584/4154250
I am working on a tool to perform sequence of animations by updating an object array. This array would have all the parameters to customize animation as per varied requirements. This tool is being developed with JavaScript and makes use of createJS library and TweenJS to animate objects. Objects are created dynamically and positioned, then the tween is applied. Tween doesn't seem to work in my code.
I have the whole code below
var AnimationFlow = (function () {
'use strict';
var AnimationFlow = function (canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function (data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({'src': this.animData[i].targeturl, 'id': this.animData[i].targetID});
}
};
AnimationFlow.prototype.init = function () {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function () {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function () {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function () {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function () {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if(this.animData[i].isAnimatable){
var c = createjs.Tween.get(this.obj);
c.to({x:this.animData[i].params.xpos}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.stage.update();
};
AnimationFlow.prototype.tick = function () {
console.log("heart beat on....");
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function () {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function () {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{targetID: 'background', targeturl: 'assets/images/heliGame/sky.png',isAnimatable:true, duration: 2000, params: {xpos: '600'}, isVisibleAfterAnimation: true, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'},
{targetID: 'mousePointer', targeturl: 'assets/images/heliGame/helicopter.png',isAnimatable:true, duration: 1000, params: {xpos: '500'}, isVisibleAfterAnimation: false, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
I have the code in JSFiddle
https://jsfiddle.net/jamesshaji/t4pxzsoo/
There were a couple of issues. Firstly, you need to define all of your positions as integers and not as strings (ie: take the quotes off of your position data in your data object). Secondly, you need to call: this.timeline.gotoAndPlay(0); to start the timeline execution. Otherwise the animations won't play. Here is a fixed version:
var AnimationFlow = (function() {
'use strict';
var AnimationFlow = function(canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function(data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({
'src': this.animData[i].targeturl,
'id': this.animData[i].targetID
});
}
};
AnimationFlow.prototype.init = function() {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function() {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function() {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function() {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function() {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if (this.animData[i].isAnimatable) {
console.log("animatable:" + this.animData[i].params.xpos + " " + this.animData[i].duration);
var c = createjs.Tween.get(this.obj);
c.to({
x: this.animData[i].params.xpos
}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.timeline.gotoAndPlay(0);
this.stage.update();
};
AnimationFlow.prototype.tick = function() {
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function() {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function() {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{
targetID: 'background',
targeturl: 'https://s13.postimg.org/tyj4iop93/Sky_Pic.jpg',
isAnimatable: true,
duration: 2000,
params: {
xpos: -100
},
isVisibleAfterAnimation: true,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 0,
initialYPos: 0
}, {
targetID: 'mousePointer',
targeturl: 'http://jamesshaji.com/angular/assets/images/heliGame/helicopter.png',
isAnimatable: true,
duration: 2000,
params: {
xpos: 100
},
isVisibleAfterAnimation: false,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 450,
initialYPos: 50
}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tweenjs/0.6.2/tweenjs.min.js"></script>
<div>Animation</div>
<canvas height="500" width="500" id="testCanvas">
</canvas>
function readXML(){
var xmlDoc = loadXML();
var x = xmlDoc.getElementsByTagName("image");
for (i = 0; i < x.length; i++) {
if (i == 600){
break;
}
var path = x[i].getElementsByTagName("path")[0].childNodes[0].nodeValue;
var title = x[i].getAttribute("class");
this.imageArray.push(new InfoImage(path,title));
while(this.imageArray[i].isImageLoaded() == false); //something like this
console.log(this.imageArray[i].getMaxPixels());
}
}
function InfoImage(path,title){
this.path = path;
this.title = title;
this.color = undefined;
this.maxPixels = undefined;
this.imageLoaded = false;
this.init = function(){
var canvas = document.querySelector("canvas");
var img_Color = new Image_Processing_Color(canvas);
var img = new Image();
var info_image = this;
img.onload = function () {
img_Color.init(img);
info_image.color = img_Color.getDominantColor();
info_image.maxPixels = img_Color.getDominantColorPixels();
info_image.imageLoaded = true;
};
img.src = path;
};
this.isImageLoaded = function(){
return this.imageLoaded;
}
this.getPath = function(){
return this.path;
};
this.getTitle = function(){
return this.title;
};
this.getColor = function(){
return this.color;
};
this.getMaxPixels = function(){
return this.maxPixels;
};
this.init();
}
I want my for loop to only continue to the next iteration when img.onLoad completes. The while i'm using blocks the code and doesn't let img.onLoad complete. Is there a way to do this? Without changing the code structure.
You can check the .complete property of an img:
var x = document.getElementById("myImg").complete;
the result can be true or false
If I understood you correctly, I believe your best option is to use async.parallel (if you want it to be serial, they have a function for it - series).
This function can perform a series of tasks for you and issue a callback on complete (in which you get informed of errors).