Three.js collision detection (ERROR) - html

Im trying to make a collision detection "program" in Three.js (WEBGL library).
However, Im getting an error "cannot call method multiplyvector3 of undefined".
Can anyone tell me what Im doing wrong?
The function for collision detection I just implemented, is:
function animate() {
requestAnimationFrame(animate);
render();
for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
{
var localVertex = geometries[0].vertices[vertexIndex].clone();
var globalVertex = geometries[0].matrix.multiplyVector3(localVertex);
var directionVector = globalVertex.subSelf(meshes[5].position);
var ray = new THREE.Ray( meshes[5].position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( meshes);
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
}
else {
meshes[5].position.y -= 0.15;
meshes[5].rotation.z -= 0.15;
}
}
}
And the full code is,
<html>
<head>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/three.js/r54/three.min.js'></script>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var camera, scene, renderer, material;
var meshes = new Array();
var geometries = new Array();
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500;
camera.position.x += 125;
scene.add(camera);
geometries[0] = new THREE.CubeGeometry(35, 35, 35);
material = new THREE.MeshNormalMaterial();
geometries[1] = new THREE.SphereGeometry(35, 35, 35);
material = new THREE.MeshNormalMaterial();
for(var i = 0; i < 5; i++) {
meshes[i] = new THREE.Mesh(geometries[0], material);
}
meshes[5] = new THREE.Mesh(geometries[1], material);
for(var i = 0; i < 5; i++) {
meshes[i].position.x = (35*i);
meshes[i].rotation.x = 5;
}
meshes[5].position.y = (100);
for(var i = 0; i < 5; i++) {
scene.add(meshes[i]);
}
scene.add(meshes[5]);
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
}
function animate() {
requestAnimationFrame(animate);
render();
for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
{
var localVertex = geometries[0].vertices[vertexIndex].clone();
var globalVertex = geometries[0].matrix.multiplyVector3(localVertex);
var directionVector = globalVertex.subSelf(meshes[5].position);
var ray = new THREE.Ray( meshes[5].position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( meshes);
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
}
else {
meshes[5].position.y -= 0.15;
meshes[5].rotation.z -= 0.15;
}
}
}
function render() {
renderer.render(scene, camera);
}
}//]]>
</script>
</head>
<body>
</body>
</html>
Thank you!

for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
should be
for (var vertexIndex = 0; vertexIndex < geometries[0].vertices.length; vertexIndex++)

Related

HTML5 Canvas game, timer

Problem
Hello, I am creating a game and am stuck on how to get a timer on the canvas. I am aware that there are plenty of questions on Stackoverflow already about this topic.
Question
Could someone please tell me why my code does not work.
Code
var game = create_game();
game.init();
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var background_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
background_img.src = "background.png";
projectile_img.src = "projectile.png";
player_img.src = "player.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#410b11";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function tick() {
Most of game logic is here, I deleted as it I dont believe it helped keeping it in.
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
ctx.drawImage(background_img, 0, 0);
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#d1c09c";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
This is where i was going to put my code for the timer:
var startTime;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="bold 24px sans-serif";
g.fillText(elapsed+" secs", 75,25);
g.restore();
}
}
return {
init: init
};
}
I hope this makes sense, sorry for the overload of code.
From what I see, you might have forgotten to initialize your startTime variable.
ParseInt() of something undefined returns NaN.
Make sure to assign a value to it and that this value is accessible in the scope of your drawElapsedTime() function.

How do I remove eventlisteners and objects from an array upon game completion?

I have written a drag and drop game and, for the most part, it works.
It runs and does what I need it to do.
However, I cannot figure out two things.
How to remove the toy objects from the screen and re-add them after game over.
How to remove the event listeners for dragging/collision action after game over has initiated.
At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed.
Does anyone have any idea what I am doing wrong?
I would love to figure this out but it is driving me crazy.
Any help would be great.
Here is my code ...
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.Font;
import flash.filters.GlowFilter;
public class MainGame extends MovieClip {
const BG_SPEED:int = 5;
const BG_MIN:int = -550;
const BG_MAX:int = 0;
const PBG_SPEED:int = 3;
var bg:BackGround = new BackGround;
var paraBg:ParaBg = new ParaBg;
var toybox:TargetBox = new TargetBox;
var toy:Toy = new Toy;
var tryAgain:TryAgain = new TryAgain;
var cheer:Cheer = new Cheer;
var eightBit:EightBit = new EightBit;
var countDown:Number = 30;
var myTimer:Timer = new Timer(1000, 30);
var myText:TextField = new TextField;
var myText2:TextField = new TextField;
var myTextFormat:TextFormat = new TextFormat;
var myTextFormat2:TextFormat = new TextFormat;
var font1:Font1 = new Font1;
var kids:Kids = new Kids;
var count:int = 0;
var finalScore:int = 0;
var score:Number = 0;
var toy1:Toy1 = new Toy1;
var toy2:Toy2 = new Toy2;
var toy3:Toy3 = new Toy3;
var toy4:Toy4 = new Toy4;
var toy5:Toy5 = new Toy5;
var toy6:Toy6 = new Toy6;
var toy7:Toy7 = new Toy7;
var toy8:Toy8 = new Toy8;
var toy9:Toy9 = new Toy9;
var toy10:Toy10 = new Toy10;
var toy11:Toy11 = new Toy11;
var toy12:Toy12 = new Toy12;
var toy13:Toy13 = new Toy13;
var toy14:Toy14 = new Toy14;
var toy15:Toy15 = new Toy15;
var toy16:Toy16 = new Toy16;
var toy17:Toy17 = new Toy17;
var toy18:Toy18 = new Toy18;
var toy19:Toy19 = new Toy19;
var toy20:Toy20 = new Toy20;
var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20);
public function mainGame():void
{
trace("HI");
eightBit.play(0, 9999);
addChildAt(paraBg, 0);
addChildAt(bg, 1);
addChildAt(kids, 2);
kids.x = 310;
kids.y = 200;
addChild(toy);
toy.x = 306;
toy.y = 133;
addChild(toybox);
toybox.x = 295;
toybox.y = 90;
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
for (var i:int = 0; i < toyArray.length; i++)
{
addToys(1140 * Math.random() + 20, 170 * Math.random() + 230);
}
}
public function bgScroll (e:Event)
{
stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.start();
e.target.addEventListener(Event.ENTER_FRAME, collision);
if (stage.mouseX > 600 && bg.x > BG_MIN)
{
bg.x -= BG_SPEED;
paraBg.x -= PBG_SPEED;
for (var m:int=0; m< toyArray.length; m++)
{
(toyArray[m] as MovieClip).x -=BG_SPEED
}
}
else if (stage.mouseX < 50 && bg.x < BG_MAX)
{
bg.x += BG_SPEED;
paraBg.x += PBG_SPEED;
for (var j:int=0; j< toyArray.length; j++)
{
(toyArray[j] as MovieClip).x +=BG_SPEED
}
}
for (var k:int = 0; k < toyArray.length; k++)
{
toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab);
}
bg.addEventListener(Event.ENTER_FRAME, bgScroll);
} // End of BGScroll
public function collision (e:Event)
{
for (var l:int=0; l< toyArray.length; l++)
{
if (toyArray[l].hitTestObject(toy))
{
removeChild(toyArray[l]);
toyArray[l].x=100000;
toybox.gotoAndPlay(2);
cheer.play(1, 1);
score = score + 10;
trace(score);
}
if (score == 200)
{
timerDone();
myTimer.stop();
}
}
}
public function arrayGrab(e:MouseEvent)
{
e.target.startDrag();
}
public function arrayDrop(e:MouseEvent)
{
stopDrag();
}
public function resetGame(e:Event):void {
trace("CLICK");
countDown = 30;
myText.text = "0" + countDown.toString();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.reset();
removeChild(tryAgain);
myText2.visible = false;
score = 0;
}
public function countdown(e:TimerEvent):void
{
if (countDown > 0)
{
countDown--;
}
if (countDown < 10)
{
myText.text = "0" + countDown.toString();
myText.x = 270;
displayText();
}
else if (countDown < 20 && countDown > 9)
{
myText.text = countDown.toString();
myText.x = 280;
displayText();
}
else
{
myText.text = countDown.toString();
myText.x = 270;
displayText();
}
} // end of countdown function
public function displayText():void
{
myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)];
addChild(myText);
myText.width = 500, myText.height = 50, myText.y = 10;
myTextFormat.size = 50, myTextFormat.font = font1.fontName;
myText.setTextFormat(myTextFormat);
}
public function displayText2():void
{ myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)];
addChild(myText2);
myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200;
myTextFormat2.size = 30, myTextFormat2.font = font1.fontName;
myText2.setTextFormat(myTextFormat2);
}
public function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
addChild(tryAgain);
tryAgain.x = 300;
tryAgain.y = 300;
tryAgain.addEventListener(MouseEvent.CLICK, resetGame);
}
} // End of class
} //End of package
Nevermind ... solved it.
Easiest was was to change
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
To
function addToys(xpos:int, ypos:int)
{
stage.addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
And then, in the timerDone function I added thisif statement ...
for (var m = 0; m < toyArray.length; m++) {
if (stage.contains(toyArray[m])) {
stage.removeChild(toyArray[m]);
}
Worked a treat!

HTML5 Canvas Floating Circles

I am trying to create a floating circles effect using HTML5 and canvas. An example of what I'm going for can be seen on https://layervault.com/ You can see the example by going to the 4th slide (titled "Introducing LayerVault for iOS") in the slider. On that slide, lots of circles are floating up out of the object. So far in my code, I am only able to get 1 circle floating up. Any ideas on the approach I should take?
My Code so far:
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
var circleColors = new Array();
circleColors[0]="#f0f";
circleColors[1]="#0f0";
circleColors[2]="#00f";
circleColors[3]="#f00";
function makeCircles() {
var posX = Math.floor(Math.random()*500);
var posY = 500;
var theCircleColor = circleColors[Math.floor(Math.random()*circleColors.length)];
function renderContent()
{
context.save();
context.fillStyle=theCircleColor;
context.beginPath();
context.arc(posX,posY,40,0,2*Math.PI);
context.fill();
context.restore();
}//end function renderContent
function animationLoop()
{
canvas.width = canvas.width;
renderContent();
posY -= 5;
if (posY < -40)
posY = 500;
setTimeout(animationLoop, 33);
}//end function animationLoop
animationLoop();
}//end function makeCircles
makeCircles();
});//end document ready
You need to make an array of circles, each circle needs its own X/Y/Color and potentially speed, so they move at different rates.
So each circle will be a javascript object with
{
posX: someValue,
posY: someValue,
color: someValue,
speed: someValue
};
Then we will add many of those to an array. Here's an example using your code:
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
var circleColors = new Array();
circleColors[0] = "#f0f";
circleColors[1] = "#0f0";
circleColors[2] = "#00f";
circleColors[3] = "#f00";
var circles = [];
function makeCircles() {
for (var i = 0; i < 20; i++) {
var circle = {
posX: Math.floor(Math.random() * 500),
posY: 500,
color: circleColors[Math.floor(Math.random() * circleColors.length)],
speed: Math.floor(Math.random()*5)
};
circles.push(circle);
}
function renderContent() {
for (var i = 0; i < circles.length; i++) {
var c = circles[i];
context.fillStyle = c.color;
context.beginPath();
context.arc(c.posX, c.posY, 40, 0, 2 * Math.PI);
context.fill();
}
} //end function renderContent
function animationLoop() {
canvas.width = canvas.width;
renderContent();
for (var i = 0; i < circles.length; i++) {
var c = circles[i];
c.posY -= c.speed;
if (c.posY < -40) c.posY = 500;
}
setTimeout(animationLoop, 33);
} //end function animationLoop
animationLoop();
} //end function makeCircles
makeCircles();
And here it is live:
http://jsfiddle.net/vTaLF/

HTML5, Easel.js game problems

Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt

Requestanimationframe usage issue

I got the following RequestAnimationframe function from http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
I am trying to use it. But not sure how to call it and use it. Can someone give me a simple example. I am new to this html5 animation thing so you can understand..
I will really appreciate any help! The function is below..
(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.cancelRequestAnimationFrame = 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);
};
}())
Just paste that code into your JS or in its own file and put this inside of your rendering function at the very bottom.
requestAnimationFrame(yourrenderingfunction);
Live Demo
// requestAnimationFrame shim
(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.cancelRequestAnimationFrame = 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);
};
}())
// Sprite unimportant, just for example purpose
function Sprite(){
this.x = 0;
this.y = 50;
}
Sprite.prototype.draw = function(){
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(this.x, this.y, 10, 10);
}
// setup
var canvas = document.getElementsByTagName("canvas")[0],
ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;
//init the sprite
var sprite = new Sprite();
// draw the sprite and update it using request animation frame.
function update(){
ctx.clearRect(0,0,200,200);
sprite.x+=0.5;
if(sprite.x>200){
sprite.x = 0;
}
sprite.draw();
// makes it update everytime
requestAnimationFrame(update);
}
// initially calls the update function to get it started
update();