Code Monkey home page Code Monkey logo

kontra's Introduction

Version Build Status

Kontra.js

A lightweight JavaScript gaming micro-library, optimized for js13kGames.

Documentation

All the documentation can be found on the github page.

Community

If you'd like to chat about Kontra, check out the #kontra channel of either the js13kGames Slack or the Gamedev.js Discord!

Contributing

See the Contributing file.

Supporting

Kontra.js is made possible by users like you. Through helping find issues, opening pull requests, and funding continuous development, Kontra.js can continue to provide you with quality improvements and updates.

When you become a Patron, you get access to behind the scenes development logs, the ability to vote on which features to work on next, and early access to development builds.

Top Patrons

  • Karar Al-Remahy
  • UnbrandedTech
  • Innkeeper Games
  • Nezteb

kontra's People

Contributors

anderoonies avatar boldbigflank avatar bouiboui avatar burntcustard avatar danieltdt avatar dependabot[bot] avatar depp avatar fariazz avatar fbertolotti avatar felladrin avatar jfcisco avatar johnedvard avatar jvalecillos avatar leokuo0724 avatar mgmarlow avatar neo97online avatar nezteb avatar nibblebot avatar niicojs avatar qw3n avatar rayne avatar reece-bennett avatar sdepold avatar sheepsteak avatar straker avatar swashvirus avatar sylfel avatar tollefsen avatar torik135 avatar wini3d 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

kontra's Issues

More collisions

I've been thinking of a few ways to make more robust collision detection. Perhaps it should be its own plugin. It'd be nice to say what shape it is, then let the plugin decide what algorithm to do.

collidesWith: kontra.collisions.circle

Collision direction and blocking sprites

How do you detect the direction of collision? I tried updating the collision with the code below to move the chicken, but can be stopped in any direction by the player.

    window.chicken = kontra.Sprite({
        x: tileEngine.sx + 400,
        y: tileEngine.sy + 50,
        count: 0,
        animations: chickenSpritesheet.animations,
        update: function() {
            if (!this.collidesWith(window.collisionBox)) {
                this.x = this.x + .5
            }
            this.advance();
        }
    });

Also, would it also be possible to have the same collision effect as the tile collision layer and player, between sprites? sort of sliding effect or free movement if the other entity or sprite is standing beside the player or any sprite. An example would be if the player presses against any side of the bridge and can still move up or down freely. just curious.

Pointer/Touch events not working

I'm trying to do a simple touch / click at first, but it seems that the events are not fired. I also tried on mobile, and sometimes it fired an alert for the onDown function, but not always.

this._kontra.card = kontra.sprite({
	x: 0,
	y: 0,
	image: KontraSprites.card,
	width: this.width,
	height: this.height,
	onDown: function() {
		console.log("down");
	},
	onUp: function() {
		console.log("up");
	},
	onOver: function() {
		console.log("over");
	}
});

kontra.pointer.track(this._kontra.card);

And I have a really simple gameLoop:

kontra._loop = kontra.gameLoop({
	update: function() {
		sprite.update();
		for(var i in KontraPOOL){
			KontraPOOL[i].update();
		}
	},
	render: function() {
		sprite.render();
		for(var i in KontraPOOL){
			KontraPOOL[i].render();
		}
	}
});

kontra._loop.start();

Any ideas why the events for the pointer won't fire? Am i missing something?
Thanks

iOS < 10 Safari - Unexpected Identifier 'imageRegex'

v5.3.0
Trying to load kontrajs on an old ipod touch with iOS 9.3.5, but fails.

This is likely an ES6 issue. The message is:
Unexpected identifier 'imageRegex'

Not sure how much effort should go into fixing old devices, but it's something I'm seeing so I would love some help if possible.

Modularize sprites/entities when using asset preloader event.

More on a question how to do this. I was trying to separate each sprite/entity on each separate js file and require them and then pack them all back in one later for production.

Also, will there be support for entity component system? maybe as a plugin.

Porting the build workflow to Webpack

This is 2018 and Webpack is hot and popular. On the other hand it is quite powerful and efficient . So is it possible and feasible to port the build workflow to Webpack 4.x

Can't load Tiled map that uses tilesets as jsons

map created by Tiled uses the following structure:

...
"tilesets":[
        {
         "firstgid":1,
         "source":"tileset.json"
        }
],
...

Kontra expects the image inside tileset, but not json:
https://github.com/straker/kontra/blob/master/src/tileEngine.js#L190

addTilesets: function addTilesets(tilesets) {
  [].concat(tilesets).map(function(tileset) {
    let tilesetImage = tileset.image;
...
    image = tilesetImage;
...
numTiles = ( (image.width / tileWidth | 0) || 1 )

the last line throws a runtime error of course:
Uncaught (in promise) TypeError: Cannot read property 'width' of undefined

Support for pointers on `object.render()` objects

For objects that I have created with this function:

function createCircle(options) {
            var circleSprite = kontra.sprite({
                x: options.x,
                y: options.y,
                color: options.color,
                radius: options.radius,
                width: options.radius * 2,
                height: options.radius * 2,
                render: function() {
                    this.context.fillStyle = this.color;
                    this.context.beginPath();
                    this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
                    this.context.fill();
                },
                onDown: function() {
                    console.log("Hello"); // never called
                },
                collidesWithPointer: function(pointer) {
                    // perform a circle v circle collision test
                    var dx = pointer.x - this.x;
                    var dy = pointer.y - this.y;
                    var isCollided = Math.sqrt(dx * dx + dy * dy) < this.radius;
                    return isCollided;
                }
            });
            return circleSprite;
        }

Simple circles; I have implemented the collidesWithPointer() method and I read in the API that the object must haven been rendered to the canvas using object.render(). I don't understand why this would be needed since I supplied a collidesWithPointer() method. All I ask is you remove this object.render() check and only check for a collidesWithPointer() method.

Update to use ES6 module syntax

Support webpack, rollup, and code splitting.

  • assets
  • core
  • gameLoop
  • keyboard
  • plugin
  • pointer
  • pool
  • quadtree
  • sprite
  • spriteSheet
  • store
  • tileEngine

Suggestion: sprite.anchor

It would be nice to be able to set an 'anchor' point as the point of origin. Don't know what would match more, having a sprite.anchorX and sprite.anchorY or sprite.anchor = {x:0, y:0}, but the idea would be to set the origin as a percentage of the width/height. That way an anchor of x:.5, y: .5 would render the default sprite with the center at the point (x, y) and collision would also match.

On touch devices, events are fired twice

I'm noticing when you use a phone to press a button, it's firing twice, once for touchstart and once for mousedown. To fix this. the event handler should stop propogation on touches on the canvas. I'll make a PR

          let rightButton = kontra.sprite({
            x: 240,
            y: 500,
            width:80,
            height: 80,
            onDown: function () {
                car.rotation = (car.rotation-90+360)%360
            },
            render: function () {
                this.context.save();
                this.context.strokeStyle = this.color;
                this.context.translate(this.x, this.y)
                this.context.beginPath()
                this.context.moveTo(0,20)
                this.context.lineTo(40, 20)
                this.context.lineTo(40, 0)
                this.context.lineTo(80, 40)
                this.context.lineTo(40, 80)
                this.context.lineTo(40, 60)
                this.context.lineTo(0, 60)
                this.context.closePath()
                this.context.stroke()
                
                this.context.restore();
            }
        })
        kontra.pointer.track(rightButton)
        sprites.push(rightButton)

Prevent default behavior with keypresses

Is it possible to do event.preventDefault() with keypress bindings? For example, hitting the space bar in my game will do a thing, but also scroll down the window a page.

Pointer/anchor not matching

I'm making a draggable object, and it seems the pointer is not properly following the anchor point. here's a sprite:

const COLOR_AMBER = '#FFBF00'
var critter = {
            x: kontra.canvas.width/2,
            y: kontra.canvas.width/2, // Width bc we don't want to count the bar at the bottom
            anchor: {
                x: 0.5,
                y: 0.5
            },
            width:96,
            height:96,
            color: COLOR_AMBER,
            selected: false,
            onDown: function() {
                this.selected = true;
                this.lastPosition = {
                    x: kontra.pointer.x,
                    y: kontra.pointer.y
                }
            },
            onUp: function() {
                this.selected = false;
            },
            update: function() {
                if (!this.selected)
                    this.advance()
                else {
                    this.x += kontra.pointer.x - this.lastPosition.x
                    this.y += kontra.pointer.y - this.lastPosition.y
                    this.lastPosition = {
                        x: kontra.pointer.x,
                        y: kontra.pointer.y
                    }
                }
            },
        }

Viewport Control

Another idea, not sure where this would fit in the system. It would be nice to set a viewport with an x, y, width and height. Every frame this would translate and scale the context before going through the render function. This would make it easy to zoom and focus on certain sprites in a larger-than-viewport-size map.

Sprite to Sprite Collision on tileEngine

The new update looks great, but just adding an update function on the chicken sprite stops its animation. I'm actually trying to add collision test on the example but it just stops. So would it be nice to showcase some of the basic components on tileEngine and update the example with a collision on another sprite that has the same effect as the collision tile layer?

Pointer doesn't work past bottom of the page

This one took a while to figure out. I have a canvas that is under a list of players. When two or more people were joined in a game I'm making, the a tracked sprite being used as a Start button wouldn't work sometimes. Found out it was only when I had to scroll down to hit the button because it was under the fold.

Tile based movement

This is probably more of a feature enhancement and also related with the TileEngine and it would be nice to have a smooth tile based movement option as well.

Possibility of rotating an animation

Hey there, very nice work!

We're currently making a hackday at our company and I was wondering if it's possible to rotate an animation by an angle.

It's (imo) cheaper (in case of filesize) to rotate the image than to import more sprites.

I'm trying with overwriting the draw methods and stuff, but so far, no luck.

Can you help me or provide any code sources where I can have a look?

Greetings
Chris

Sprites without TTL have a 0 ttl

This is a change that happened recently and it causes some bad behavior to sprites by default. I'd like to know the reasoning to perhaps find a better solution.

Text drawing support

Would you be open to a pull request adding PixelFont for drawing text? It seemed very popular during js13k.

Asset Loading - loading multiple times

Would it make sense for the kontra.assets.loadImage function to resolve with the existing image if it has already been loaded into the assets? Same with the other load functions.

Object Pool always making object to maxSize

When getting objects from an object pool the get() method will check current objects and always find that to be true when using kontra.sprite as the create property (kontra.sprite init defaults to ttl=Infinity). In my own project I just changed the default to 0 and specify Infinity on non-pool sprites to get around the issue. Not sure if there is a better way to fix this. I noticed it when I didn't set a max size and my browser tab stopped responding (it was stuck in an infinite loop of object creation).

This test will fail. The other pool tests use a modified sprite which doesn't include ttl.

    it('should not continue making objects if not needed', function() {
      var pool = kontra.pool({
        create: kontra.sprite,
        maxSize: 500
      });

      for (var i = 0; i < 129; i++) {
        pool.get();
      }

      expect(pool.size).to.not.equal(pool.maxSize);
      expect(pool.size).to.be.equal(256);
    });

Sprite - Serialize/ToJSON

I'm working on a game that has multiple users over a network, and it's a pain point to keep sprites synchronized. It might be good to have some form of toJSON function that would pull just enough out of the Sprite object to be able to make it again.

I do a sprite template like this

var customSprite = {
    id: 0,
    x: 0,
    y: 0,
    width: 50,
    height: 50,
    performAction: function(e) {
        // Do stuff
    },
    desiredX: 0,
    desiredY: 0
}

then make a bunch of sprites

for (let i = 0; i < 10; i++) {
    let s = kontra.sprite(customSprite)
    s.id = i
    s.x = i * 50
}

Ideally I'd like to do something like this

socket.emit('sprite', s.toJSON())

and then catch it on the other end

socket.on('sprite', function(data) {
    let s = sprites.find((sprite) => sprite.id === data.id)
    if (!s) {
        s = kontra.sprite(customSprite)
    }
    // Update the sprite with the object... somehow
    s.fromJSON(data)
})

I could probably put some work into this, but I wanted to know if there were any suggestions or insights on doing this.

Suggestion: Sprite Z Ordering Feature

It would be nice to easily have a sprite z ordering feature (with options) particularly with the tileEngine in addition to the position all sprites including player controlled sprite.

An example option would be basing it on y value for top down maps.

Advanced Text Sprites

I think there might be some potential for a Text based sprite. If you were to define a width/height, then 'text' it could figure out the largest size it could fit into the rect. Would this be a new Plugin? Probably.

Pointer - iOS Chrome - touchmove refreshes the page

Problem:
When using Chrome for iOS, dragging on the kontra canvas causes the page to scroll (Even in the latest version). This is reproducible on all sites, but http://alexswan.info/js13k-2018/dist is a place to try it out. You cannot see this issue using the desktop Chrome in responsive mode or Firefox, they don't simulate touch moves.

Source:
The code that sets up listeners is assigned globally, which I believe is too high up to stop the browser's scroll behavior.

addEventListener('mousedown', pointerDownHandler);
addEventListener('touchstart', pointerDownHandler);
addEventListener('mouseup', pointerUpHandler);
addEventListener('touchend', pointerUpHandler);
addEventListener('blur', blurEventHandler);
addEventListener('mousemove', mouseMoveHandler);
addEventListener('touchmove', mouseMoveHandler);

I was able to fix the issue with this in _tick but this is an awful way of doing it, I would like a better recommendation.

if (!kontra.eventsAdded) {
      if (kontra.canvas) {
        console.log("adding events");
        kontra.canvas.addEventListener('mousedown', pointerDownHandler);
        kontra.canvas.addEventListener('touchstart', pointerDownHandler);
        kontra.canvas.addEventListener('mouseup', pointerUpHandler);
        kontra.canvas.addEventListener('touchend', pointerUpHandler);
        kontra.canvas.addEventListener('blur', blurEventHandler);
        kontra.canvas.addEventListener('mousemove', mouseMoveHandler);
        kontra.canvas.addEventListener('touchmove', mouseMoveHandler);
        kontra.eventsAdded = true;
      }else {
        console.log("no kontra.canvas")
      }
    }

Suggestion: sprite.rotation

While simple to render, would be a bit more difficult to determine collidesWith. For this reason it'd be good to do once and have available for all.

Is kontra.assets.loadImage() deprecated?

First of all, amazing framework! I plan to use it to teach a class on JavaScript to people who are new to coding.

Anyways, I was trying to run some of the examples and I got the error kontra.assets.loadImage is not a function a couple times. However, when I replaced the call with kontra.assets.load everything worked!

I'm pretty sure it's because the API changed at some point, but I couldn't find any mention of it.

Pointer x/y not updated with touch

I'm making a drag and drop setup and the pointer has some strange behavior with touches. Right now, when I try to drag an object, touching selects it correctly, but dragging does not move the sprite. Releasing the touch moves the sprite to the place it was released, but does not do the unselected behavior. Tapping elsewhere releases the sprite.

I would expect that touch[0] would be the same as 'left' mouse button, so pointer.pressed('left') should return true when I have one finger down. Also, touchMoved should update kontra.pointer.x and kontra.pointer.y.

Here's some sample code for trying it out

const COLOR_AMBER = '#FFBF00'
var critter = {
            x: kontra.canvas.width/2,
            y: kontra.canvas.width/2, // Width bc we don't want to count the bar at the bottom
            anchor: {
                x: 0.5,
                y: 0.5
            },
            width:96,
            height:96,
            color: COLOR_AMBER,
            selected: false,
            onDown: function() {
                this.selected = true;
                this.lastPosition = {
                    x: kontra.pointer.x,
                    y: kontra.pointer.y
                }
            },
            onUp: function() {
                this.selected = false;
            },
            update: function() {
                if (!this.selected)
                    this.advance()
                else {
                    this.x += kontra.pointer.x - this.lastPosition.x
                    this.y += kontra.pointer.y - this.lastPosition.y
                    this.lastPosition = {
                        x: kontra.pointer.x,
                        y: kontra.pointer.y
                    }
                }
            },
        }

Dynamic sprite/object placement on tileEngine map

I'm trying to add some static and dynamic sprites to a tileEngine level, having x and y properties with a value of 0 sticks it to the top left of the screen and just follows the player.

So how do you place sprites on specific location or parts of the level? This is somehow related to my last closed issue. Thanks.

Unable to import with parcel or webpack bundlers

Hello,
I tried importing the package, after installing it from npm, with parcel and webpack but both didn't work.
Can you please clarify in the docs how we should proceed to make it work.
Thanks.

Mouse Support

Is there a reason that there is no mouse support?
It would be great if there was way to bind an onClick event on a sprite.

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.