GithubHelp home page GithubHelp logo

useflashpunk / flashpunk Goto Github PK

View Code? Open in Web Editor NEW
386.0 50.0 135.0 1.98 MB

A free ActionScript 3 library designed for developing 2D Flash games. It provides you with a fast, clean framework to prototype and develop your games in. This means that most of the dirty work (timestep, animation, input, and collision to name a few) is already coded for you and ready to go, giving you more time and energy to concentrate on the design and testing of your game.

Home Page: http://useflashpunk.net

License: MIT License

ActionScript 100.00%

flashpunk's Introduction

FlashPunk

Create games. Easy.

FlashPunk is a free ActionScript 3 library designed for developing 2D Flash games. It provides you with a fast, clean framework to prototype and develop your games in. This means that most of the dirty work is already done, letting you concentrate on the design and testing of your game.

Get FlashPunk!

The total package.

Not only is FlashPunk absolutely free, it also contains everything you'll need to make the game you want. From its robust and dead-simple sprite-based graphics handling to its powerful live debugger, you won't need a team of berets and neckbeards to make your game come to life.

Features

Graphics

Helper classes for animations, tilemaps, text, backdrops, and more with z-sorted render lists for easy depth management.

// Create a new Image from imported image.
[Embed(source = 'player.png')]
private const PLAYER_IMAGE:Class;
var playerImage:Image = new Image(PLAYER_IMAGE);

Collision

Fast and manageable rectangle, pixel, and grid collision system with a plethora of built-in collision options.

// Check for collision between the player and all enemies.
var touchedEnemy:Entity = player.collide("enemy", player.x, player.y);

Motion

Powerful motion tweening for linear, curved, and path-based movement as well as spritesheet support and image transformation.

// Move an enemy across the screen with a tween, stopping against walls.
enemy.moveBy(5, 0, "wall");

Audio

Sound effect support with volume, panning, and fading/crossfading, complete with one-line sound playback.

// Play a shoot sound.
[Embed(source = 'shoot.mp3')] private const SHOOT:Class;
var shoot:Sfx = new Sfx(SHOOT);
shoot.play();

Particles

Quick and efficient particle effects and emitters allow for beautiful particle systems without slowing things down.

Timesteps

Framerate-independent and fixed-framerate timestep support allow you to decide what mode is best for you and your game.

// Add the frame time to a timer.
timer += FP.elapsed;

Input

Simple keyboard and mouse input state checking makes setting keys and events incredibly easy, yet powerful.

// Call a function when Space is pressed.
if (Input.pressed(Key.Space)) {
  spacebar();
}

Built-in Debugging

Handy console for real-time debugging and information tracking. It even allows moving the camera and inspecting entities while playing!

// Enable the debugger and watch the player's speed.
FP.console.enable();
FP.console.watch(player.speed);

Community

If all this just isn't enough and you absolutely require a team of berets and neckbeards, the FlashPunk Developers community is an incredible resource eager to answer any question you can fathom. Oh, and its free as well.

flashpunk's People

Contributors

abeltoy avatar azrafe7 avatar blckknght avatar chevyray avatar djcsdy avatar draknek avatar duncanbeevers avatar elipsitz avatar erikyuzwa avatar evix7 avatar jacobalbano avatar julsam avatar mangelats avatar mikeevmm avatar mikemgames avatar noonat avatar shinyhappypixels avatar smileyjames avatar svenito avatar sxd1140 avatar zachwlewis avatar

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flashpunk's Issues

Canvas.applyFilter() (Code)

Here's an applyFilter implementation for canvas:

        public function applyFilter(filter:BitmapFilter):void
        {
            for each (var buffer:BitmapData in _buffers)
            {
                buffer.applyFilter(buffer, buffer.rect, FP.zero, filter);
            }
        }

Parenting system

The ability to add one Entity as the child of another, so that when the parent moves it takes the child with it.

Flixel does this in a semi-hacky semi-elegant way that might be worth examining and possibly stealing. The clever part is that it doesn't have local coordinates anywhere, instead it remembers a past position and a current position. When updating an entity, it compares the two and offsets its children by that amount.

Open questions:

  • Do we need to get/set positions of an Entity in both local and world coordinates?
  • Do we need/want to support angular rotations?

The debug console sometimes doesn't scale with the game

Don't right now have code which triggers this, but it's to do with the order in which you call things.

I think the three things that I reorder until it works are:

  • calling Engine constructor
  • setting FP.screen.scale
  • calling FP.console.enable()

Spritemap/TiledSpritemap.add() should allow replacement of animation

Current Behavior: When adding a set of frames to a Spritemap or TiledSpritemap using add() with a name that already exists, it will throw the error "Cannot have multiple animations with the same name."

Suggested Behavior: If the name already exists, Spritemap should treat it as an expected action and overwrite the existing animation with the new one using the same name.

Justification Example: There are times when you will create a class and set a series of animations, say for a default look. This class contains logic that will use the animations with a defined naming convention. A second class extends this class and changes the default animations while leaving the superclass' logic alone. With the current behavior, you are unable to simply use Spritemap.add() to replace the animations.

Risk: Existing code does not attempt to do this, because it would have been changed after throwing the error. Adding this functionality should not require any kind of refactoring for those code bases.

moveTowards moving past target, FP.stepTowards redundancy

This is annoying:

Entity.moveTowards doesn't check whether amount to move is longer than distance, therefor it sometimes jams moving back and forth, when you expect it to stop at the point we are moving towards.

I found a helper under FP called stepTowards, but the stepTowards does not preserve int values for coordinates and is oddly placed under FP

I edited moveTowards to suit my personal needs but it doesn't take in to account collision during coordinate set in final iteration.

public function moveTowards(x:Number, y:Number, amount:Number, solidType:Object = null, sweep:Boolean = false):void
{
    _point.x = x - this.x;
    _point.y = y - this.y;
    if (_point.length <= amount)
    {
        this.x = x;
        this.y = y;
        return;
    }
    _point.normalize(amount);
    moveBy(_point.x, _point.y, solidType, sweep);
}

Get list of entities in rendered order

I've kinda been resisting, but I'm coming to agree that we do need something. So let's just go with the simplest thing: just a method which returns all entities, which can then be filtered if need be.

Implementation: http://pastebin.com/UdAnncL4

So I guess the only thing stopping this is coming up with a damn name for it.

getRenderOrder?
getLayerOrder?

updated Sfx.play() and Sfx.loop() methods

I am currently working on a game which has music that speeds up as the game goes on. I want the player to be able to resume when they die, along with starting the music where it left off.

After poking around the forums, documentation, and IRC I didn't find any good answers, so I made a small tweak to the Sfx class, which might be useful (and perhaps worthy of a commit in the next version?). I didn't want to create my own branch just to change a couple lines of code.

Anyways, I changed line 43 to this (added the "pos" parameter):
Code:
public function play(vol:Number = 1, pan:Number = 0, pos:Number = 0):void

then changed line 52 to this (passing in the pos param):
Code:
_channel = _sound.play(pos, 0, _transform);

And likewise for the loop method.

line 67:
Code:
public function loop(vol:Number = 1, pan:Number = 0, pos:Number = 0):void

line 69:
Code:
play(vol, pan, pos);

Now, I can resume music from the last Sfx.position, by passing it into the play() or loop() methods. Alternatively, it may be useful to add an Sfx.position setter method, which basically calls a stop(), and then a play(), passing in the position to play from.

setHitboxTo doesnt set y properly

In Entity.setHitboxTo

if (o.hasOwnProperty("originY") && !(o is Graphic)) originX = o.originY; else if (o.hasOwnProperty("y")) originX = -o.y;

Should really be:

if (o.hasOwnProperty("originY") && !(o is Graphic)) originY = o.originY; else if (o.hasOwnProperty("y")) originY = -o.y;

Default values of Text class should be named with a "default" prefix

It's much clearer to say this:

Text.defaultSize = 24;
Text.defaultFont = "Comic Sans";
new Text(...);

Than it is to say this:

Text.size = 24;
Text.font = "Comic Sans";
new Text(...);

With the current names, I don't think it properly communicates "setting this only affects Text objects created after this point".

Alas, for backwards compatibility the current variables need to stay around. How ugly would it be to have both a static var defaultSize variable and also a deprecated static function get/set size for all these properties?

Add frontCollidePoint() to World.as

For the community project Punk.UI, a modification is required to the World.as file in order to retrieve the top-most entity at a particular point. However, anyone who adds this to their project's World.as class will have to merge this modification into any new branches of FlashPunk. Since this function is also useful outside of Punk.UI, I think it's a good idea to add this to the current branch to reduce the headache involved with upgrading project libraries.

You can read about it here: https://github.com/RichardMarks/punk.ui/wiki/Additional-function-on-World

Rolpege's (at least I assume it's his) code cut-and-pasted from the above link:

/**
 * Returns the Entity at front which collides with the point.
 * @param   x       X position
 * @param   y       Y position
 * @return The Entity at front which collides with the point, or null if not found.
 */
public function frontCollidePoint(x:Number, y:Number):Entity
{
    var e:Entity,
    i:int = 0,
    l:int = _layerList.length;
    do
    {
        e = _renderFirst[_layerList[i]];
        while (e)
        {
            if(e.collidePoint(e.x, e.y, x, y)) return e;
            e = e._renderNext
        }
        if(i > l) break;
    }
    while(++i);
        return null;
}

Update Sequence

it is possible to have a function like bringToFront / sendToBack for the updateFirst, updateNext sequence? Because some entity would want to update in advance of other entities. It is particularly useful for building UI where some input would have higher priority when being handled.

Blendmode Image stuck

When you apply a Blendmode to a graphic element the image resulted stuck. Also, since the frame that the Blendmode is applied, the image position is always x = FP.camera.x and y = FP.camera.y even if you move the camera. The problem seems to be present in the newest release, I've tried an older release and the same code worked fine.

Tilemap line function is slow (faster version provided)

Here's a faster version, based on Draw.line:

        /**
         * Draws a line of tiles
         *  
         * @param   x1      The x coordinate to start
         * @param   y1      The y coordinate to start
         * @param   x2      The x coordinate to end
         * @param   y2      The y coordinate to end
         * @param   id      The tiles id to draw
         * 
         */     
        public function line(x1:int, y1:int, x2:int, y2:int, id:int):void
        {
            if(usePositions)
            {
                x1 /= _tile.width;
                y1 /= _tile.height;
                x2 /= _tile.width;
                y2 /= _tile.height;
            }

            x1 %= _columns;
            y1 %= _rows;
            x2 %= _columns;
            y2 %= _rows;

            // get the drawing difference
            var X:Number = Math.abs(x2 - x1),
                Y:Number = Math.abs(y2 - y1),
                xx:int, yy:int;

            // draw a single pixel
            if (X == 0)
            {
                if (Y == 0)
                {
                    setTile(x1, y1, id);
                    return;
                }
                // draw a straight vertical line
                yy = y2 > y1 ? 1 : -1;
                while (y1 != y2)
                {
                    setTile(x1, y1, id);
                    y1 += yy;
                }
                setTile(x2, y2, id);
                return;
            }

            if (Y == 0)
            {
                // draw a straight horizontal line
                xx = x2 > x1 ? 1 : -1;
                while (x1 != x2)
                {
                    setTile(x1, y1, id);
                    x1 += xx;
                }
                setTile(x2, y2, id);
                return;
            }

            xx = x2 > x1 ? 1 : -1;
            yy = y2 > y1 ? 1 : -1;
            var c:Number = 0,
                slope:Number;

            if (X > Y)
            {
                slope = Y / X;
                c = .5;
                while (x1 != x2)
                {
                    setTile(x1, y1, id);
                    x1 += xx;
                    c += slope;
                    if (c >= 1)
                    {
                        y1 += yy;
                        c -= 1;
                    }
                }
                setTile(x2, y2, id);
            }
            else
            {
                slope = X / Y;
                c = .5;
                while (y1 != y2)
                {
                    setTile(x1, y1, id);
                    y1 += yy;
                    c += slope;
                    if (c >= 1)
                    {
                        x1 += xx;
                        c -= 1;
                    }
                }
                setTile(x2, y2, id);
            }
        }

Multiple layers per entity

This is a tricky one. Some entities want to render themselves partly above and partly below something else.

We can't just move the layer property to be per-Graphic because we need to keep the very useful ability to override Entity.render().

One suggestion is to implement a parenting system. Then you have a simple-ish workaround: add a separate Entity as a child, and give that Entity a different layer and graphic.

Remove the usePositions property of Grid and Tilemap

It makes the code more complicated and is not something you want to have a per-object setting for.

Instead, we should have a usePixels parameter on certain (not all) methods.

This will be a breaking change, but most people don't use usePositions so we might be okay. Will wait until there's a release pending which looks likely to break other things too.

Spritemap animation definitions should use time-per-frame instead of frames-per-second

If you use time-per-frame, it makes sense to extend it to have per-frame timing (e.g. first frame is shown for 0.5s, second frame for 0.1s, third frame for 0.5s). Doing anything like that is just confusing with fps values.

Time-per-frame also makes a lot more sense when the units of time are in frames rather than seconds ("show for 4 frames" is much more intuitive than "animate at 0.25 frames-per-frame").

Unfortunately I don't know how we can nicely change this without breaking existing code. :( That is more important than changing this.

Make Text class more flexible

There are many properties on TextField and TextFormat that aren't directly accessible on the Text class. It would be good to have a way of interacting with those wrapped objects so that you don't have to hack Text.as to make use of them.

I'm envisaging a function like setTextProperty(name:String, value:*) but possibly there's a better name.

It would see if name is a property of the internal TextField or TextFormat object and update the appropriate one. I assume there is no property which is on both.

Allow changing the unit of time separately to the timestep mode

Currently, times are in seconds if using variable timesteps or in frames if using fixed timesteps.

This is bad and confusing!

The default would ideally be seconds for both timestep modes, but be easily changeable by changing a global boolean value.

As a temporary step I suggest introducing the global boolean but leaving its default as timestep-dependent, to avoid breaking everyone's code.

Fix draw hitbox of parallax entity

Open

package net.flashpunk.utils.Draw

Find in static function hitbox

var x:int=e.x - e.originX - _camera.x, 
    y:int=e.y - e.originY - _camera.y;

Change to

var x:int=e.x - e.originX - _camera.x * e.graphic.scrollX, 
    y:int=e.y - e.originY - _camera.y * e.graphic.scrollY;

Open

package net.flashpunk.debug.Console

Find in function renderEntities

g.drawRect((e.x - e.originX - FP.camera.x) * sx, (e.y - e.originY - FP.camera.y) * sy, e.width * sx, e.height * sy);

Change to

g.drawRect((e.x - e.originX - FP.camera.x * e.graphic.scrollX) * sx, (e.y - e.originY - FP.camera.y * e.graphic.scrollY) * sy, e.width * sx, e.height * sy);

Angles are negated (and in degrees, but we'll let that one slide)

So I guess the degrees thing is personal preference, and it's admittedly sometimes more convenient to type 90 rather than Math.PI*0.5.

But the fact that they're negated has on a few occasions led to some really avoidable issues.

Is there anything that can be done about this without breaking a lot of code?

Global volume controls

It would be nice if there were global variables to change the volume of, or mute/unmute, all sounds.

Possibly nicer again would be the ability to control subgroups separately, e.g. sound effects vs. music.

Tilemap/Grid behave differently with out-of-bound coordinates

Haven't double-checked this, but I believe Tilemap does partial wrapping (wraps right to left and bottom to top but not vice-versa -- because of modulo behaviour on negative numbers) while Grid ignores any out-of-bounds values.

The non-wrapping behaviour is probably a more sensible default, but possibly we want a per-object setting to determine whether to wrap tiles. If we do wrap, we probably want to wrap negative coordinates as well as positive!

Too many private variables

More fields should be protected or even public.

While we're at it, we should get rid of all the accompanying /** @private */ comments: they don't add anything useful and in a lot of places are out of date with the actual code.

Per-mask types and multiple masks per entity

Some entities want different-sized hitboxes depending on what they're colliding against. This applies both for collision queries initiated by that entity and queries which are testing an entity as one of several options.

So entities would need to have direct support for having multiple masks, and type would need to be moved to a per-mask property. Calling collide() on an entity would test all of that entity's masks, but there might be a preference for instead calling the collide() method of a specific mask.

We should avoid breaking any existing code if possible.

Bitmap font support

There are a few different implementations already, hopefully it shouldn't be a lot of work to take one and include it.

For discussion: which of these options would be best?

A) The Text class should be modified to support embedded fonts or bitmap fonts.
or
B) There should be a new BitmapText class which extends Text.
or
C) A new BitmapText class NOT extending Text.

I am personally in favour of option A.

Discussion:
http://flashpunk.net/forums/index.php?topic=2366.0
http://flashpunk.net/forums/index.php?topic=2796.0

Extensible broadphase component

Currently when testing for collisions we restrict the search to entities of the correct type. This is the only optimisation in place for limiting the number of entities tested.

This is a reasonable (and easy to code and understand!) solution but some people want something more flexible.

So: we should have a Broadphase class, with World delegating all queries to it. There should be one or more implementations of Broadphase included by default. It should have a public API so that per-game implementations can be developed.

This should be refactored without breaking existing code.

Allow Image to accept an Image as an image source

A pointless example:

var img:Image = new Image(SOURCE, new Rectangle(0, 0, 5, 5));
graphic = new Image(img);

The reason I really want this is so I can use an Image object with a Spritemap, to clip the source image, for example:

var img:Image = new Image(SOURCE, new Rectangle(5, 5, 10, 10));
graphic = new Spritemap(img, 10, 10);

This could be done by grabbing the source buffer if the source image is an Image object.

Another way would be making the source buffer on an Image object public; that would be cool.

EDIT: Just realised the technical difficulties in doing this since Images are drawn like this:

target.copyPixels(_buffer, _bufferRect, _point, null, null, true);

The buffer isn't modified by its rectangle, so I'm not quite sure how the desired effect could be achieved.

FP.elapsed in fixed timestep

FP.elapsed is in milliseconds when using fixed timestep. Very silly when it's in seconds when using non-fixed.

For consistency could this be fixed to be in seconds too?

Incorporate Rolpege's outline text into Text.as ?

Rolpege/Abel Toy made a neat addition to Draknek's improved Text class by adding outlines. After updating to 1.6, this was the only thing I needed to hack in for compatibility with out codebase. I think it's very useful for spicing up text and would be a great addition to Flashpunk standard. Plus, the coding is already done! :)

Useless calculation in Emitter.as

n:Particle, t:Number;
// ...
t = p._time / p._duration;

The variable t is useless in this method, so is the time scale calculation (lines 55 & 62). Can safely be removed.

World transition effects

Brainstorm some nice API here? May not be a good friendly way of integrating it with FlashPunk.

Interactive terminal in debug mode

This would be super-awesomely useful: basically something that would let you query and/or change variables at runtime.

One for the "lots of work" pile.

`collide`, `collideTypes`, etc. shouldn't require x/y position

If unspecified, the position should default to the entity's current position.

Unfortunately, a lot of methods like collidePoint and collideInto have other parameters after these, so may be no easy way to make these optional. In some cases we might be able to do some cleverness based on the number of parameters provided, but not sure if that's too unintuitive.

Now it never makes rounded corners for outlines.

You missed part of my code, where it checks if the user wants rounded corners on their outline or not. Now it never makes the corners round for the edges. I fixed it below.

Change
else {
_graphics.lineStyle(thick, color, alpha, false, LineScaleMode.NORMAL, null, JointStyle.MITER);
}

To
else {
if (radius <= 0) {
_graphics.lineStyle(thick, color, alpha, false, "normal", null, JointStyle.MITER);
} else {
_graphics.lineStyle(thick, color, alpha);
}
}

And it'll all be good. :)
-Bret Hudson

Circular hitboxes

This is a very common requirement, it should be built-in to FlashPunk.

Regression testing framework

Not something I'm likely to prioritise but it would be really good to have an automated test suite.

Not sure what options there are out there.

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.