Coder Social home page Coder Social logo

jaws's Introduction

Jaws - HTML5 Javascript web game development library

<img src=“https://travis-ci.org/ippa/jaws.svg?branch=master” alt=“Build Status” />

Depends on JavaScript Edition 5. Works with Chrome 9+, Firefox 3.6+, Safari 5+ & IE9.

Licensed under LGPL so you’re free to use it for commercial projects.

Highlights

  • Animation(), Sprite(), SpriteSheet(), TileMap(), Assets() and other useful constructors

  • Easy and robust game state system to switch between menus, play, high score lists and settings

  • JSDOC Documentation & commented examples

Jaws also:

  • Uses 2D canvas to draw stuff on the screen

  • Does not depend on any other JavaScript library

  • Suple-simple-to-use collision detection, bounding box and circles.

  • Doesn’t try to force a certain “JS class pattern” on you, just pure JavaScript as mother nature intended it

  • Tries to make assets (images, music, json data) in webgames as easy as possible

  • Often does object literals as arguments for readabillity (ie. new Sprite({image: “player.png”, x: 100, y: 100})

  • Builds on lessons learned from years of developing github.com/ippa/chingu (Ruby game lib)

Install

$ bower install jaws

Local build / test

npm install
npm test

Learn more

Tutorials

What kind of games can you make with Jaws?

Jaws is well suited for “classic” side/top scrolling games (tile based or not) where you have a number of sprite-sheet-animated sprites. Jaws comes with basic rect-vs-rect/circle-vs-circle collision detection that works well in most cases. If you have tons of sprites (for example, a bullet hell schmup) you probably want to use a physicslib like Box2D or spatial hashing like quad trees to speed things up. Jaws use of canvas makes pixel perfect collisions and worms-style terrain relatively easy to develop. If your game is very GUI-heavy you might want to base your game on pure HTML-elements instead of canvas-sprites.

Simple examples demonstrating certain features

Check out the sourcecode for comments and explanations:

Games using Jaws

… missing your game here? Mail me about it (my email is on my github profilepage). Or create a new issue.

Libs using Jaws

Loading Jaws

  • jaws.js - includes the whole framework in one easy-to-include file.

  • jaws-min.js - same as jaws.js but minified with Googles closure compiler. This is probably what you want to include in your project.

  • jaws-dynamic.js - dynamically loads all separate jaws files. Useful for debugging errors when patching jaws since you get exact file/line# of possible errors. Warning, jaws-dynamic.js loads all Jaws-files asynchronously, resulting in Jaws might not be fully loaded when the browser reaches your game.js. You can solve this by hooking into the jaws.onload callback and put your jaws.start() there.

You can also link to invidual files in your HTML:

<script src="/jawsjs/src/core.js"></script>
<script src="/jawsjs/src/sprite.js"></script>

NOTE: core.js is always needed but after that you can pick and choose depending on what you need. A rule of thumb is that a file named “foo.js” will include a constructor named Foo().

NOTE #2: jaws.js and jaws-min.js does Not include files from src/extras-dir. Examples of files that aren’t included in the mainbundle are: tile_map_pathfinding.js, pixel_map.js and audio.js (jaws <audio>-wrapper). If you want to use them, load them as usual:

<script src="/jawsjs/src/extras/tile_map_pathfinding.js"></script>

Contribute

Jaws accepts contributions, some simple guidelines:

  • Formatting: oneFunction(), OneConstrutor() and one_variable

  • 2 spaces for indentation

  • Don’t patch jaws.js or jaws-min.js, but rather the invidual files in the src/-directory

  • Please bundle tests with non-trivial patches, see test/-dir for inspiration

  • For bigger patches/feature additions, please contact me beforehand to discuss if/how it fits into Jaws and how to form the API

  • Naming shouldn’t consist of abbreviations, let’s use “context”, not “ctx”

Jaws has gotten bigger contributions from:

github.com/videlais - QuadTree() and other things github.com/dmitrizagidulin - SpriteList() rewrite github.com/gregmax17 - Viewport related stuff github.com/MalphasWats - Viewport pathfinding

Issues and bugs

If you find an issue with Jaws githubs issue-tracker is the place to go. Easiest for the developers is if you put your game online. If you don’t have any hosting check out pages.github.com/. Pasting your problematic code in the issue-ticket itself will usually mean a lot of hassle with supportcode and assets to actually be able to test the code in question.

API-deprecations leading up to ver 1.0

2013-09: Remove experimental, buggy DOM-sprite-support from Sprite and Text
2013-08: SpriteList is no longer included in jaws(-min).js bundle, better off using arrays and jaws.draw/jaws.update
2013-08: jaws.assets.loadAll() -  onfinish -> onload, onload -> onprogress
2013-08: jaws.assets.load(asset, options)  - options can have properties onload and onerror
2013-03: sprite.anchor() is now sprite.setAnchor()
2013-03: sprite.scale() is now sprite.scaleAll()

Example

<html>
<script src="jaws.js"></script>
<body>

<canvas width=500 height=300></canvas> 

<script>
  function MyGameState() {
    var player;
    var robot;

    this.setup = function() {
      player = new jaws.Sprite({image: "player.png", x: 10, y: 200});
      robot = new jaws.Sprite({x: 200, y: 200});
      robot.animation = new jaws.Animation({sprite_sheet: "images/droid_11x15.png", frame_size: [11,15], frame_duration: 120});
    }
    this.update = function() {
      if(jaws.pressed("left"))  { player.x--; }
      if(jaws.pressed("right")) { player.x++; }
      robot.setImage( robot.animation.next() );
    }
    this.draw = function() {
      player.draw();
      robot.draw();
    }
  }

  window.onload = function() {
    jaws.assets.add("images/droid_11x15.png");
    jaws.assets.add("images/player.png");
    jaws.start(MyGameState);
  }
</script>
</body>
</html>

The same example with comments

/*
* Jaws provides powerful functions like jaws.start() to quickly get a robust gameloop running.
* It's also possible to do it more manually, fetch your own canvas context and send it to new Sprite().
* Nothing stops you from using jaws.assets or other jaws.helpers with your own game loop either.
*
* Below code shows the preferred way, letting jaws worry about most of the setup, 
* so we can get straight to get game logic.
*/
<html>
<script src="jaws.js"></script>
<body>

<canvas width=500 height=300></canvas> <!-- don't set width/height of canvas with CSS -->

<script>
  /*
  * Jaws encourages the use of game states to separate various parts of your game.
  * We send MyGameState to jaws.start() to start with.
  * You can later switch to another game state with jaws.switchGameState(OtherGameState)
  */
  function MyGameState() {
    var player;
    var robot;

    /* Put your one-time initializing here. Will get called once each time this game state is activated. */
    this.setup = function() {
      /*
      * Make a sprite, place it at position 10/200.
      * The string "player.png" will resolve to a previously fetched resource.
      * If we wanted the sprite to be drawn to a special canvas, we could add the option {context: my_canvas_context}.
      * Otherwise jaws will just pick the most likely canvas, which works 99% of the times.
      */
      player = new jaws.Sprite({image: "player.png", x: 10, y: 200});

      /* Let's create an animated robot sprite */
      robot = new jaws.Sprite({x: 200, y: 200});

      /* Creates an animation from a classic sprite sheet */
      robot.animation = new jaws.Animation({sprite_sheet: "images/droid_11x15.png", frame_size: [11,15], frame_duration: 120});
    }

    /* update() is called each gametick with given FPS. Put your game logic here. */
    this.update = function() {
      if(jaws.pressed("left"))  { player.x--; }
      if(jaws.pressed("right")) { player.x++; }
      robot.setImage( robot.animation.next() );
    }

    /* draw() is called each gametick just after update() is done. Put your drawing/canvas stuff here. */
    this.draw = function() {
      player.draw();
      robot.draw();
    }
  }

  /* Let's start jaws after the document is fully loaded... */
  window.onload = function() {
    /*
    * Add two images to jaws internal list of assets to be loaded.
    * You can load them manually with jaws.assets.loadAll({loaded: myAssetsAreReadyCall}).
    * jaws.start() will automatically load all unloaded assets while displaying a progress meter.
    *
    * Alternative way (nice when you have a lot of assets in the same dir): 
    *   jaws.assets.path = "images/"; 
    *   jaws.assets.add(["droid_11x15.png", "player.png"]) 
    */
    jaws.assets.add("images/droid_11x15.png");
    jaws.assets.add("images/player.png");

    /*
    * jaws.start(MyGameState) is the easiest way to get something up and running. It will in this order:
    *
    * 1) 
    * Call jaws.init() that will detect <canvas> (or create one for you) and set up the 2D context.
    * It's then available in jaws.canvas and jaws.context and will be used by all new sprites.
    * Also setup keyboard input event listeners with jaws.setupInput().
    *
    * 2) 
    * Pre-load all assets while showing progress meter through with jaws.assets.loadAll().
    * Assets are then available with jaws.assets.get("player.png").
    *
    * 3) 
    * Create an instance of given game state constructor (in this case MyGameState) and call setup() on that instance.
    * In setup() you usually initialize the game state, create the gameobjects, sprites and so forth.
    *
    * 4) 
    * Loop calls to update() and draw() with given FPS (default 60) until the game ends,
    * is paused or another game state is activated.
    *
    */
    jaws.start(MyGameState);
  }
</script>
</body>
</html>

jaws's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jaws's Issues

Question: viewport y

I can't seem to get a viewport to render only on the bottom part of the canvas. I can get it to render on only the top part just fine.
canvas size is 500,320

// render top half - works
viewport_top = new jaws.Viewport({max_x: width*32, max_y: height*32, height:160 })
//expected this to render to the  bottom half of the canvas
viewport_bottom = new jaws.Viewport({max_x: width*32, max_y: height*32, height:160, y: 160 }) 

Private object variables accessible from outside.

Hi ippa, here are a few things I noticed. I could open new issues for each if you want.

Private variables
Assigning to a rect's x/y does not alter right/bottom. This creates problems like tile_map.atRect(rect) not working due to right/bottom being off. I imagine x/y are supposed to be private. Is it possible for jaws' current design to accomodate private object member variables?

I worked around it by calling moveTo() every update() with the rect's current x/y.

Jumping mid air after walking off a ledge
Example 9 (the side scrolling platformer) uses the can_jump variable, which is assigned true when the player collides with the ground. The player is therefore able to jump in midair after falling from a ledge, because can_jump is still true.

I added a feet_rect under the player that "attaches" to his feet. I then added a canJump() function to check if the feet_rect is colliding with something. So the player only jumps when his feet are in contact with something.

player.canJump = function() {
  var collided_block = tile_map.atRect(feet_rect)[0];

  if (collided_block) {
    return true;
  }
}

// in the update function:
//if(jaws.pressed("up"))    { if(player.can_jump) { player.vy = -10; player.can_jump = false } }

if (jaws.pressed("up")) {
  if (player.canJump()) {
    player.vy = -10;
  }
}

Jaws side scrolling platformer example 9 "fixed"

Example 9 JavaScript gist "fixed"

Rect.js function parameters
Rect.js uses raw function parameters instead of an option object like most of the other classes. I'm not sure why this is the case.

Examples index.html
Being able to navigate the examples would be convenient. Maybe a link back to the index from each example, or even a table of contents.

Offline development
Chrome offline development is hairy due to XSS. Firefox 11 is happy to run them offline though. I'm not sure what can be done about this besides informing devs how to work around the inconvenience.

Tell me if anything is unclear or if you need more info. If none of these are of concern then I'll leave them be.

Thanks!

Sprite.image

Changing the image of my sprite via:

my_sprite.image = "hello.png";

sprite.image is not working, I get "TypeError" on jaws.js.

my_sprite.setImage ("hello.png");

However, doing sprite.setImage ("new_image.png") is working.

sprite.rect() X and Y NaN

Hi,

I'm trying to make a game using jawsJs, which is really helpful.
I found a weird comportement, trying to detect collision between a sprite and a tile block.
when i use a statement as :

if(tile_map.atRect(sprite.rect()).length > 0) { 
...;
}

the test was always false.
I made a console.log(sprite.rect()); and sees that X and Y properties of the rect were "NaN".
then a console.log(sprite); shows that the "offset"properties are false either (NaN also)

When i initialise my sprite, i declare the offsets

            var sprite = new jaws.Sprite({anchor: "center center", x: x, y: y});
                        (......other sprite properties...)
            sprite.setImage( sprite.anim_default.next() );
            sprite.left_offset = 0;
            sprite.right_offset = 0;
            sprite.top_offset = 0;
            sprite.bottom_offset = 0;

It seems sprite.move() change the offsets to NaN

i have to re-declare the 4 offsets as shown before, to have the collision detected correctly.

Anyway, i first started a Html5 game from scratch.. it's much easier with JawsJs.. thanks && keep up !

Feature request: tilemap ROW and COL returned

It would be very helpful for collision detection etc if each sprite returned by the tile_map.atRect etc functions had an additional rect returned: tilemaprect. So we could know .tilemaptop, left, bottom, right, tilemapCOL, tilemapROW.

Why? I store all pickups in a platormer in the tilemap for speed (rendering AND collision). Then you hit a coin, you can't remove it from the tilemap without first CALCULATING which tilemap tile was returned via the sprite's x,y. Then you have to SEARCH the array at the tilemap[row][col][] you calculated to find the sprite in question if there are more than one. All this just to remove a coin from the tilemap.

Essentially I'd love a "this is the tilemap you hit" data to make accessing (changing) the tilemap more intuitive.

P.S. YOU ROCK! Forgive all the requests - I know you're busy. Just an idea you may want to consider for a "someday" upgrade.

Cannot load .bmp on chrome?

Hi, I noticed that in example 8 you used an image called block.bmp.

The example is working if I opened it at your page but when I downloaded the files and opened locally, It always stuck at 50%.
It works fine on firefox but stuck at chrome.

Also if I uncomment either one or both of these lines, the robot won't move
// uncomment to show bounding box rects
// blocks.forEach( function(item, total) { item.rect.draw() })
// player.rect.draw()

setupInput()
assets.loadAll()
#50%: droid_11x15.png

(dunno why the text suddenly become larger)

Cannot rotate sprite properly

Great library but I am finding difficulties with rotating a sprite properly. I used to work with this:

context.save();
context.beginPath();
context.translate(xCenter, yCenter);
context.scale(1, 0.5);
context.scale(2.75, 2.75);
context.rotate(-rot);
context.translate(-128, -128);
context.drawImage(image, 0, 0);
context.closePath();
context.restore();

The result is an isometric rotation.

But with JawsJS I find it hard to invoke these methods on the context in that order because the draw function is very limited. What would be a correct approach?

Opinion: Best way to structure larger games.

Hey,

I couldn't figure out a better place to get in contact with you to ask your opinion on this so I figured a github issue would have to do.

After getting a few demos up and running. I'm thinking about attempting a slightly larger project and before I dive in entirely, I wanted to get your thoughts on structure. I hate large monolithic files (I blame rails for this) and would like to split my code up as much as possible, but I continue to run into issues with scope. I've read up on some basic OOP and loose augmentation with js files.

I'm going for a directory structure where gamestates and classes have their own directory and are called from game.js

Any input would be great.

Thanks

Would be nice to include a version number in jaws.js

Hi ippa, great library, just beginning to try it out.

It'd be nice to include a version number either in the comments or as a property in jaws.js, so that it's easy to track whether my copy is the newest or not.

Sorry if I missed it (please point it out in that case)

Also git tags per release would be great.

Uses much memory?

HI,

First, you really did a great work!

I found example12 uses much memory in Safari(>460M) or Firefox (About 700M), but it only uses about 200M in Chrome. That's hard to run it on my mobile. So, would you please check if the memory usage could be reduced? (My PC testing environment is Mac OS Lion).

numpad0 keycode missing

In input.js line 75:var numpadkeys = ["numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9"]

This make numpad1(keycode:97) actually trigger by the numpad0(keycode:96), I think here should add "numpad0" at first.

Because in input.js line 81:for(var i = 0; numpadkeys[i]; i++) { k[96+i] = numpadkeys[i] }
This is start from keycode 96, where is numpad0's keycode.

Thanks!

Feature? Delete from TileMap

Hi there!
Wouldn't it be cool if we could delete objects from a TileMap no?
Therefore a bunch of functions wourd be welcome:

  • jaws.TileMap.pop()
  • jaws.TileMap.popAsPoint()
  • jaws.TileMap.popAsRect()
  • jaws.TileMap.popFromCell() ?

One more thing to think about. What to do when there's more than one object on a tile? Delete the whole array?..

Gamepad support, multiplayer considerations?

Hey there,

Just wondering if you've spent any time working with the Gamepad API, now that it's in live builds of Chrome and Firefox... I whipped up something to add support myself, but it's far from perfect at this point. Xbox 360 support only, but that would be easy enough to change. Feel free to check it out on my fork: https://github.com/zatch/jaws

Criticisms and enhancements appreciated!

-Zatch

SpriteList still drawing elements after they're removed

Hi ippa,

So after beating my head against the wall on this issue all last night, this is what I found out.

If you add a sprite to a SpriteList, and then remove it, and then call draw() on the sprite list,
the removed sprite is still drawn.

What this actually boils down to is:

list = new SpriteList
list.push('a')
list[0]  //=> 'a'
list.splice(0, 1)  
list.length  //=> 0. But!
list[0] //=> 'a', still

You can see a more detailed demo here:
https://github.com/dmitrizagidulin/IronSanta/blob/c03fdaeb2ad6c48475e3d082751bc961867ca692/sprite_list_issue.html

And the reason for THAT behavior is, basically, you can't subclass Array, in javascript, as this excellent article explains:
http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

Meaning, it's not just the SpriteList. You can duplicate this behavior by creating any subclass of Array (ie creating a new object and setting Array as its prototype, as JawsJS does). The resulting "subclass" of Array will not behave properly with regards to various methods, including splice()

So.. would you accept a patch to rewrite SpriteList using composition instead of inheritance? (that is, a SpriteList would have an attribute called 'contents', which would be an actual array, which would store the list of sprites, and delegate its calls to it, etc)

Player is Not Defined

Hey ippa,
This jaws library is amazing, but i've run into a bug that I simply cannot figure out and thought I'd get your take on it.

The game keeps pausing at 100% loaded and when I check my console it tells me, game.js:28Uncaught ReferenceError: player is not defined

Its very odd, because my player is defined and I cannot for the life of me figure this out.

Thanks

My game.js file

function Game() {
  this.setup = function() {
    this.player = new jaws.Sprite({
      image: "plane.png",
      x: jaws.width / 2,
      y: jaws.height / 2,
      anchor: "center"
    });
    jaws.preventDefaultKeys(["up", "down", "left", "right"]);
    return;
  };
  this.update = function() {
    if (jaws.pressed("left")) {
      player.x -= 2;
    }
    if (jaws.pressed("right")) {
      player.x += 2;
    }
    if (jaws.pressed("up")) {
      player.y -= 2;
    }
    if (jaws.pressed("down")) {
      player.y += 2;
    }
    return;
  };
  this.draw = function() {
    player.draw(); // This is the line calling the error ------------------------
    return;
  };
  return;
};
window.onload = function() {
  jaws.assets.add("plane.png");
  jaws.start(Game);
  return;
};

and my index.html file

<html>
  <head>
    <title>Test Game with Jaws Framework</title>
  <script src="jaws.js" type="text/javascript"></script> 
  </head>
  <body>
    <canvas></canvas>
    <script src="game.js"></script> 
  </body>
</html>

Tilesets instead of individual images

Just like the title states, is there a way this can be accomplished with the current JawsJS framework? Are there any plans to release something similar to this? It would make use of the tilemap a class a lot easier. I don't like having to specify each tile as an image.

PixelMap 'tainted cross-origin data' in chrome 25

Trying to use the PixelMap functionality in chrome, but it seems to have issues loading the content (something to do with it using a canvas internally to store/modify the image?). The below code works with no issues in firefox 18

code looks like so:

jaws.setup = function()
{
    [...]
    pixelmap = new jaws.PixelMap({image: "skyline.png", scale_image: 1})
    [...]
}
jaws.onload = function()
{
    [...]
    jaws.assets.add("skyline.png")
    [...]
}

stacktrace is below:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. jaws.js:677
jaws.retroScaleImage jaws.js:677
PixelMap jaws.js:2969
Example3.setup ds.js:9
GameLoop.start jaws.js:1591
jaws.switchGameState jaws.js:404
assetsLoaded jaws.js:348
processCallbacks jaws.js:1453
assetLoaded jaws.js:1400
Uncaught Error: SecurityError: DOM Exception 18 jaws.js:677
jaws.retroScaleImage jaws.js:677
PixelMap jaws.js:2969
Example3.setup ds.js:9
GameLoop.start jaws.js:1591
jaws.switchGameState jaws.js:404
assetsLoaded jaws.js:348
processCallbacks jaws.js:1453
assetLoaded jaws.js:1400

ParallaxLayer.x and .y don't do anything

When ParallaxLayer.x and ParallaxLayer.y are assigned on layer creation, they seem to have no effect on the layer's positioning on the canvas when drawn. Instead, I've had to bruteforce it by adding a constant onto the camera_x and camera_y.

This is based simply on my assumption of how ParallaxLayer.x and ParallaxLayer.y are supposed to act--this may be entirely incorrect. In any case, the only way I could at all affect the layer positioning was by monkeying with line 1931 of jaws.js--setting that to either a constant changed the y positioning of the layer. However, I wasn't sure how the x and y were supposed to be computed, and therefore couldn't figure out how to fix the issue.

Mouse down event

I'd like a "if jaws.mouse_down() { }" function, that I can call from update function.

Thank you!

About the viewport bound

Hello, I'm trying to use jaws to make a game,
and I want scroll the screen when player leave.

I use "viewport.isInside(player)" to do this, but here has some problem.

It is a board game, one step is 32px, and my screen size is 320x320(10x10 square on screen), viewport's height & width is 320 too, x & y range is 0~319 from top left corner.
When player is on (320,y) or (x,320), the 11st square, it is totally leave the screen but viewport still think player is inside the viewport.

This may because min of x & y is 0, and min of height & width is 1?

Last, I have one more question, why you made "jaws.cutImage (image, x, y, width, height)" as private?
I think this is a useful function :P

Thanks!

handleKeyUp and handleKeyDown are not passing the key

I expected those two to pass what key has been pressed. In my case I want to handle all the numbers and need the exact key to be passed.

  jaws.on_keydown(['0', '1', '2', '3', '4'], function(key) { alert(key) } )

No functions for mouse bindings(?)

Hi, I really liked the examples and the simple documentation provided for this js game library, but I couldn't seem to find any subject regarding mouse bindings.
In the game I intend to make I want to make it react on mouse events, both when clicking and moving the mouse.
How would I go about doing this?

Thanks in advance.

method 'saved' of undefined

var bubbles = new _bubbles();

$(document).ready(function() {
    var context = $('#canvas')[0].getContext("2d");
    jaws.assets.add(["img/red-bubble.png","img/yellow-bubble.png","img/blue-bubble.png","img/purple-bubble.png","img/green-bubble.png","img/black-bubble.png"]);
    jaws.start(GameState);
});

function GameState() {
    this.setup = function(){
        bubbles.loadAllAnimations();
        bubble_spritelist = jaws.SpriteList();
        bubble_spritelist.push(bubbles.red.sprite);
    }
    this.update = function() {
        bubbles.red.sprite.setImage(bubbles.red.animation.next());
    }
    this.draw = function() {
        jaws.clear();
        bubble_spritelist.draw();
    }
}

function _bubbles(){
    this.red = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
    this.yellow = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
    this.blue = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
    this.green = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
    this.purple = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
    this.black = { sprite: new jaws.Sprite({ x:0, y:0 }), animation: [] };
}

_bubbles.prototype.loadAllAnimations = function(){
    bubbles.red.animation = bubbles.loadAnimation("red");;
    bubbles.yellow.animation = bubbles.loadAnimation("yellow");
    bubbles.blue.animation = bubbles.loadAnimation("blue");
    bubbles.green.animation = bubbles.loadAnimation("green");
    bubbles.purple.animation = bubbles.loadAnimation("purple");
    bubbles.black.animation = bubbles.loadAnimation("black");
}
_bubbles.prototype.loadAnimation = function(color){
    return new jaws.Animation({sprite_sheet: "img/"+color+"-bubble.png", frame_size: [40,40], frame_duration: 100});
}

basic basic problem

Just beginning to tinker with jawsjs and... Cannot read property width of undefined.

red_bubble_spritesheet = new jaws.SpriteSheet({image: "img/red-bubble.png", frame_size: [40,40] });

Straight out of the engine constructors example.
Yes the image exists.

Problem with viewport.move(x,y), when argument is float

Hi.
I have a problem with viewport when it's moved by non-integer numbers.
There is modified example#12:

http://dreamella.pl/jaws/examples/example12,5.html

I change the droids moving speed from 2.00 to 2.11 and add red background to canvas.
If you move droid to position, for example, 400, 400 you will see red lines.
This problem appear in Fire Fox 18, Opera Next 12.12 and Internet Explorer 9.
In Google Chrome 23.0.1271.97 m (latest version) work fine.

My OS is Windows 7 Proffesional up to date.

canvas squished on x axis if id=canvas

If I set the id of the canvas to "canvas" the whole thing renders squished.

this isn't a huge issue because if the id="something_else" it doesn't matter, but I thought i would mention it as it might point to some broken logic in core.js

More SpriteSheet flexibility

Looking at the docs and the code of the SpriteSheet class, there is limited flexibility regarding cutting up sprite sheets. They have to fixed sized frames in horizontal or vertical order. Working with (an example, Google'd for "sprite sheet") something like this: (http://www.pixeljoint.com/files/icons/full/sprite_sheet.png) is currently not possible (or am I missing something?).

Should I refactor my sprite sheet so Jaws can work with it properly or is there a more efficient way to do this?

number keycodes offset by 1

Line 60 of src/input.js """var numbers = ["1","2","3","4","5","6","7","8","9"]""" I think because of the missing 0, all the codes are off by 1. For example, pressing "0" triggers the event for 1, and pressing "2" tiggers 1's event.

Finally, brilliant library, really simplifies sprite and asset management.

Rotate viewport

I'm not sure how hard this would be but I think it would be awesome to be able to rotate view-ports.

Documentation download

Hi ippa. Nice engine, man. I like the fact that every method is documented. I was just wondering whether the documentation is available for download. There's a Ruby build script, I understand, but from what I can tell it's for development on your end. The speed of offline documentation is noticable and saves you bandwidth, too.

Thanks, and good luck with your next Ludum Dare!

canvas doesn't render in certain cases

Depending on various dimensions, I get a white page instead of a canvas. I think it's related to the max width and max width of my viewport compared to the size of the canvas. You can reproduce the problem here: http://pastebin.com/1YK4DBNT . To fix the problem, in that code change config.mapXTileCount to 51 (instead of 50).

For example, on a canvas that's 1024x768, I get the problem when the viewport has max_x of 1000 and a max_y of 1000. I don't get the problem when the viewport's max_x is 1020.

invalid asset path is repeatedly retried

If I call "jaws.assets.add()" with a string argument representing an invalid asset path, then that path is attempted to be fetched each time it is referenced in a jaws.Sprite constructor. This leads to massive slowdown (and lots of network traffic) if there are thousands of sprites that use this invalid asset path.

I would prefer an invalid asset is not attempted to be retrieved once it fails to be retrieved the first time. Also, an exception or even a console error would be nice as soon as the asset is deemed invalid.

Sprite custom anchor points

I believe you intended for custom sprite anchor points at one time but it doesn't appear the code is working.

lines 1145 and 1146 in jaws.js have the following:

if(!options.anchor_x == undefined) this.anchor_x = options.anchor_x;
if(!options.anchor_y == undefined) this.anchor_y = options.anchor_y; 

The following code doesn't seem to work without modification:

ttop = new jaws.Sprite({'image':'images/tanktop.png', x:100, y:100, 'anchor_x':0.5, 'anchor_y':0.75});

Sprite.setImage doesn't take into account scale_image

Currently, when using setImage with a Sprite, it will ignore any previous set scale_x, scale_y, or scale_image properties. I can't decide if this is an issue or not with setImage. However, if it is not, then should setScale be included in Sprite?

sprite = new jaws.Sprite({image: "path/initial image", scale_image: number});

Basically, should it be:

sprite.setImage("path/new image"); //Internal scaling

or:

sprite.setImage("path/new image");
sprite.setScale(number);

or even:

sprite.setImage(jaws.gfx.retroScaleImage("path/new image"), sprite.scale);

Suboptimal SpriteSheet code

I was looking through the Jaws code to see how it worked when I noticed that you store sprites as canvas elements.

Curious, I wrote a quick test to see what sort of performance each type of drawImage will get, and here are the results. As you can see, canvas is by far the worst performer. The BlobURL method seem to work very well in Chrome, but createObjectURL isn't compatible with all browsers.

If compatibility doesn't matter as much as speed, you might want to switch to using createObjectURL. Otherwise, data: URLs are still looking good.

After that, I thought it might be good to look into the performance difference of pre-cutting spritesheets as opposed to just leaving them one image and using drawImage(Object image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh) to pick out pieces of them at blit-time. Here's that test which seems to indicate that it doesn't matter which you use. Since both are the same speed, I would go with the dynamic lift as it doesn't take up extra memory for all the individual sprites, it only needs a reference to the existing spritesheet image asset.

jaws bug?

Hi I'm new in html 5. I'm actually new in game development.

I noticed that when the player is moving, if you change the browser tab or opening something that make the page suddenly lose focus, when you get back to the page, the player will keep moving and hard to be stopped.

In this page http://jawsjs.com/jawsjs/examples/example3.html
if you move left(keep pressing left arrow), then suddenly change to other tab and got back to the example tab, you'll notice that the robot will keep moving to the left.

Feature Request: Text Support

This is just as much a question as it is a feature request: Is there a reason that there isn't any support for drawing text?

I'm considering creating a copy of the Sprite class and modifying it to create a "Text" class that will accept a "text" option instead of a "image" option. Additionally, I would swap the setImage() method with a setText() method.

Are there any reasons that I -shouldn't- do it this way? Is there a better way? If there are already plans to add text support, should I even bother?

Thanks!

jaws.Assets() Arrays vs. Objects

I've been looking at the source for jaws.Assets and noticed that, although the "loaded", "loading" and "data" properties of the Assets() instance are defined as Arrays, they seem to be treated as Objects (i.e. "associative arrays" rather than indexed numerically).

My questions are:

  1. What is the rationale behind defining these as Arrays rather than plain Objects/hashes? Are there any advantages to doing it this way?
  2. When using multiple instances of jaws.Assets(), I've had trouble getting my onload() handlers to fire (when passed in as an option to loadAll()). Does anyone else have experience with using multiple instances of the assets loader?

distanceBetween seems to have an obvious bug...

jaws.distanceBetween = function(object1, object2) {
return Math.sqrt( Math.pow(object1.x-object2.x, 2) + Math.pow(object1.y, object2.y, 2) )
}

I think the last pow call needs to subtract the y's like this:
Math.pow(object1.y - object2.y, 2)

add fillRect and fillStyle to sprites (& sprite lists, tile maps)

I was thinking it might be useful to be able to create sprites using fillRect and fillStyle as per the canvas 2D context spec, for quick colored background, blocks etc. This could have been used in example 8 instead of block.bmp

Long term creation of sprites using other drawing methods like beginPath & arc could also be cool.

Thoughts?

Question: how to use jaws.Text?

I'm trying to use jaws.Text, but I cannot make it work and cannot find any example on how to use it :(

Here's what I've tried so far (here's the jsfiddle)

var text;

function setup() {
    text = new jaws.Text({text: "Hello World", x: 10, y:10});
}

function draw() {
    jaws.clear();
    text.draw();
}

jaws.start();

What am I doing wrong? Thanks! :)

jaws.Parallax.add_layer use jaws.Parallax.prototype.default_options.layers

Hello, I'm new with jaws.js and I love it. I just found something here, not sure if it's me or a real bug.

// in the menu GameState
var para1 = new jaws.Parallax({});
para1.addLayer({image: "image1.png", damping: 1});
para1.addLayer({image: "image2.png", damping: 2});
console.log(para1.layers.length); // 2

// in another GameState
var para2 = new jaws.Parallax({});
para2.addLayer({image: "image3.png", damping: 3});
console.log(para2.layers.length); // 3, should be 1 right?

It make the parallax from the menu gamestate visible in the gamescene gamestate.
A good workaround is to not use that function but the constructor instead:

var para1 = new jaws.Parallax({
   layers: [
      new jaws.ParallaxLayer({image: "image1.png", damping: 1}),
      new jaws.ParallaxLayer({image: "image2.png", damping: 2})
  ]
});

Possible Memory Leak

This is not a very detailed bug report but I thought you may find this interesting. I had one of the demos open in my browser (example3 i believe) all night and in the morning noticed the FPS had dropped to 12. Sorry that I don't have more details but I thought it may at least be a heads up that there could be a memory issue.

P.S. I really like our engine. I've been toying with the idea of creating games for a while now and being a javascript developer, wanted to find a good js game engine. I appreciate that you've honored pure javascript and idiomatic constructs. So many people try to bastardize js into something it's not. I can see you've put a lot of thought into the API. Nice work, excited to see this engine mature.

CocoonJS integration

Everything I'm doing works great in all the desktop browsers I've tested. But when i load up a Test Jaws game with a test game state inside of the CocoonJS launcher (for mobile devices) , I get the error below

JSUtilities Exception: TypeError: Result of expression 'asset' [undefined] is not an object. Line: 778 File: 1494923456 Tag: load

This happens whenever i try to make a new jaws.Sprite

I know it's because of the CocoonJS launcher, because it isn't a complete browser. It has a lot stripped out of it. But i was wondering if there was a way to get Jaws completely compatible with CocoonJS? Or if anyone has ran into this problem too?

Parallax.draw doesn't work correctly and is slow.

The Parallax drawing code contains two bugs:

  1. It doesn't work correctly with a vertically scrolling parallax (http://mooses.nl/misc/jaws/bug1/orig/)
  2. It draws way too many sprites when the camera X and/or Y coordinates have a high value.
    (in fact, all sprites between the top-left corner of the game world and the current camera position are drawn!)

I've squashed both bugs in my fork of jaws (see https://github.com/jorisvddonk/jaws/blob/master/src/parallax.js)
Unfortunately, I didn't get around to adding in proper support for options.repeat_x, options.repeat_y and options.scale.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.