### Clone ct.js Docs Repository
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/README.md
Instructions to clone the ct.js documentation repository from GitHub to your local machine, initiating the development setup process.
```Shell
git clone https://github.com/ct-js/docs.ctjs.rocks.git
```
--------------------------------
### Launch ct.js Docs Development Server
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/README.md
Command to start the local development server for the ct.js documentation, enabling live reloading for previewing changes to markdown files in real-time.
```Shell
npm run dev
```
--------------------------------
### Install Dependencies for ct.js Docs
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/README.md
Command to install necessary Node.js dependencies for the ct.js documentation project using npm, which are required to run the development server.
```Shell
npm install
```
--------------------------------
### Initialize Object Generation Timers in Room Start
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Illustrates how to set up initial timers within the `Room start` event to control the spawning of different game entities, such as asteroids and enemies, at predefined intervals.
```JavaScript
this.timer1 = 0.3; // asteroid timer
this.timer2 = 3; // enemy timer
```
```CoffeeScript
# asteroid timer
@timer1 = 0.3
```
--------------------------------
### Navigate into ct.js Docs Directory
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/README.md
Command to change the current working directory to the newly cloned ct.js documentation repository, preparing for dependency installation.
```Shell
cd ./docs.ctjs.rocks/
```
--------------------------------
### Initialize Room Data with a Behavior
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-platformer.md
This snippet demonstrates how to set up initial room-specific variables using a 'Behavior'. It's intended for a 'Room start' event within a behavior named `inGameRoomStart`. It initializes the `crystals` count to zero and calculates the `crystalsTotal` based on the number of 'GreenCrystal' templates in the game, making the setup reusable across multiple rooms.
```JavaScript
rooms.current.crystals = 0;
rooms.current.crystalsTotal = templates.list['GreenCrystal'].length;
```
```CoffeeScript
rooms.current.crystals = 0
rooms.current.crystalsTotal = templates.list['GreenCrystal'].length
```
```Catnip
current room.crystals = 0
current room.crystalsTotal = templates.list['GreenCrystal'].length
```
--------------------------------
### Implement Enemy Ship Spawning Timer
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Sets up a second timer for generating enemy ships at random intervals and positions. This example is provided in JavaScript.
```JavaScript
// enemy timer
this.timer2 = random.range(3, 6);
templates.copy('EnemyShip', random(camera.width), -100);
```
--------------------------------
### Migrating ct.js Global Object Access - New Code Example
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/troubleshooting/migration-3to4.md
This snippet demonstrates the new syntax in ct.js v4.0, where the `ct.` prefix has been removed for most global functionalities like `random`, `camera`, and `tween`. It shows the updated game logic for setting a target position and adding a tween animation, reflecting the simplified access.
```js
// A snippet from the catsteroids demo
this.targetx = random.range(75, camera.width - 75);
this.targety = random.range(75, 300);
tween.add({
obj: this,
fields: {
x: this.targetx,
y: this.targety
},
duration: 1500
});
```
--------------------------------
### Migrating ct.js Global Object Access - Old Code Example
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/troubleshooting/migration-3to4.md
This snippet demonstrates the old syntax in ct.js v3.x and earlier, where global functionalities like `random`, `camera`, and `tween` were accessed via the `ct.` prefix. It shows a typical game logic for setting a target position and adding a tween animation.
```js
// A snippet from the catsteroids demo
this.targetx = ct.random.range(75, ct.camera.width - 75);
this.targety = ct.random.range(75, 300);
ct.tween.add({
obj: this,
fields: {
x: this.targetx,
y: this.targety
},
duration: 1500
});
```
--------------------------------
### JavaScript While Loop for Object Instantiation
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt2.md
Example demonstrating the use of a 'while' loop in JavaScript to efficiently create a specified number of game objects ('Copies') without hardcoding each instance.
```js
var counter = 20; // We need to create 20 Copies
while (counter > 0) {
templates.copy('Enemy', this.x, this.y);
counter --;
}
```
--------------------------------
### Complete Room Transition in New Room Start
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-polishing-jettycat.md
This snippet shows how to complete a room transition by calling `transition.circleIn` in the `InGame` Room's start code. This creates a smooth entry animation into the new room, matching the previous `circleOut` effect. The duration and color should typically align with the outgoing transition for a seamless experience.
```JavaScript
transition.circleIn(500, 0x446ADB);
```
```CoffeeScript
transition.circleIn 500, 0x446ADB
```
--------------------------------
### Execute Enemy Ship Movement (Frame Start Event)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Calls the built-in `this.move()` method within the Frame Start event. This single line of code reads the `this.speed` and `this.direction` variables set in the Creation event and applies the movement to the enemy ship, automating its position updates each frame.
```JavaScript
this.move();
```
```CoffeeScript
@move()
```
```Catnip
Move this copy
```
--------------------------------
### Initialize Player Lives in Room Start
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Sets the initial number of player lives when a room starts. This variable is stored on the `this` context of the room, making it accessible throughout the room's lifecycle.
```JavaScript
this.lives = 3;
```
```CoffeeScript
@lives = 3
```
```Catnip
Set lives value 3
```
--------------------------------
### JavaScript Game Jump Logic
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt2.md
Example demonstrating how to implement a jump action in a game using an 'if' statement. It checks if the player is on the ground and if the 'Jump' action key is pressed before applying vertical speed.
```js
this.onGround = true;
var keyUp = actions.Jump.down;
if (this.onGround && keyUp) {
this.addSpeed(this, 10, 270);
}
```
--------------------------------
### Platformer Movement with Gravity and `moveSmart` (ct.js)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tips-n-tricks/movement.md
Demonstrates platformer character movement, including gravity application, jumping, and collision handling with `this.moveSmart` to prevent sticking to obstacles and reset vertical speed on Y-axis collisions. This example includes both 'On Create' for initial setup and 'On Step' for continuous logic.
```js
this.gravity = 0.5;
this.gravityDir = 270;
```
```js
this.hspeed = actions.MoveX.value * 10;
// Is there any ground underneath?
if (place.occupied(this, this.x, this.y + 1, 'Solid')) {
// Check whether a player wants to jump.
if (actions.Jump.down) {
this.vspeed = -15;
}
}
// Move the copy
const collided = this.moveSmart('Solid');
// Check whether there was a collision, and whether it was on Y axis
if (collided && collided.y) {
// Reset vertical speed
this.vspeed = 0;
}
```
--------------------------------
### Create and configure a new background with backgrounds.add
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/backgrounds.md
This example demonstrates how to use the `backgrounds.add` method to create a new background. It shows how to specify the texture, frame, and depth during creation, and then further configure the created background by setting its `alpha` (opacity) and `movementX` (horizontal movement) properties.
```JavaScript
const bg = backgrounds.add('BG_SkyClouds', 0, -1000);
bg.alpha = 0.5;
bg.movementX = 1;
```
```CoffeeScript
bg = backgrounds.add 'BG_SkyClouds', 0, -1000
bg.alpha = 0.5
bg.movementX = 1
```
--------------------------------
### Initialize Room Timer for Pipe Spawning
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-jettycat.md
Sets up a `timer1` variable in the 'Room start' event, which automatically counts down and triggers the 'Timer 1' event. This variable acts as an initial delay before the first set of pipes are spawned.
```JavaScript
this.timer1 = 5;
```
```CoffeeScript
@timer1 = 5
```
```Catnip
Set 1st timer tosecond(s)
```
--------------------------------
### Initialize Pulse Phase for Hint Animation
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-polishing-jettycat.md
Sets the initial value for the `pulsePhase` property in the template's Creation code. This property is crucial for controlling the pulsating animation of the hint icon, ensuring it starts from a defined state.
```JavaScript
this.pulsePhase = 0;
```
--------------------------------
### `sounds.volume` Method Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
API documentation for the `sounds.volume` method, used to get or set the volume for a specific sound instance.
```APIDOC
sounds.volume(name: string | IMediaInstance, volume?: number)
name: The name of the sound or an IMediaInstance.
volume: (optional) A value from 0 to 1 to set the volume. If not specified, returns the current volume.
Returns: Number. The current or new volume of the sound.
```
--------------------------------
### `sounds.speed` Method Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
API documentation for the `sounds.speed` method, used to get or set the playback speed for a specific sound instance.
```APIDOC
sounds.speed(name: string | IMediaInstance, value?: number)
name: The name of the sound or an IMediaInstance.
value: (optional) A number representing the playback rate (1 is 100%). If not specified, returns the current speed.
Returns: Number. The current or new speed of the sound.
```
--------------------------------
### Playing a 3D Sound Following a Copy
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
Example of `sounds.playAt` where the sound's position dynamically updates with the `this` (current copy) object, making the sound follow the copy.
```JavaScript
sounds.playAt('MySound', this);
```
```CoffeeScript
sounds.playAt 'MySound', this
```
--------------------------------
### Basic JavaScript 'for' Loop for Iteration
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt2.md
Demonstrates a traditional 'for' loop in JavaScript, iterating downwards from 20 to 1, calling 'templates.copy' in each iteration. This example shows how to combine initialization, condition, and iteration expression in a single line.
```JavaScript
for (var counter = 20; counter > 0; counter--) {
templates.copy('Enemy', this.x, this.y);
}
```
--------------------------------
### Get Direction of Vector (u.pdn, u.pointDirection)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/u.md
Calculates the direction of a vector pointing from a starting point (x1;y1) to an ending point (x2;y2).
```APIDOC
u.pdn(x1: number, y1: number, x2: number, y2: number)
u.pointDirection(x1: number, y1: number, x2: number, y2: number)
x1: number - x-coordinate of the starting point.
y1: number - y-coordinate of the starting point.
x2: number - x-coordinate of the ending point.
y2: number - y-coordinate of the ending point.
Returns: number - The direction of the vector in degrees.
```
--------------------------------
### Example: Creating a New Camera Instance
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/pt_BR/ct.camera.md
This JavaScript code demonstrates how to create a new `Camera` object and assign it as the active camera for the game. It also shows how to store the previously active camera instance, allowing for potential restoration or manipulation of multiple camera views.
```JavaScript
const oldCamera = ct.camera;
ct.camera = new Camera(0, 0, 1024, 768);
```
--------------------------------
### JavaScript Condition to Destroy Game Object
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt2.md
Example showing how to use an 'if' statement in JavaScript to set a game object's 'kill' flag to true if its health drops to zero or below.
```js
if (this.health <= 0) {
this.kill = true;
}
```
--------------------------------
### Set Next Room in Room Start Event
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-platformer.md
This example shows how to set the 'nextRoom' property for a room, typically within a 'Room start' event. This property can then be used by other logic (like the previous snippet) to determine where to transition next. The 'this' keyword in JavaScript and '@' in CoffeeScript refer to the current room instance.
```JavaScript
this.nextRoom = 'Level_02';
```
```CoffeeScript
@nextRoom = 'Level_02'
```
```Catnip
Set "nextRoom" value "Level_02"
```
--------------------------------
### Calculate Sum of Array Properties with JavaScript `reduce`
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt3.md
Explains how `array.reduce` can be used to iterate over an array and accumulate a single value. This example sums up the 'delay' property from an array of wave objects, starting with an initial sum of zero.
```js
var waves = [{
delay: 30,
monsters: [{
type: 'Monster_Flyer',
health: 10,
amount: 10
}]
}, {
delay: 10,
monsters: [{
type: 'Monster_Flyer',
health: 15,
amount: 12
}]
}, {
delay: 12,
monsters: [{
type: 'Monster_Flyer',
health: 15,
amount: 20
}, {
type: 'Monster_Tank',
health: 15,
amount: 20
}]
}, {
delay: 20,
monsters: [{
type: 'Monster_Boss',
health: 1000,
amount: 1
}]
}];
var timeTillBoss = waves.reduce((currentSum, wave) => {
return currentSum + wave.delay
}, 0); // Here 0 is the starting value.
```
--------------------------------
### Implement Frame Start Logic for Object Lifecycle
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Demonstrates how to apply per-frame updates to a game object, including checking if it's off-screen for destruction, applying movement, and rotating its texture. It highlights the use of `u.time` to ensure frame-rate independent calculations.
```JavaScript
if (this.y > camera.height + 40) {
this.kill = true;
}
this.move();
this.angle -= 240 * u.time;
```
```CoffeeScript
if @y > camera.height + 40
@kill = true
@move()
@angle -= 240 * u.time
```
```Catnip
Ify>height+
Destroy this copy
Move this copySet texture rotation totexture rotation-×time
```
--------------------------------
### Declare and Access Simple JavaScript Arrays
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt3.md
This snippet demonstrates how to declare basic arrays using literal notation and access individual elements by their numerical index, starting from zero. It shows examples with simple strings and numbers.
```js
var groceryList = ['potato', 'carrot', 'thyme'];
this.waveEnemyAmount = [10, 10, 15, 15, 20, 25];
console.log(groceryList[0]); // Will log 'potato'
console.log(groceryList[1]); // Will log 'carrot'
console.log(this.waveEnemyAmount); // Will output the whole array
```
--------------------------------
### Find Elements and Indices in JavaScript Arrays with `find` and `findIndex`
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt3.md
Demonstrates `array.find` to retrieve the first element matching a condition (or `undefined`), and `array.findIndex` to get its index (or `-1`). Examples include finding an object by property and removing an element using its found index.
```js
this.gear = [{
name: 'The hammer of bug killing',
type: 'weapon'
}, {
name: 'The helmet of system thinking',
type: 'head'
}, {
name: 'The chestplate of ignorance',
type: 'torso'
}];
// Set the dealt damage to the weapon's damage in the current gear array
var weapon = this.gear.find(item => item.type === 'weapon');
this.damage = weapon.damage;
// Remove the helmet
var helmetIndex = this.gear.findIndex(item => item.type === 'head');
if (helmetIndex !== -1) { // Make sure we did find a helmet
this.gear.splice(helmetIndex, 1);
}
```
--------------------------------
### Using CtAction Instances for Game Movement and Input Handling
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/inputs.md
This example demonstrates how to integrate `CtAction` instances into game logic to control copy movement and trigger actions. It utilizes `actions.MoveX.value` and `actions.MoveY.value` for scalar input-driven movement and `actions.Shoot.pressed` for button-press detection, enabling dynamic game responses to player input.
```JavaScript
/**
* Move the copy around.
* See "Project" > "Actions and input methods"
* and "Actions" in the docs.
*/
this.hspeed = 8 * actions.MoveX.value; // Move by X axis
this.vspeed = 8 * actions.MoveY.value; // Move by Y axis
if (actions.Shoot.pressed) {
templates.copy('Bullet', this.x, this.y);
}
```
```CoffeeScript
###
Move the copy around.
See "Project" > "Actions and input methods"
and "Actions" in the docs.
###
@hspeed = 8 * actions.MoveX.value # Move by X axis
@vspeed = 8 * actions.MoveY.value # Move by Y axis
if actions.Shoot.pressed
templates.copy 'Bullet', @x, @y
```
--------------------------------
### Spawn Copy Under Cursor on Mouse Click
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/templates.md
This example shows how to create a new 'Fruit' copy at the current pointer's x and y coordinates when a 'Press' action (e.g., primary mouse button) is detected as being down. This requires an action named 'Press' to be configured.
```JavaScript
if (actions.Press.down) {
templates.copy('Fruit', pointer.x, pointer.y);
}
```
```CoffeeScript
if actions.Press.down
templates.copy 'Fruit', pointer.x, pointer.y
```
--------------------------------
### API Migration: Catmods and Module Changes
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/troubleshooting/migration-3to4.md
This section details several changes related to catmods and module usage in ct.js v4.0. It covers the renaming of `tween.add` option, removal of `/*!%start%*/` injection, and the deprecation of `mouse` and `touch` catmods in favor of the `pointer` module or built-in pointer events.
```APIDOC
tween.add: Option `useUiDelta` renamed to `isUi`.
/*!%start%*/ injection: Removed. Write code in `index.js`.
mouse and touch catmods: Removed. Use `pointer` module or built-in pointer events.
```
--------------------------------
### `sounds.play` Method Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
API documentation for the `sounds.play` method, detailing its parameters, available options for playback control, and return types.
```APIDOC
sounds.play(name: string, options?: object)
name: Sound's name
options: (optional) Options used for sound playback.
start: Start time offset, in seconds.
end: End time, in seconds.
loop: Whether to loop the sound or not.
filters: pixi-sound filters to apply.
complete: A callback that is called when the sound has finished playing.
loaded: If the sound is not already preloaded, this function will be called when the sound asset finishes loading.
muted: If sound instance is muted by default.
singleInstance: Setting true will stop any playing instances.
speed: Override playback speed; defaults to the Sound's speed setting.
volume: Override the sound's volume.
Returns: Either a sound instance, or a promise that resolves into a sound instance. See IMediaInstance.
```
--------------------------------
### Catnip Properties and Variables Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-catnip/introduction.md
This section provides a comprehensive overview of the different types of properties and variables in Catnip, explaining their scope, lifecycle, and typical use cases within the game development environment. It details how each type of data storage behaves and when to use them.
```APIDOC
Properties and variables:
Regular properties:
Description: Saved directly in a copy or a room instance; not shared. Persist as long as the copy/room exists. Useful for tracking unit-specific data like hit points.
Example: `price`
Regular variables:
Description: Exist only during the event they are edited. Their values reset to `undefined` every time the event restarts. Suitable for temporary computation results or values not needed long-term.
Example: `target`
Global variables:
Description: Stored in the game itself and persist until the game is closed. Their single value can be read and written from anywhere in the game. For persistence between game runs, 'Save/Load from storage' blocks are needed.
Example: `money`
Event variables:
Description: Provided by specific events to offer additional context or specifics about when the event was triggered.
Example: `other`
Behavior properties:
Description: Inherited from behaviors linked in templates and rooms. Function identically to regular properties, but are tied to specific behaviors.
Example: `power`
```
--------------------------------
### Spawn Star and Tube Setup in Timer Event
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-jettycat.md
This code snippet, intended for a room's Timer 1 event, sets up two tubes with varied textures to ensure consistent gaps. The JavaScript version additionally includes logic to conditionally spawn a star bonus with a 30% chance between the tubes, utilizing the `random` module for probability and positioning.
```javascript
// Wind it again
this.timer1 = 2
// Create two tubes
var tube1 = templates.copy('Tube', camera.right + 250, camera.bottom - 130); // At the bottom of the camera
var tube2 = templates.copy('Tube', camera.right + 250, camera.top - 70); // At the top
// Change second tube's texture depending on which texture is used in the first tube
if (tube1.tex === 'Tube_01') { // Shortest tube will result in the longest tube
tube2.tex = 'Tube_04';
} else if (tube1.tex === 'Tube_02') {
tube2.tex = 'Tube_03';
} else if (tube1.tex === 'Tube_03') {
tube2.tex = 'Tube_02';
} else if (tube1.tex === 'Tube_04') { // Longest will result in the shortest one
tube2.tex = 'Tube_01';
}
// Thus we will always get gaps of the same size, but with random tubes.
// Now, flip the upper (second) tube
tube2.scale.y = -1;
// Create a star bonus with 30% chance somewhere in between top and bottom edge, with 300px padding.
if (random.chance(30)) {
templates.copy('Star', camera.right + 250 + 500, random.range(camera.top + 300, camera.bottom - 300));
}
```
```coffeescript
# Wind it again
@timer1 = 2
# Create two tubes
# At the bottom of the camera
tube1 = templates.copy 'Tube', camera.right + 250, camera.bottom - 130
# At the top
tube2 = templates.copy 'Tube', camera.right + 250, camera.top - 70
# Change second tube's texture depending on which texture is used in the first tube
if tube1.tex == 'Tube_01'
# Shortest tube will result in the longest tube
tube2.tex = 'Tube_04'
else if tube1.tex == 'Tube_02'
tube2.tex = 'Tube_03'
else if tube1.tex == 'Tube_03'
tube2.tex = 'Tube_02'
else if tube1.tex == 'Tube_04'
# Longest will result in the shortest one
tube2.tex = 'Tube_01'
# Thus we will always get gaps of the same size, but with random tubes.
# Now, flip the upper (second) tube
tube2.scale.y = -1
```
--------------------------------
### Catnip Visual Scripting: Notes and Timer Setup
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/ru/tutorials/making-games-jettycat.md
This section showcases basic commands in the Catnip visual scripting environment, including adding descriptive notes and setting up a timer. The timer is configured to trigger after a specified duration.
```Catnip Visual Script
Note: Wind it again
Set 1st timer to 2 second(s)
Note: Create two tubes, one at the bottom of the camera and one at the top
```
--------------------------------
### Aligning Copies in a UI Room with makeCopyAlignedRef
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/room.md
This example demonstrates how to create a new copy and align it to the top-center point within a UI room using the `makeCopyAlignedRef` method. It assumes the copy's initial position is relative to the room's template dimensions, and then uses `alignX: 'center'` and `alignY: 'start'` to position it relative to the camera's dimensions.
```js
// In room's Start event:
// Create a copy in the center of the room.
// Use camera.width and camera.height for this.makeCopyAligned.
var copy = templates.copy('BossHealthbar', this.template.width / 2, 0);
this.makeCopyAlignedRef(copy, {
alignX: 'center',
alignY: 'start'
});
```
--------------------------------
### Get All Assets in a Folder (Recursive)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Gets all the assets inside of a folder, including in subfolders.
Parameters:
- `path` (string, optional): Behaves exactly as in `res.getChildren`.
Returns:
- `ExportedAsset[]`: All the assets in the folder and its subfolders. Folders themselves are not included.
```APIDOC
res.getAll(path?: string): ExportedAsset[]
```
--------------------------------
### Start Dragging Logic for a ct.js Copy
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tips-n-tricks/dragging-copies.md
Implements the logic in the `Frame Start` tab to initiate dragging. It checks if the pointer is hovering over the copy and if the 'PointerAction' (mouse button/tap) is pressed, setting `this.dragging` to `true`.
```js
if (pointer.hovers(this) && actions.PointerAction.pressed) {
this.dragging = true;
}
```
--------------------------------
### Visual Scripting: Copy Template and Set Scale
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-jettycat.md
A visual block sequence demonstrating how to copy a template and subsequently apply a specific scale to the copied instance. This snippet illustrates nesting and direct parameter input within the visual scripting environment.
```Visual Scripting
With copy
tube2
Blocks:
Set scale to [1] [ -1]
```
--------------------------------
### Adding a Basic Timer
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/timer.md
Demonstrates how to add a simple timer using `timer.add()` or by instantiating `CtTimer` directly. These timers run for a specified duration in milliseconds.
```JavaScript
// Add a timer
timer.add(1000, 'test');
// Or:
new CtTimer(1000, 'test');
```
```CoffeeScript
# Add a timer
timer.add 1000, 'test'
# Or:
new CtTimer 1000, 'test'
```
--------------------------------
### Get All Frames of a Texture
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Gets a pixi.js texture from a ct.js' texture name. Returns an array with all the frames of this ct.js' texture.
Parameters:
- `name` (string): The name of the ct.js texture. If -1 (a number) is provided, an empty texture will be returned.
```APIDOC
res.getTexture(name: string): PIXI.Texture[]
```
--------------------------------
### Catnip Visual Scripting for Game Logic and Object Creation
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-jettycat.md
This section illustrates various operations using Catnip, a block-based visual scripting language. It includes adding notes, setting a game timer, and copying 'Tube' game object templates to specific positions relative to the camera, storing them in variables for later reference.
```Catnip
Note: Wind it again
Set 1st timer to 2 second(s)
Note: Create two tubes, one at the bottom of the camera and one at the top
Copy a template "Tube"
Position X: camera.right + 250
Position Y: camera.bottom - 130
Store as: tube1
Copy a template "Tube"
Position X: camera.right + 250
Position Y: camera.top - 70
Store as: tube2
```
--------------------------------
### Basic JavaScript While Loop Structure
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-js/jsintro_pt2.md
Illustrates the fundamental syntax for a 'while' loop in JavaScript, demonstrating how code is repeatedly executed as long as a specified condition remains true.
```js
while (/* this statement is true */) {
/* do something */
}
```
--------------------------------
### Initialize Score Variable in Room Start
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
This code snippet initializes the global score variable to zero when a game room starts. It ensures the score begins at a clean state for each new game session or level.
```JavaScript
this.score = 0;
```
```CoffeeScript
@score = 0
```
```Catnip
Setscorevalue
```
--------------------------------
### Get Specific Frame of a Texture
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Gets a pixi.js texture from a ct.js' texture name, extracting a specific frame.
Parameters:
- `name` (string): The name of the ct.js texture. If -1 (a number) is provided, an empty texture will be returned.
- `frame` (number): The specific frame to extract.
```APIDOC
res.getTexture(name: string, frame: number): PIXI.Texture
```
--------------------------------
### Get All Assets in a Folder by Type (Recursive)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Get all the assets inside of a folder, including in subfolders, filtered by type.
Parameters:
- `type` (AssetType | 'folder'): The type of asset to filter by.
- `path` (string, optional): Behaves exactly as in `res.getChildren`.
Returns:
- `(ExportedAsset | ExportedFolder)[]`: All the entries in the folder.
```APIDOC
res.getAllOfType(type: AssetType | 'folder', path?: string): (ExportedAsset | ExportedFolder)[]
```
--------------------------------
### Example: Realign UI Elements in ct.js Room
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/camera.md
Demonstrates how to use the `camera.realign` method within the Frame End code of a UI room to adjust the positioning of UI elements. This example shows the minimal code required to trigger the realignment process for the current room.
```JavaScript
camera.realign(this);
```
```CoffeeScript
camera.realign this
```
--------------------------------
### u.wait Method API Documentation
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-jettycat.md
Detailed documentation for the `u.wait` asynchronous method, explaining its purpose, parameters, return type, and typical usage patterns with `.then()`. It also clarifies its asynchronous nature and relation to JavaScript Promises, along with alternative methods.
```APIDOC
u.wait(milliseconds: number): Promise
Description: Asynchronously waits for the specified number of milliseconds.
Parameters:
milliseconds (number): The duration to wait, in milliseconds.
Returns:
Promise: A Promise that resolves after the specified delay.
Usage:
- `u.wait(1000).then(() => { ... })`: Executes code after the delay.
- Asynchronous: Code runs outside the Frame start event, happens later in the game.
- Promises: In the JavaScript world, such actions are also called "Promises".
Alternatives:
- Timer 1 event and `this.timer1` can achieve similar waiting functionality.
```
--------------------------------
### Create and Configure Copy via Stored Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-catnip/working-with-copies.md
This sequence demonstrates creating a copy of a 'Bullet' template, storing it in a variable named 'bullet', then setting a local variable 'dir' to a 'direction' value, and finally using a 'With copy' block to set the 'direction' property of the 'bullet' copy to the value of 'dir'. This method allows for multi-step configuration.
```Catnip Blocks
Copy a template "Bullet" at x, y store in bullet
Set dir value direction
With copy bullet {
Set direction to dir
}
```
--------------------------------
### Get Direct Children of a Folder by Type
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Gets direct children of a folder, filtered by asset type.
Parameters:
- `type` (AssetType | 'folder'): The type of asset to filter by.
- `path` (string, optional): Behaves exactly as in `res.getChildren`.
Returns:
- `(ExportedAsset | ExportedFolder)[]`: An array of all the selected entries in the folder.
```APIDOC
res.getOfType(type: AssetType | 'folder', path?: string): (ExportedAsset | ExportedFolder)[]
```
--------------------------------
### `sounds.speedAll` Method Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
API documentation for the `sounds.speedAll` method, which sets the playback speed for all sounds globally.
```APIDOC
sounds.speedAll(value: number)
value: A number representing the playback rate (1 is 100%).
```
--------------------------------
### Get Direct Children of a Folder
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/res.md
Gets direct children of a folder.
Parameters:
- `path` (string, optional): A filepath-like string (e.g., `/Core/Player`). Both `/` and `\` are supported, and leading/trailing slashes are optional. If falsy, not specified, or `/`, returns root entries.
Returns:
- `ExportedAsset[]`: An array of all the assets in the folder. Subfolders are not included.
```APIDOC
res.getChildren(path?: string): ExportedAsset[]
```
--------------------------------
### Calculate and Apply Drag Offsets on ct.js Copy Pickup
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tips-n-tricks/dragging-copies.md
Modifies the drag start logic in the `Frame Start` tab to calculate initial offsets. When dragging begins, `this.xOffset` and `this.yOffset` are computed based on the difference between the pointer's coordinates and the copy's coordinates, ensuring a smooth pick-up.
```js
if (pointer.hovers(this) && actions.PointerAction.pressed) {
this.dragging = true;
this.xOffset = pointer.x - this.x;
this.yOffset = pointer.y - this.y;
}
```
--------------------------------
### Attach particle emitter to game object using emitters.follow
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-polishing-jettycat.md
This code attaches a 'Jet' particle emitter to the current game object (`this`) using the `emitters.follow` method. It ensures the particle effect follows the object's movement and saves a reference to the emitter in `this.jet` for later manipulation.
```JavaScript
this.jet = emitters.follow(this, 'Jet');
```
```CoffeeScript
@jet = emitters.follow this, 'Jet'
```
```Catnip
Create an emitter and followthisJetstore injet
```
--------------------------------
### Change Text to a String Containing a Number in Catnip
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/learn-catnip/introduction.md
This example demonstrates how to concatenate a static string with the result of a numerical calculation within Catnip's visual block environment. It shows the process of combining 'Buy for $' with the product of 'price' and 'discountMod', then converting the final numerical result to a string for display.
```Catnip Blocks
Set text
├── "Buy for $"
└── +
└── to string
├── price
└── ×
└── discountMod
```
--------------------------------
### rooms Object API Reference
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/rooms.md
Comprehensive API documentation for the `rooms` object, detailing its properties and methods for managing game rooms, camera views, and dynamic content loading.
```APIDOC
rooms object:
Description: Manages rooms and current view (camera).
Properties:
current: object
Description: The current room's object.
templates: array
Description: Existing rooms to switch to.
list: object>
Description: Contains arrays of rooms on the current stage, similar to `templates.list`. Useful for managing UI widgets.
Methods:
switch(NewRoomName: string): void
Description: Calls the latest room's `onleave` event and moves to a new room.
Parameters:
NewRoomName: string
Description: The name of the room to switch to.
restart(): void
Description: Calls this room's `onleave` event and restarts it.
clear(): void
Description: Destroys all the existing copies in the room.
remove(room: RoomReference): void
Description: Safely removes a previously appended/prepended room from the stage. Triggers "On Leave" for the room and "On Destroy" for its copies. Sets `this.kill` to `true` in the room's event. Cannot remove `rooms.current`.
Parameters:
room: RoomReference
Description: A reference to the previously created room object.
append(NameOfTheRoom: string, ext?: object): void
Description: Adds a new room to the current stage, placing it above all copies. Useful for reusing UI, backgrounds, and environment effects. Layers will have a different draw stack than the main room.
Parameters:
NameOfTheRoom: string
Description: The name of the room to append.
ext: object (optional)
Description: Additional parameters to apply to the new room (e.g., `{color: 0x446ADB}`, `{isUi: true}`). These become `this.property` in the new room's events.
prepend(NameOfTheRoom: string, ext?: object): void
Description: Adds a new room to the current stage, placing it behind all copies. Similar to `append`.
Parameters:
NameOfTheRoom: string
Description: The name of the room to prepend.
ext: object (optional)
Description: Additional parameters to apply to the new room.
merge(NameOfTheRoom: string): {copies: array, tileLayers: array, backgrounds: array}
Description: Puts all entities (copies, tile layers, backgrounds) of the given room into the current one. Useful for prefabs and procedural generation. "On Create" and other room events are NOT called. The returned object is for initial setup only and should not be stored to avoid memory leaks.
Parameters:
NameOfTheRoom: string
Description: The name of the room whose entities are to be merged.
Returns: object
Description: An object containing arrays of `copies`, `tileLayers`, and `backgrounds` from the merged room.
```
--------------------------------
### Destroy Enemy Ship Off-Screen (Frame Start Event)
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/tutorials/making-games-shooter.md
Modifies the Frame Start event logic to include a check for the enemy ship's vertical position. If the ship moves beyond the bottom edge of the camera view (plus an 80-pixel buffer), it sets `this.kill = true`, marking the copy for destruction and preventing it from accumulating off-screen.
```JavaScript
this.move();
if (this.y > camera.height + 80) {
this.kill = true;
}
```
```CoffeeScript
@move()
if @y > camera.height + 80
@kill = yes
```
```Catnip
Move this copyIfy>height+
Destroy this copy
```
--------------------------------
### JavaScript Example: Defining Custom Catnip Blocks
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/modding-ctjs/adding-blocks-to-catnip.md
This JavaScript code demonstrates how to define custom blocks for the Catnip library within a `blocks.js` file. It exports an array of block objects, each specifying properties like `name`, `type`, `code`, `icon`, `category`, `pieces` (for arguments and labels), and a `jsTemplate` function that generates the actual JavaScript code for the block's logic. The example includes two 'move' commands with different behaviors.
```JavaScript
module.exports = [{
name: 'Move this copy along a line stopping at',
name_Ru: 'Переместить эту копию по линии, останавливаясь перед',
type: 'command',
code: 'move template bullet',
icon: 'move',
category: 'Movement',
pieces: [{
type: 'argument',
key: 'cgroup',
typeHint: 'string',
required: true
}, {
type: 'filler'
}, {
type: 'label',
name: 'store in',
i18nKey: 'store in'
}, {
type: 'argument',
key: 'return',
typeHint: 'wildcard'
}],
jsTemplate: (values) => {
if (values.return !== 'undefined') {
return `${values.return} = this.moveBullet(${values.cgroup}, ${values.precision || 1});`;
}
return `this.moveBullet(${values.cgroup}, ${values.precision || 1});`;
}
}, {
name: 'Move this copy stopping at',
name_Ru: 'Переместить эту копию, останавливаясь перед',
type: 'command',
code: 'move template smart',
icon: 'move',
category: 'Movement',
pieces: [{
type: 'argument',
key: 'cgroup',
typeHint: 'string',
required: true
}, {
type: 'filler'
}, {
type: 'label',
name: 'store in',
i18nKey: 'store in'
}, {
type: 'argument',
key: 'return',
typeHint: 'wildcard'
}],
jsTemplate: (values) => {
if (values.return !== 'undefined') {
return `${values.return} = this.moveSmart(${values.cgroup}, ${values.precision || 1});`;
}
return `this.moveSmart(${values.cgroup}, ${values.precision || 1});`;
}
}];
```
--------------------------------
### Preload Multiple Sound Assets Concurrently
Source: https://github.com/ct-js/docs.ctjs.rocks/blob/master/docs/sounds.md
Illustrates how to preload an array of sound assets ('AmbientMusic', 'BattleMusic', 'VictoryMusic') concurrently using `Promise.all()` with `sounds.load()`. This ensures that all specified sounds are loaded before proceeding to switch to 'MainRoom', optimizing game flow.
```JavaScript
var soundsToLoad = [],
soundsNames = ['AmbientMusic', 'BattleMusic', 'VictoryMusic'];
for (var sound of soundsNames) {
soundsToLoad.push(sounds.load(sound));
}
Promise.all(soundsToLoad).then(() => {
rooms.switch('MainRoom');
});
```
```CoffeeScript
soundsToLoad = []
for sound in ['AmbientMusic', 'BattleMusic', 'VictoryMusic']
soundsToLoad.push sounds.load sound
Promise.all soundsToLoad
.then =>
rooms.switch 'MainRoom'
```