Components
A component is a piece of code that defines a specific behavior of a game object. It returns a set of properties and methods that are attached to the game object.
Using a component
For use components we have to attach them in the add()
function.
const player = add([
// rect(width, height) comp draws a rectangle in the obj
rect(40, 60),
// pos(x, y) comp sets the obj position
pos(10, 10),
]);
// method given by pos() comp
player.move(100, 0); // moves the player 100px to the right
// property given by rect() comp
debug.log(player.height); // will log 60
There are a lot of useful components in KAPLAY like:
sprite()
to make the object draw an image, and play animationsarea()
to make the object do collision detection, with methods likeonCollide()
text()
to make the object draw textscale()
to make the game object bigger or smaller or to stretch it
You can see all the components in the API Reference.
Components operations
All components have an id, this is the name of the component, sprite()
’s
id is "sprite"
. This is used in many operations.
How to add components
loadSprite("bean", "sprites/bean.png");
// Add the component on creation
const bean = add([
sprite("bean"), // bean the frog :D
opacity(0.6), // a ghost bean???
]);
// Add the component after creation
bean.use(color("#ff00ff")); // green bean <:
How to remove components
// We pass the component id for remove it.
bean.unuse("sprite"); // bye bean
How to know if a game object have a component
// We pass the component id:
bean.has("sprite"); // false - true if comp is there, otherwise false
Making your own components
If you are creating a larger game, it’s probably a good idea to bundle some of your game’s functionality into custom components. You can check out how to do that in this guide.