Community Cookbook

6,846 views
Skip to first unread message

TheGrak

unread,
Jul 30, 2012, 8:48:31 PM7/30/12
to craf...@googlegroups.com
I'd like to start a community cookbook, where everyone can contribute code that they have found to be useful in some way.
In return, everyone can study the code and together we can build a cookbook for Crafty. 

For consistency, I'd like the examples to follow a basic pattern:
A description of what your code does, any wisdom you gained from using it, and a link to a jsfiddle illustrating your code.  I will start:





Description:
This snippet will initialize the Crafty viewport to fullscreen, up to a maximum size you specify.
I've set the maximum width at 960 in the example. 
I've found that the iPhone 3g, 3gs, and 4g will trigger full screen mode, implying a lower resolution than 960 pixels wide (as of 7/2012).
I've also discovered that the Samsung Note will trigger full screen mode as well.

Fiddle:
http://jsfiddle.net/ysDtQ/1/






I will try to keep the momentum going by posting snippets daily. 
Feel free to contribute examples, but I'd prefer to keep the questions regarding examples in a new thread specific to that question.

Thanks,
//garrick

TheGrak

unread,
Jul 30, 2012, 9:07:23 PM7/30/12
to craf...@googlegroups.com
Description:
This fiddle will load a song (.mp3 or .ogg) to play on repeat forever.
Due to .wav file size and lack of compression, I left out the option for playing a .wav file. 

Fiddle:
http://jsfiddle.net/VfEyL/




(Please don't assume anything is too basic to post a fiddle about.)

TheGrak

unread,
Jul 30, 2012, 9:20:19 PM7/30/12
to craf...@googlegroups.com
Description:
This fiddle illustrates how to get the x,y position of where the user has clicked, or touched.
The fiddle also shows how to change a text component's .text value based on user input (click position).

Fiddle:
http://jsfiddle.net/VXyd6/

TheGrak

unread,
Jul 30, 2012, 9:33:48 PM7/30/12
to craf...@googlegroups.com
Description:
This fiddle illustrates one way to apply keyboard events to a Crafty entity.
Pressing the up, down, left, right keys will move the player sprite around by 16 pixels.
Fiddle 1 was written to support held down keys.  Fiddle 2 was written to support single key presses.

Fiddle 1:
http://jsfiddle.net/WzpFH/

Fiddle 2:
http://jsfiddle.net/yDCca/

ABev

unread,
Jul 31, 2012, 10:43:22 AM7/31/12
to craf...@googlegroups.com

This is a great idea!  I don't have much to contribute yet, but I really appreciate your contribution.

João Henrique Pimentel

unread,
Jul 31, 2012, 1:20:02 PM7/31/12
to craf...@googlegroups.com
Hi, your comment made me check the source code, because I had assumed that Crafty would load ONLY the best option for the current browser.
However, it seems that it loads the same audio in ALL formats the browser is able to run, is that it?

Matt Petrovic

unread,
Jul 31, 2012, 1:24:22 PM7/31/12
to craf...@googlegroups.com
Make a new thread for that. We should keep a thread like this on topic.

Pic

unread,
Jul 31, 2012, 3:16:11 PM7/31/12
to craf...@googlegroups.com
I just started playing with Crafty and found this simple hack, please tell me if it's any good or correct.

Description: Crafty let's you use components to specify different things, like Color. But what if you want your entity to have two colors?
This fiddle will show you how to create a component which lets you create two rectangles with different colors as a single entity.

http://jsfiddle.net/Jasz/gxuA2/

Søren Bramer Schmidt

unread,
Jul 31, 2012, 3:44:38 PM7/31/12
to craf...@googlegroups.com
You should explore the use of .attach to make sure the two rectangles follows the main entity when moved. See this updated version   http://jsfiddle.net/gxuA2/1/ 

TheGrak

unread,
Jul 31, 2012, 8:49:13 PM7/31/12
to craf...@googlegroups.com
Description:
This fiddle shows one way of creating and managing an "in game" menu. 
In this fiddle, the player can be moved around using the up, down, left, & right arrow keys. 
The menu will be created above the player, and will close if the player clicks on anything besides the menu.
The menu system can be extended to any number of menus with any number of buttons, images, text, etc...
And yes, you could also build a website instead of a menu using this approach.

I learned that creating menu systems using Crafty components requires that you keep track of them, so you can destroy() them later on.
Destroying() an entity essentially tells crafty to tell javascript to tell the garbage collector that the space allocated in memory to contain that entity can be freed/used for other purposes.
If you don't destroy crafty entities when you are done with them, they will exist in memory until they go out of scope.  If they never go out of scope, your code will leak memory.
It is interesting to note that you cannot force garbage collection in javascript (http://stackoverflow.com/questions/3034179/javascript-force-gc-collection-forcefully-free-object).

Fiddle:
http://jsfiddle.net/ejRpE/





Let's see what ya got! :)




TheGrak

unread,
Aug 1, 2012, 8:56:08 PM8/1/12
to craf...@googlegroups.com
Description:
This fiddle illustrates one way of loading a large (1280x1280) background image for a game world.
The player can be moved around using the up, down, left, and right arrow keys, in increments of 32 pixels.
The Crafty viewport follows the player, and the stage is 500x500 pixels.  There is no collision detection, but you could extend this to use Crafty's collision detection.
The fiddle requests sprites from the OpenGameArt.org website, which is a great resource for sprites to use in your own game.

I've adopted this approach for a game that I am working on.  I found that having a small viewport with a scrolling background works well on mobile devices, due to limited screen space.

Fiddle:
http://jsfiddle.net/FpNaF/

TheGrak

unread,
Aug 1, 2012, 9:31:19 PM8/1/12
to craf...@googlegroups.com
Description:
This fiddle illustrates the similarities between a Javascript Class and a Crafty Component, and provides examples of both side by side.
This fiddle also illustrates accessing the properties and methods of both a class and a component.

Fiddle:
http://jsfiddle.net/s2eZ9/

TheGrak

unread,
Aug 2, 2012, 9:07:03 PM8/2/12
to craf...@googlegroups.com
Description:
These fiddles illustrate object inheritance in javascript and in Crafty. 
Fiddle 1 shows object inheritance using pure javascript, wrapped in a Crafty scene.
Fiddle 2 shoes object inheritance using Crafty components, overwriting previous methods/variables, or appending new ones.

If you would like to learn more about classes/objects and inheritance/extending objects, here are some resources to get you started:
http://www.phpied.com/3-ways-to-define-a-javascript-class/
http://www.webmonkey.com/2010/02/make_oop_classes_in_javascript/
http://ejohn.org/blog/simple-javascript-inheritance/

Fiddle 1:
http://jsfiddle.net/Mvyms/

Fiddle 2:
http://jsfiddle.net/Ernvq/

Prabhakar Peri

unread,
Aug 3, 2012, 1:50:21 AM8/3/12
to craf...@googlegroups.com
Hi,
That is a good motive.
Regarding Note triggering full screen mode, I guess, it is the intended functionality. Following code is seen in Crafty to identify the device. For all these devices, it will trigger fullscreen mode.
mobile = /iPad|iPod|iPhone|Android|webOS|IEMobile/i.exec(ua); [ua is the user agent]

G

unread,
Aug 3, 2012, 11:21:24 AM8/3/12
to craf...@googlegroups.com

Except in the example I do not use Crafty.mobile.  The fullscreen is triggered because the Note's browser resolution is less than 960 pixels. The screen resolution is higher than 960, but the browser's is not.

Matt Petrovic

unread,
Aug 3, 2012, 11:32:02 AM8/3/12
to craf...@googlegroups.com
What did I just say?

G

unread,
Aug 3, 2012, 2:23:07 PM8/3/12
to craf...@googlegroups.com

Prabhakar - start another thread about your questions regarding full screen mode and crafty.mobile. Thanks!

StephenZ

unread,
Aug 4, 2012, 12:20:08 AM8/4/12
to craf...@googlegroups.com
Description:

This example demonstrates one technique for implementing cross-browser mousewheel event handling. In the example, the mouse wheel can be used to zoom in and out of the scene, and works the same in all PC browsers (mobile not tested). It leverages several other fiddles--thanks to the original authors!

I learned a lot putting this together (new to Crafty), but the biggest lessons were:
  • Firefox does not implement the mousewheel DOM 3 level event according to WC3 standard.
  • Crafty doesn't work with a concept of "distance" for the camera (from the scene), so you can't increment/decrement the zoom level--instead, you literally apply a scalar to the amount of the world it views.
  • In the latest dev (and 0.5.1), Canvas rendering seems unstable. If you change the DOM component of worldBkg to "Canvas", it will corrupt the viewport after a few zooms.
Fiddle:

TheGrak

unread,
Aug 4, 2012, 2:04:58 PM8/4/12
to craf...@googlegroups.com
@ StephenZ: Very nice!  Thanks for contributing!  Keep em' coming!  :)




FUNCTIONS AS OBJECTS

Description:

This fiddle explores the use of functions as objects, essentially allowing a programmer to add properties to a function,
treating it like an object.  I learned that all functions are actually objects in javascript.

Fiddle:
http://jsfiddle.net/Px4mx/


Description:
This fiddle illustrates how to use functions as objects within the context of a Crafty component.
This allows a programmer to add properties to a method, treating it like an object.

Fiddle:
http://jsfiddle.net/a9aQG/

TheGrak

unread,
Aug 4, 2012, 2:06:28 PM8/4/12
to craf...@googlegroups.com
DEFINING LAZY FUNCTIONS

Description:
This fiddle illustrates an example of using lazy function definitions.  There are two main reasons for wanting to
defer defining functions until a later time:
1. Resources required for a function to be fully defined are not available until the page fully loads or until a
user-driven event (for example, determining page scroll).
2. The resources created by defining the function are particularly taxing and may not even be needed (for example
attaching event handlers).
The Lazy Function Definition solves these problems by defining resources upon the first invocation of the function
and then redefining itself so that they are not recreated during subsequent calls. All resources are stored via
closure so they remain available to the inner function (which becomes the new definition for the outer function).

Resources:
http://peter.michaux.ca/articles/lazy-function-definition-pattern
http://2007-2010.lovemikeg.com/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/

Fiddle:
http://jsfiddle.net/KA2a6/


Description:
This fiddle illustrates using lazy function definitions in the context of a Crafty component.

Fiddle:
http://jsfiddle.net/zQgUd/



TheGrak

unread,
Aug 4, 2012, 2:08:23 PM8/4/12
to craf...@googlegroups.com
A TOP DOWN SINGLE PLAYER EXAMPLE
Description:

This fiddle illustrates an example of a topdown single person game, where the user can input the location
that the player should move to using a mouse click or touch event.  The example uses a gameCell javascript
object to hold a pointer to the player (or other players/enemies) and also to determine if the gameCell is
walkable or solid (implying the gameCell cannot be crossed).  The user clicks to set a waypoint for the player,
at which point the player begins moving towards the waypoint taking into account walls and other occupied
gameCells.  This example could be expanded to support enemies, battles, allies, dialog, trade, quests, etc...

Fiddle:
http://jsfiddle.net/eJnDt/


A TOP DOWN TEAM AI EXAMPLE
Description:
This fiddle builds upon the previous one, showing how to create two teams that each pursue a common target.
The fiddle uses red and blue squares, but they could just as easily be zombies or monsters.

Fiddle:
http://jsfiddle.net/sRNyY/



Ask any questions you have in a separate thread.
I, or someone else will be happy to answer them.  Thanks!  :)

TheGrak

unread,
Aug 12, 2012, 12:22:42 AM8/12/12
to craf...@googlegroups.com
A JUKEBOX EXAMPLE
Description:

This code snippet shows how to play several songs in a row.  The "Jukebox" can repeat the songs or stop after playing all the songs once.
This code snippet also shows how to add event listeners to the Crafty.audio javascript object.
This code snippet will not run in jsFiddle (the error returned is: "Crafty.audio.sounds is undefined" - http://jsfiddle.net/2zEDR/).
This code snippet will run locally and on a web server.

Snippet:
//Jukebox
        var trackCounter = 1
        var nextTrack = function()
        {
            if (trackCounter == 4){trackCounter = 1}  //if we hit the last track, reset to the first
            var themeToPlay = "theme"+trackCounter
            //play once
            Crafty.audio.play(themeToPlay, 1);
            trackCounter += 1;
        }
        //add the theme songs to the music quene, add event listener
        Crafty.audio.add("theme1", [ "audio/oldTexasTheme.ogg" ]);
        Crafty.audio.sounds.theme1.obj.addEventListener("ended", function(){  nextTrack();  },true);
        //2
        Crafty.audio.add("theme2", [ "audio/dubDrone.ogg" ]);
        Crafty.audio.sounds.theme2.obj.addEventListener("ended", function(){  nextTrack();  },true);
        //3
        Crafty.audio.add("theme3", [ "audio/nothingSpecial.ogg"    ]);
        Crafty.audio.sounds.theme3.obj.addEventListener("ended", function(){  nextTrack();  },true);
        //Play the songs
        nextTrack();


Thanks,
Garrick

TheGrak

unread,
Sep 8, 2012, 8:04:14 AM9/8/12
to craf...@googlegroups.com


Description:
This fiddle shows how to have a Crafty entity follow a hidden mouse cursor.

Fiddle:
http://jsfiddle.net/QmPDp/

Thanks,
Garrick

TheGrak

unread,
Sep 8, 2012, 8:21:57 AM9/8/12
to craf...@googlegroups.com

Description:
This fiddle shows how to properly initialize the Crafty.viewport to fullscreen or up to a maximum size.
The previous example (cookbook post #1) did not take into account Crafty.mobile and is therefore wrong.

Fiddle:
http://jsfiddle.net/8G2ZF/

Thanks,
Garrick

jplur

unread,
Sep 8, 2012, 1:09:44 PM9/8/12
to craf...@googlegroups.com
Description:
A Vector2D class, with use in a Velocity and Gravity component

Fiddle:

TheGrak

unread,
Sep 18, 2012, 1:19:33 PM9/18/12
to craf...@googlegroups.com
Description:
These pairs of fiddles demonstrate one method of determining the 'mean' or 'average' running time of any given javascript/crafty code.
The 2nd fiddle uses a function that accepts a string of javascript code to be timed (this function does not use eval() ).

Fiddle 1:
http://jsfiddle.net/nGhaK/

Fiddle 2:
http://jsfiddle.net/YZSJ8/



@jplur:  Awesome fiddle!  Thanks for contributing!  :)

Gabriel Ziden Ziden

unread,
Sep 24, 2012, 9:15:19 AM9/24/12
to craf...@googlegroups.com
Hello there.

  Im new to crafty, just started friday, and i liked craftyjs pretty much (except it kinda lags alot on my galaxyS2).

  I dont have a snippet, i have a simple Demo witch can help people do a tactical tiled non-isometric game (witch is my project). Source is all divided up into parts, easy reading i guess.

  It still have some issues, like every single tile is a Entity, so i belive its one of the main reasons the game is a littlebit laggy.Every tile behaves the same, so it could use a 'compound' of entityes if thats possible. Im using Canvas instead of Dom because DOM the game gets even a little laggyer. It works fine on Firefox/Chrome/iphone and ipad Safari, however it lags like shit in my galaxys2(Chrome or Opera) and it have a little input delay in Safari.

  This is my little project im still working on it. If you want to make it a demo for craftyjs it would be cool, but i still to improve its performance, specially the tile system and the pathfinding algorithm, the search for 'where the character can possibly move' is nonsense heavy since i pathfind every possible tile. Need to improve that later on to search all tiles with A* with the maximum number of steps < the unit max steps.

  Now im tryng to make the GUI ( hud ) of this game, but i just have NO CLUE on how to start since craftyjs has no Hud support. Any ideas / suggestions would be pleased (mainly, if someone knows how to build a HUD !!! haha)

  Thanks :) Hope this helps some tactical games lovers haha.

TheGrak

unread,
Sep 24, 2012, 11:49:17 AM9/24/12
to craf...@googlegroups.com

Thanks for joining the Crafty community.  A couple of quick things:

1.  Ask questions in a separate thread
2.  This thread is reserved for snippets and fiddles, if you don't have one, don't post here - we're trying to build a community cookbook, not promote our games.

If you ask your question in a separate thread, I will be happy to give you at least 2 ways of constructing and managing an in-game HUD (although a HUD example is contained within this thread).

Thanks,
//ThGrk


Gabriel Ziden Ziden

unread,
Sep 24, 2012, 12:44:40 PM9/24/12
to craf...@googlegroups.com
Thanks alot for your attention ! This was not an intention to promote any game, sorry this is not a game its just a 'study' im new to javascript and to javascript gaming, this is my first try i wished to contribute with crafty with it since it was responsible for making it possible in short time.

  Ive posted a thread about HUDs yestarday tho, and im still googlin it about it and i cant find an easy answer. No one replyed the other thread tho.

 Again, thanks for the attention, sorry for the 'non jsfiddle' format, i have little time to code (maybe because im @ work fulltime, lol) so i didnt wanted the work to make a snigle script, images etc to make it work on jdfiddle. But my intention was not promoting the game whatsoever but giving out something people could possibly want, witch is a tactical battlefield similar to FFT. Ill make it a jdfiddle later on if i have some extra time for the community.

  Thanks !

TheGrak

unread,
Sep 25, 2012, 1:55:21 PM9/25/12
to craf...@googlegroups.com
A SPRITE MENU EXAMPLE

Description:

This fiddle shows another way of creating an in-game menu, this time based on an image divided into sprites.
This fiddle also shows how to redefine a sprite's pixel co-ordinates using the .sprite method.
This fiddle also shows how to use the 'mouseOver' and 'mouseOut' events to change a sprite entities properties (in this case, the alpha value).

Fiddle:
http://jsfiddle.net/kg2Xp/

Thanks,
//ThGrk

TheGrak

unread,
Sep 25, 2012, 2:08:59 PM9/25/12
to craf...@googlegroups.com
A HUD EXAMPLE

Description:

This fiddle shows an efficient way of creating a HUD that follows a crafty entity.
There are 51 text components attached to one sprite.  The sprite does an indefinite semi-random walk.
The ms per frame are displayed above the crafty entity.

Fiddle:
http://jsfiddle.net/YZZBb/

TheGrak

unread,
Oct 19, 2012, 11:24:34 AM10/19/12
to craf...@googlegroups.com
Here are updated fiddles that work with Safari (if one of the above/previous fiddles doesn't work, it's because there is a console.clear() command that Safari doesn't support) :

 Team AI example:

Sprite Menu example:

HUD example w/ ms per frame:


Note: any (OSX) Safari developers will need to enable Developer Mode to view console.logs & errors:
 - from the Preferences > Advanced > Click 'Show Develop menu in bar'
 - then from Safari's menu, choose Develop > Show Error Console

//ThGrk


P.S.  I finally got a powerful Mac and was testing the community fiddles across OSX/Ubuntu/WinXP+7.  Seems the only changes needed were removing the console.clear() commands.
P.P.S  I'm also working on some object pooling examples for Crafty, will have them ready soon.


Message has been deleted
Message has been deleted

Bills

unread,
Oct 20, 2012, 2:55:56 AM10/20/12
to craf...@googlegroups.com

João Henrique Pimentel

unread,
Dec 17, 2012, 11:10:17 AM12/17/12
to craf...@googlegroups.com
Description: This snippet creates a component that toggles visibility, giving a "blink" effect. I realized that by encapsulating behaviors in separate components makes it easier to reuse this behavior in different entities. Also, I found out that we can use Crafty.frame() to simulate periodic events.

Bills

unread,
Jan 4, 2013, 6:40:38 AM1/4/13
to craf...@googlegroups.com
Description: this fiddle shows how generate random colors.

Bills

unread,
Jan 6, 2013, 9:41:34 AM1/6/13
to craf...@googlegroups.com


Description: a simple geometric shape component.


Deep R. Ode

unread,
May 16, 2013, 12:44:10 PM5/16/13
to craf...@googlegroups.com
Thanks a lot!

On Thursday, August 2, 2012 6:26:08 AM UTC+5:30, TheGrak wrote:
Description:
This fiddle illustrates one way of loading a large (1280x1280) background image for a game world.
The player can be moved around using the up, down, left, and right arrow keys, in increments of 32 pixels.
The Crafty viewport follows the player, and the stage is 500x500 pixels.  There is no collision detection, but you could extend this to use Crafty's collision detection.
The fiddle requests sprites from the OpenGameArt.org website, which is a great resource for sprites to use in your own game.

I've adopted this approach for a game that I am working on.  I found that having a small viewport with a scrolling background works well on mobile devices, due to limited screen space.

Fiddle:
http://jsfiddle.net/FpNaF/

Lab Monkey

unread,
May 24, 2013, 10:06:20 AM5/24/13
to craf...@googlegroups.com
Description:
This snippet will create a fade transition between two scenes. It fades to black, loads the new scene, then fades back to transparent.  It seems to work on the limited testing I have done. Just thought I would throw it out there in case anyone else needs something like this while this feature is (hopefully) being developed.

Originally proposed by RedHickory Creative in https://groups.google.com/d/msg/craftyjs/hjlRb7hYbYg/Tw_kQzl4cIAJ

Snippet:
function load_scene(scene, duration) {
    Crafty.e("2D, Canvas, Tween, Color")
        .attr({alpha:0.0, x:0, y:0, w:800, h:600})
        .color("#000000")
        .tween({alpha: 1.0}, duration)
        .bind("TweenEnd", function() {
            Crafty.scene(scene);
            Crafty.e("2D, Canvas, Tween, Color")
                .attr({alpha:1.0, x:0, y:0, w:800, h:600})
                .color("#000000")
                .tween({alpha: 0.0}, duration);
        });
}

Yann LEFLOUR

unread,
May 29, 2013, 6:01:35 AM5/29/13
to craf...@googlegroups.com, somelo...@gmail.com
I don't know if there are still many people working on Crafty but I started creating a tool for Brett Victor style debugging:

It allows recording player inputs to be able to then go back and worth through time and change their behavior at a precise moment if needed. It is independent of the entities in the scene.

More information on the Wiki page. The repository contains the demo and the module is in js/craftyExtend.js

Steve

unread,
Jun 4, 2013, 4:42:26 PM6/4/13
to craf...@googlegroups.com
Description: Put a jquery-ui slider input into a Crafty game.

The idea is that a crafty DOM element is just a wrapper around an HTML div, and jquery-ui is capable of taking any div of your choice and turning it into a slider input.

I guess this is more generally an example of putting non-crafty html / css / javascript stuff into a crafty game.

jsfiddle: http://jsfiddle.net/jKKTc/
Message has been deleted

Alexandre Rousseau

unread,
Aug 30, 2013, 5:04:09 PM8/30/13
to craf...@googlegroups.com
Description:
Create a gradient-filled viewport-sized DOM entity

Message has been deleted

Steve

unread,
Oct 7, 2013, 3:07:17 PM10/7/13
to craf...@googlegroups.com, somelo...@gmail.com
Description: When you click and drag, it makes a rectangular box, like on a computer desktop.

Notes: I used canvas, not DOM, although it could be modified to use DOM. Warning: I haven't tested this code on touchscreens, just with a mouse.

JSfiddle: http://jsfiddle.net/sbyrnes321/g2gdB/

~~Steve

On Monday, July 30, 2012 8:48:31 PM UTC-4, TheGrak wrote:
I'd like to start a community cookbook, where everyone can contribute code that they have found to be useful in some way.
In return, everyone can study the code and together we can build a cookbook for Crafty. 

For consistency, I'd like the examples to follow a basic pattern:
A description of what your code does, any wisdom you gained from using it, and a link to a jsfiddle illustrating your code.  I will start:





Description:
This snippet will initialize the Crafty viewport to fullscreen, up to a maximum size you specify.
I've set the maximum width at 960 in the example. 
I've found that the iPhone 3g, 3gs, and 4g will trigger full screen mode, implying a lower resolution than 960 pixels wide (as of 7/2012).
I've also discovered that the Samsung Note will trigger full screen mode as well.

Fiddle:
http://jsfiddle.net/ysDtQ/1/






I will try to keep the momentum going by posting snippets daily. 
Feel free to contribute examples, but I'd prefer to keep the questions regarding examples in a new thread specific to that question.

Thanks,
//garrick

Bills

unread,
Nov 16, 2013, 7:54:25 PM11/16/13
to craf...@googlegroups.com, somelo...@gmail.com
Description:
Simple example showing how uses Crafty and PhysicsJS together.

CodePen:
http://codepen.io/anon/pen/gFwci

Ctibor Laky

unread,
Jan 13, 2014, 8:36:11 AM1/13/14
to craf...@googlegroups.com, somelo...@gmail.com
Title: Collision component is required on both objects to work properly
 
Description:
Fiddle1 shows example when player has collision component and obstacle doesnt. Obstacle is working, so player cannot go trough BUT it doesnt take  player polygon but the sprite into collision.

So if you want polygon to start working with this obstacle, obstacle must have collision component included, you can see it in fiddle2 
 
Fiddle1:
http://jsfiddle.net/qY5k2/1/
 
Fiddle2:
http://jsfiddle.net/qY5k2/2/
 

Ashiq A.

unread,
Jan 17, 2014, 5:40:52 PM1/17/14
to craf...@googlegroups.com, somelo...@gmail.com
Hi,

As the cookbook is still a work in progress, is there any way (other than reading this thread) to see the content?

What if this was, say, a Wikia wiki instead? I think that would lend itself to better searching.

Steve Byrnes

unread,
Jan 20, 2014, 7:58:22 PM1/20/14
to craf...@googlegroups.com
If you want a wiki, don't make a new one, use the one we already have ...


I agree that the thread is too hard to search / scroll through. :-D --Steve


--
You received this message because you are subscribed to the Google Groups "Crafty" group.
To unsubscribe from this group and stop receiving emails from it, send an email to craftyjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Sami Sami

unread,
Jun 4, 2014, 12:29:00 PM6/4/14
to craf...@googlegroups.com
Hey!

I love this Cookbook, and agree it should be on the wiki.

Does anyone have any objection to me transferring things over to the GitHub wiki?

--
Sami

Ashiq A.

unread,
Jun 4, 2014, 12:36:13 PM6/4/14
to craf...@googlegroups.com
No objection, but a recommendation: if you use the GitHub wiki feature, which I assume you are referring to, please also create a gh-pages branch (GitHub hosted, Jekyll blog); there's an automatic page generator, and if your readme.md file is like a "table of contents" with links to wiki pages, that would be super amazing.

--Ashiq



For more options, visit https://groups.google.com/d/optout.

Sami

unread,
Jun 4, 2014, 12:38:43 PM6/4/14
to craf...@googlegroups.com
Hmm not quite sure what you mean about the gh-pages branch?


--
You received this message because you are subscribed to a topic in the Google Groups "Crafty" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/craftyjs/qtUQaDzVYAM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to craftyjs+u...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Sami

Ashiq A.

unread,
Jun 4, 2014, 12:41:47 PM6/4/14
to craf...@googlegroups.com
Sorry, I assume too much :)

Here's the introduction/summary from GitHub: https://pages.github.com/

The TLDR is "if you have a gh-pages branch, anything there is automatically web-serv'd to the world." 

On any existing repo, go to Settings > GitHub Pages section > Automatic Page Generator. Go through the wizard, click the link (http://...github.io/...) and you'll see what I mean.

That's the "techncial" part. What I'm suggesting "strategically" is:

- Use a wiki for 99% of the content
- Have readme.md contain a bunch of wiki links
- Use GitHub Pages to host it, so you get a nice page for your table of contents

--Ashiq

Message has been deleted
Message has been deleted

Sami Sami

unread,
Jun 9, 2014, 10:17:45 AM6/9/14
to craf...@googlegroups.com
Ahh that does make sense!

I just found this: http://craftyjs.com/cookbook/

Would we rather use a new gh-pages or expand on that?

Dimka Witer

unread,
Aug 1, 2016, 4:06:05 AM8/1/16
to Crafty, somelo...@gmail.com
Description:
Canvas odometer by Mark Crossley, adapted for Crafty

Fiddle:

Matthijs Groen

unread,
Aug 25, 2016, 7:16:04 PM8/25/16
to Crafty, somelo...@gmail.com
https://github.com/matthijsgroen/game-play/blob/master/app/scripts/components/utils/scalable.coffee

(You need to port the coffeescript to javascript though)

This adds a property 'scale' to the entity
1.0 is the value of the original size, and you can size the whole entity up and down by adjusting this float.

It automatically scales all attached children (useful for entities build from multiple), and it also
scales the collision map

Since is a property, entity.scale = 0.8 also works, and you can therefor also use it in tweens for fluent scaling



Nathan Jackson

unread,
Dec 3, 2016, 11:55:32 AM12/3/16
to Crafty, somelo...@gmail.com, njac...@alumni.uwo.ca



Description:
 
Code to get a player sprite animated and moving (it's ugly) The sprite map image is attached.

 
Cobbled together from examples around the web, here is a simple and effective (and probably incorrect) way to get a sprite animated and moving with controls. Make no mistake, it's ugly in every respect from, but it represents a javascript learning experience and it works!
 
Also, I scoured the web for code to deconstruct and found very little. I can't believe I didn't just check this forum for code examples, it would have made this a lot easier.

 Without further ado:

Crafty.init(500,300, document.getElementById('game'));

window.onload = function() {
Crafty.init(400, 400);
};

Crafty.sprite(32, 'ash2.png', {
spr_player: [0, 0]}, 0, 0);
Crafty.c('Player',
{
init: function() {
this.requires('2D, Canvas, Fourway, spr_player, SpriteAnimation')
.fourway(50);
}
}
);

var player = Crafty.e('Player')
.attr({x:0, y:0, h:32, w: 32})
.reel("walkingDown", 1000, [[1, 0], [0, 0], [2, 0], [0, 0]])
.reel("walkingRight", 1000, [[4, 0], [3, 0], [5, 0], [3, 0]])
.reel("walkingUp", 1000, [[7, 0], [6, 0], [8, 0], [6, 0]])
.reel("walkingLeft", 1000, [[10, 0], [9, 0], [11, 0], [9, 0]]);
player.bind('KeyDown', function() 
{
if(this.isDown("LEFT_ARROW")) {
document.getElementById('tags').innerHTML = "left";
if(!this.isPlaying("walkingLeft"))
this.pauseAnimation().animate("walkingLeft", -1);
} else if(this.isDown("RIGHT_ARROW")) {
document.getElementById('tags').innerHTML = "right";
if(!this.isPlaying("walkingRight"))
this.pauseAnimation().animate("walkingRight", -1);
} else if(this.isDown("UP_ARROW")) {
document.getElementById('tags').innerHTML = "up";
if(!this.isPlaying("walkingUp"))
this.pauseAnimation().animate("walkingUp", -1);
} else if(this.isDown("DOWN_ARROW")) {
document.getElementById('tags').innerHTML = "down";
if(!this.isPlaying("walkingDown"))
this.pauseAnimation().animate("walkingDown", -1);
}
}).bind("KeyUp", function(e) 
{
this.pauseAnimation();
});

Nathan Jackson

unread,
Dec 6, 2016, 11:43:06 AM12/6/16
to Crafty, somelo...@gmail.com
PlayerCharacter Simple Collision

 Hi all,

This code will stop the player from moving onto 'solid' objects:

Crafty.c('PlayerCharacter',
{
init: function()
{
this.requires('MovingEntity, Fourway, Living, Persist')
.checkHits('Solid')
.origin('center').collision(new Crafty.polygon(6, 18, 24, 18, 24, 32, 6, 32)) // creates a custom polygon around the sprite, it uses x,y pairs like: (x1, y1, x2, y2, x3, y3)
.bind('Moved', function(from1)  // from1 is an object that has the info about where the character tries to move from
                                                                    // if the character moves on the x-axis only, then from1.axis will equal 'x' and oldValue will equal where the character                                                                     // was when they started the move.
                                                                    // If the character moves on both axis, the function will be called twice, once with from1.axis equalling 'x' and once                                                                       // equalling 'y'
{
if(this.hit('Solid'))
{
if(from1.axis == 'x')
{
this.attr({x: from1.oldValue, y: this.y});
}
if(from1.axis == 'y')
{
this.attr({x: this.x, y: from1.oldValue});
}
};
});
},

});

Nathan Jackson

unread,
Dec 6, 2016, 2:16:08 PM12/6/16
to Crafty, somelo...@gmail.com
Feel free to remove or define "living" and "movingEntity" yourself, it's pretty boilerplate and I'm not sure it's functional (though I don't get any errors). For reference, here's the code:

Crafty.c('MovingEntity',
{
 spriteName
:'',
 
 init
: function()
 
{
 
this.requires('Entity, Collision, SpriteAnimation, Sprite')
 
.collision(new Crafty.polygon(0, 0, 0, 32, 32, 32, 0, 32))
 
.bind('HitOn', this.onHitOn)
 
.bind('HitOff', this.onHitOff)
 
.bind('Moved', this.onMove)
 
;
 
},
 
 onHitOn
: function()
 
{
 
return this;
 
},
 
 onHitOff
: function()
 
{
 
return this;
 
},
 
 onMove
: function()
 
{
 
return this;
 
}
});






Crafty.c('Living',
{
 health
:0,
 
 init
: function()
 
{
 
},
 
 getHealth
: function()
 
{
 
return health;
 
},
 
 modifyHealth
: function(modHealth)
 
{
 
this.health = this.health-modHealth;
 
return this;
 
}
});
 
Reply all
Reply to author
Forward
0 new messages