diff --git a/docs/Audio.html b/docs/Audio.html index 4ac6ef15..dac32695 100644 --- a/docs/Audio.html +++ b/docs/Audio.html @@ -1,3 +1,3 @@ Namespace: Audio
On this page

Audio

LittleJS Audio System

  • ZzFX Sound Effects - Sound Effect Generator
  • ZzFXM Music - Music System
  • Caches sounds and music for fast playback
  • Can attenuate and apply stereo panning to sounds
  • Ability to play mp3, ogg, and wave files
  • Speech synthesis wrapper functions

Members

(static) audioContext

Audio context used by the engine

(static, constant) zzfxR

Sample rate used for all ZzFX sounds

Default Value
  • 44100

Methods

(static) getNoteFrequency(semitoneOffset, rootNoteFrequencyopt) → {Number}

Get frequency of a note on a musical scale

Parameters:
NameTypeAttributesDefaultDescription
semitoneOffsetNumber

How many semitones away from the root note

rootNoteFrequencyNumber<optional>
220

Frequency at semitone offset 0

Returns:
  • The frequency of the note
Type: 
Number

(static) playAudioFile(url, volumeopt, loopopt) → {HTMLAudioElement}

Play an mp3 or wav audio from a local file or url

Parameters:
NameTypeAttributesDefaultDescription
urlString

Location of sound file to play

volumeNumber<optional>
1

How much to scale volume by

loopBoolean<optional>
1

True if the music should loop when it reaches the end

Returns:
  • The audio element for this sound
Type: 
HTMLAudioElement

(static) playSamples(sampleChannels, volumeopt, rateopt, panopt, loopopt) → {AudioBufferSourceNode}

Play cached audio samples with given settings

Parameters:
NameTypeAttributesDefaultDescription
sampleChannelsArray

Array of arrays of samples to play (for stereo playback)

volumeNumber<optional>
1

How much to scale volume by

rateNumber<optional>
1

The playback rate to use

panNumber<optional>
0

How much to apply stereo panning

loopBoolean<optional>
0

True if the sound should loop when it reaches the end

Returns:
  • The audio node of the sound played
Type: 
AudioBufferSourceNode

(static) speak(text, languageopt, volumeopt, rateopt, pitchopt) → {SpeechSynthesisUtterance}

Speak text with passed in settings

Parameters:
NameTypeAttributesDefaultDescription
textString

The text to speak

languageString<optional>

The language/accent to use (examples: en, it, ru, ja, zh)

volumeNumber<optional>
1

How much to scale volume by

rateNumber<optional>
1

How quickly to speak

pitchNumber<optional>
1

How much to change the pitch by

Returns:
  • The utterance that was spoken
Type: 
SpeechSynthesisUtterance

(static) speakStop()

Stop all queued speech

(static) zzfx(…zzfxSound) → {AudioBufferSourceNode}

Generate and play a ZzFX sound

Create sounds using the ZzFX Sound Designer.

Parameters:
NameTypeAttributesDescription
zzfxSoundArray<repeatable>

Array of ZzFX parameters, ex. [.5,.5]

Returns:
  • The audio node of the sound played
Type: 
AudioBufferSourceNode

(static) zzfxG(volumeopt, randomnessopt, frequencyopt, attackopt, sustainopt, releaseopt, shapeopt, shapeCurveopt, slideopt, deltaSlideopt, pitchJumpopt, pitchJumpTimeopt, repeatTimeopt, noiseopt, modulationopt, bitCrushopt, delayopt, sustainVolumeopt, decayopt, tremoloopt) → {Array}

Generate samples for a ZzFX sound

Parameters:
NameTypeAttributesDefaultDescription
volumeNumber<optional>
1

Volume scale (percent)

randomnessNumber<optional>
.05

How much to randomize frequency (percent Hz)

frequencyNumber<optional>
220

Frequency of sound (Hz)

attackNumber<optional>
0

Attack time, how fast sound starts (seconds)

sustainNumber<optional>
0

Sustain time, how long sound holds (seconds)

releaseNumber<optional>
.1

Release time, how fast sound fades out (seconds)

shapeNumber<optional>
0

Shape of the sound wave

shapeCurveNumber<optional>
1

Squarenes of wave (0=square, 1=normal, 2=pointy)

slideNumber<optional>
0

How much to slide frequency (kHz/s)

deltaSlideNumber<optional>
0

How much to change slide (kHz/s/s)

pitchJumpNumber<optional>
0

Frequency of pitch jump (Hz)

pitchJumpTimeNumber<optional>
0

Time of pitch jump (seconds)

repeatTimeNumber<optional>
0

Resets some parameters periodically (seconds)

noiseNumber<optional>
0

How much random noise to add (percent)

modulationNumber<optional>
0

Frequency of modulation wave, negative flips phase (Hz)

bitCrushNumber<optional>
0

Resamples at a lower frequency in (samples*100)

delayNumber<optional>
0

Overlap sound with itself for reverb and flanger effects (seconds)

sustainVolumeNumber<optional>
1

Volume level for sustain (percent)

decayNumber<optional>
0

Decay time, how long to reach sustain after attack (seconds)

tremoloNumber<optional>
0

Trembling effect, rate controlled by repeat time (precent)

Returns:
  • Array of audio samples
Type: 
Array

(static) zzfxM(instruments, patterns, sequence, BPMopt) → {Array}

Generate samples for a ZzFM song with given parameters

Parameters:
NameTypeAttributesDefaultDescription
instrumentsArray

Array of ZzFX sound paramaters

patternsArray

Array of pattern data

sequenceArray

Array of pattern indexes

BPMNumber<optional>
125

Playback speed of the song in BPM

Returns:
  • Left and right channel sample data
Type: 
Array
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Audio

LittleJS Audio System

  • ZzFX Sound Effects - ZzFX Sound Effect Generator
  • ZzFXM Music - ZzFXM Music System
  • Caches sounds and music for fast playback
  • Can attenuate and apply stereo panning to sounds
  • Ability to play mp3, ogg, and wave files
  • Speech synthesis functions

Members

(static) audioContext

Audio context used by the engine

(static, constant) zzfxR

Sample rate used for all ZzFX sounds

Default Value
  • 44100

Methods

(static) getNoteFrequency(semitoneOffset, rootNoteFrequencyopt) → {Number}

Get frequency of a note on a musical scale

Parameters:
NameTypeAttributesDefaultDescription
semitoneOffsetNumber

How many semitones away from the root note

rootNoteFrequencyNumber<optional>
220

Frequency at semitone offset 0

Returns:
  • The frequency of the note
Type: 
Number

(static) playAudioFile(url, volumeopt, loopopt) → {HTMLAudioElement}

Play an mp3 or wav audio from a local file or url

Parameters:
NameTypeAttributesDefaultDescription
urlString

Location of sound file to play

volumeNumber<optional>
1

How much to scale volume by

loopBoolean<optional>
1

True if the music should loop when it reaches the end

Returns:
  • The audio element for this sound
Type: 
HTMLAudioElement

(static) playSamples(sampleChannels, volumeopt, rateopt, panopt, loopopt) → {AudioBufferSourceNode}

Play cached audio samples with given settings

Parameters:
NameTypeAttributesDefaultDescription
sampleChannelsArray

Array of arrays of samples to play (for stereo playback)

volumeNumber<optional>
1

How much to scale volume by

rateNumber<optional>
1

The playback rate to use

panNumber<optional>
0

How much to apply stereo panning

loopBoolean<optional>
0

True if the sound should loop when it reaches the end

Returns:
  • The audio node of the sound played
Type: 
AudioBufferSourceNode

(static) speak(text, languageopt, volumeopt, rateopt, pitchopt) → {SpeechSynthesisUtterance}

Speak text with passed in settings

Parameters:
NameTypeAttributesDefaultDescription
textString

The text to speak

languageString<optional>

The language/accent to use (examples: en, it, ru, ja, zh)

volumeNumber<optional>
1

How much to scale volume by

rateNumber<optional>
1

How quickly to speak

pitchNumber<optional>
1

How much to change the pitch by

Returns:
  • The utterance that was spoken
Type: 
SpeechSynthesisUtterance

(static) speakStop()

Stop all queued speech

(static) zzfx(…zzfxSound) → {AudioBufferSourceNode}

Generate and play a ZzFX sound

Create sounds using the ZzFX Sound Designer.

Parameters:
NameTypeAttributesDescription
zzfxSoundArray<repeatable>

Array of ZzFX parameters, ex. [.5,.5]

Returns:
  • The audio node of the sound played
Type: 
AudioBufferSourceNode

(static) zzfxG(volumeopt, randomnessopt, frequencyopt, attackopt, sustainopt, releaseopt, shapeopt, shapeCurveopt, slideopt, deltaSlideopt, pitchJumpopt, pitchJumpTimeopt, repeatTimeopt, noiseopt, modulationopt, bitCrushopt, delayopt, sustainVolumeopt, decayopt, tremoloopt) → {Array}

Generate samples for a ZzFX sound

Parameters:
NameTypeAttributesDefaultDescription
volumeNumber<optional>
1

Volume scale (percent)

randomnessNumber<optional>
.05

How much to randomize frequency (percent Hz)

frequencyNumber<optional>
220

Frequency of sound (Hz)

attackNumber<optional>
0

Attack time, how fast sound starts (seconds)

sustainNumber<optional>
0

Sustain time, how long sound holds (seconds)

releaseNumber<optional>
.1

Release time, how fast sound fades out (seconds)

shapeNumber<optional>
0

Shape of the sound wave

shapeCurveNumber<optional>
1

Squarenes of wave (0=square, 1=normal, 2=pointy)

slideNumber<optional>
0

How much to slide frequency (kHz/s)

deltaSlideNumber<optional>
0

How much to change slide (kHz/s/s)

pitchJumpNumber<optional>
0

Frequency of pitch jump (Hz)

pitchJumpTimeNumber<optional>
0

Time of pitch jump (seconds)

repeatTimeNumber<optional>
0

Resets some parameters periodically (seconds)

noiseNumber<optional>
0

How much random noise to add (percent)

modulationNumber<optional>
0

Frequency of modulation wave, negative flips phase (Hz)

bitCrushNumber<optional>
0

Resamples at a lower frequency in (samples*100)

delayNumber<optional>
0

Overlap sound with itself for reverb and flanger effects (seconds)

sustainVolumeNumber<optional>
1

Volume level for sustain (percent)

decayNumber<optional>
0

Decay time, how long to reach sustain after attack (seconds)

tremoloNumber<optional>
0

Trembling effect, rate controlled by repeat time (precent)

Returns:
  • Array of audio samples
Type: 
Array

(static) zzfxM(instruments, patterns, sequence, BPMopt) → {Array}

Generate samples for a ZzFM song with given parameters

Parameters:
NameTypeAttributesDefaultDescription
instrumentsArray

Array of ZzFX sound paramaters

patternsArray

Array of pattern data

sequenceArray

Array of pattern indexes

BPMNumber<optional>
125

Playback speed of the song in BPM

Returns:
  • Left and right channel sample data
Type: 
Array
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Color.html b/docs/Color.html index 9948a719..d6039f18 100644 --- a/docs/Color.html +++ b/docs/Color.html @@ -1,3 +1,3 @@ Class: Color
On this page

Color

Color object (red, green, blue, alpha) with some helpful functions

Constructor

new Color(ropt, gopt, bopt, aopt)

Create a color with the rgba components passed in, white by default

Parameters:
NameTypeAttributesDefaultDescription
rNumber<optional>
1

red

gNumber<optional>
1

green

bNumber<optional>
1

blue

aNumber<optional>
1

alpha

Example
let a = new Color;              // white
let b = new Color(1, 0, 0);     // red
let c = new Color(0, 0, 0, 0);  // transparent black
let d = RGB(0, 0, 1);           // blue using rgb color
let e = HSL(.3, 1, .5);         // green using hsl color

Members

a

Properties
TypeDescription
Number

Alpha

b

Properties
TypeDescription
Number

Blue

g

Properties
TypeDescription
Number

Green

r

Properties
TypeDescription
Number

Red

Methods

add(c) → {Color}

Returns a copy of this color plus the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

clamp() → {Color}

Returns a copy of this color clamped to the valid range between 0 and 1

Returns:
Type: 
Color

copy() → {Color}

Returns a new color that is a copy of this

Returns:
Type: 
Color

divide(c) → {Color}

Returns a copy of this color divided by the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

getHSLA() → {Array}

Returns this color expressed in hsla format

Returns:
Type: 
Array

lerp(c, percent) → {Color}

Returns a new color that is p percent between this and the color passed in

Parameters:
NameTypeDescription
cColor

other color

percentNumber
Returns:
Type: 
Color

multiply(c) → {Color}

Returns a copy of this color times the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

mutate(amountopt, alphaAmountopt) → {Color}

Returns a new color that has each component randomly adjusted

Parameters:
NameTypeAttributesDefaultDescription
amountNumber<optional>
.05
alphaAmountNumber<optional>
0
Returns:
Type: 
Color

rgbaInt() → {Number}

Returns this color expressed as 32 bit RGBA value

Returns:
Type: 
Number

scale(scale, alphaScaleopt) → {Color}

Returns a copy of this color scaled by the value passed in, alpha can be scaled separately

Parameters:
NameTypeAttributesDefaultDescription
scaleNumber
alphaScaleNumber<optional>
scale
Returns:
Type: 
Color

setHSLA(hopt, sopt, lopt, aopt) → {Color}

Sets this color given a hue, saturation, lightness, and alpha

Parameters:
NameTypeAttributesDefaultDescription
hNumber<optional>
0

hue

sNumber<optional>
0

saturation

lNumber<optional>
1

lightness

aNumber<optional>
1

alpha

Returns:
Type: 
Color

setHex(hex) → {Color}

Set this color from a hex code

Parameters:
NameTypeDescription
hexString

html hex code

Returns:
Type: 
Color

subtract(c) → {Color}

Returns a copy of this color minus the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

toString(useAlphaopt) → {String}

Returns this color expressed as a hex color code

Parameters:
NameTypeAttributesDefaultDescription
useAlphaBoolean<optional>
1

if alpha should be included in result

Returns:
Type: 
String
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Color

Color object (red, green, blue, alpha) with some helpful functions

Constructor

new Color(ropt, gopt, bopt, aopt)

Create a color with the rgba components passed in, white by default

Parameters:
NameTypeAttributesDefaultDescription
rNumber<optional>
1

red

gNumber<optional>
1

green

bNumber<optional>
1

blue

aNumber<optional>
1

alpha

Example
let a = new Color;              // white
let b = new Color(1, 0, 0);     // red
let c = new Color(0, 0, 0, 0);  // transparent black
let d = RGB(0, 0, 1);           // blue using rgb color
let e = HSL(.3, 1, .5);         // green using hsl color

Members

a

Properties
TypeDescription
Number

Alpha

b

Properties
TypeDescription
Number

Blue

g

Properties
TypeDescription
Number

Green

r

Properties
TypeDescription
Number

Red

Methods

add(c) → {Color}

Returns a copy of this color plus the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

clamp() → {Color}

Returns a copy of this color clamped to the valid range between 0 and 1

Returns:
Type: 
Color

copy() → {Color}

Returns a new color that is a copy of this

Returns:
Type: 
Color

divide(c) → {Color}

Returns a copy of this color divided by the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

getHSLA() → {Array}

Returns this color expressed in hsla format

Returns:
Type: 
Array

lerp(c, percent) → {Color}

Returns a new color that is p percent between this and the color passed in

Parameters:
NameTypeDescription
cColor

other color

percentNumber
Returns:
Type: 
Color

multiply(c) → {Color}

Returns a copy of this color times the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

mutate(amountopt, alphaAmountopt) → {Color}

Returns a new color that has each component randomly adjusted

Parameters:
NameTypeAttributesDefaultDescription
amountNumber<optional>
.05
alphaAmountNumber<optional>
0
Returns:
Type: 
Color

rgbaInt() → {Number}

Returns this color expressed as 32 bit RGBA value

Returns:
Type: 
Number

scale(scale, alphaScaleopt) → {Color}

Returns a copy of this color scaled by the value passed in, alpha can be scaled separately

Parameters:
NameTypeAttributesDefaultDescription
scaleNumber
alphaScaleNumber<optional>
scale
Returns:
Type: 
Color

setHSLA(hopt, sopt, lopt, aopt) → {Color}

Sets this color given a hue, saturation, lightness, and alpha

Parameters:
NameTypeAttributesDefaultDescription
hNumber<optional>
0

hue

sNumber<optional>
0

saturation

lNumber<optional>
1

lightness

aNumber<optional>
1

alpha

Returns:
Type: 
Color

setHex(hex) → {Color}

Set this color from a hex code

Parameters:
NameTypeDescription
hexString

html hex code

Returns:
Type: 
Color

subtract(c) → {Color}

Returns a copy of this color minus the color passed in

Parameters:
NameTypeDescription
cColor

other color

Returns:
Type: 
Color

toString(useAlphaopt) → {String}

Returns this color expressed as a hex color code

Parameters:
NameTypeAttributesDefaultDescription
useAlphaBoolean<optional>
1

if alpha should be included in result

Returns:
Type: 
String
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Debug.html b/docs/Debug.html index 7e6a7090..bfe59c81 100644 --- a/docs/Debug.html +++ b/docs/Debug.html @@ -1,3 +1,3 @@ Namespace: Debug
On this page

Debug

LittleJS Debug System

  • Press ~ to show debug overlay with mouse pick
  • Number keys toggle debug functions
  • +/- apply time scale
  • Debug primitive rendering
  • Save a 2d canvas as an image

Members

(static, constant) debug :Boolean

True if debug is enabled

Type:
  • Boolean
Default Value
  • 1

(static) debugKey :Boolean

Key code used to toggle debug mode, Esc by default

Type:
  • Boolean
Default Value
  • 27

(static, constant) debugPointSize :Number

Size to render debug points by default

Type:
  • Number
Default Value
  • 0.5

(static, constant) enableAsserts :Boolean

True if asserts are enaled

Type:
  • Boolean
Default Value
  • 1

(static) showWatermark :Boolean

True if watermark with FPS should be shown, false in release builds

Type:
  • Boolean
Default Value
  • 1

Methods

(static) ASSERT(assertion, output)

Asserts if the experssion is false, does not do anything in release builds

Parameters:
NameTypeDescription
assertionBoolean
outputObject

(static) debugAABB(posA, sizeA, posB, sizeB, coloropt)

Draw a debug axis aligned bounding box in world space

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
sizeAVector2
posBVector2
sizeBVector2
colorString<optional>
'#fff'

(static) debugCircle(pos, radiusopt, coloropt, timeopt, fillopt)

Draw a debug circle in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
radiusNumber<optional>
0
colorString<optional>
'#fff'
timeNumber<optional>
0
fillBoolean<optional>
false

(static) debugClear()

Clear all debug primitives in the list

(static) debugLine(posA, posB, coloropt, thicknessopt, timeopt)

Draw a debug line in world space

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
posBVector2
colorString<optional>
'#fff'
thicknessNumber<optional>
.1
timeNumber<optional>
0

(static) debugPoint(pos, coloropt, timeopt, angleopt)

Draw a debug point in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0

(static) debugRect(pos, sizeopt, coloropt, timeopt, angleopt, fillopt)

Draw a debug rectangle in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2()
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0
fillBoolean<optional>
false

(static) debugSaveCanvas(canvas, filenameopt)

Save a canvas to disk

Parameters:
NameTypeAttributesDescription
canvasHTMLCanvasElement
filenameString<optional>

(static) debugText(text, pos, sizeopt, coloropt, timeopt, angleopt, fontopt)

Draw a debug axis aligned bounding box in world space

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0
fontString<optional>
'monospace'

(static) setDebugKey(key)

Set key code used to toggle debug mode, Esc by default

Parameters:
NameTypeDescription
keyNumber

(static) setShowWatermark(show)

Set if watermark with FPS should be shown

Parameters:
NameTypeDescription
showBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Debug

LittleJS Debug System

  • Press Esc to show debug overlay with mouse pick
  • Number keys toggle debug functions
  • +/- apply time scale
  • Debug primitive rendering
  • Save a 2d canvas as a png image

Members

(static, constant) debug :Boolean

True if debug is enabled

Type:
  • Boolean
Default Value
  • 1

(static) debugKey :Boolean

Key code used to toggle debug mode, Esc by default

Type:
  • Boolean
Default Value
  • 27

(static, constant) debugPointSize :Number

Size to render debug points by default

Type:
  • Number
Default Value
  • 0.5

(static, constant) enableAsserts :Boolean

True if asserts are enaled

Type:
  • Boolean
Default Value
  • 1

(static) showWatermark :Boolean

True if watermark with FPS should be shown, false in release builds

Type:
  • Boolean
Default Value
  • 1

Methods

(static) ASSERT(assertion, output)

Asserts if the experssion is false, does not do anything in release builds

Parameters:
NameTypeDescription
assertionBoolean
outputObject

(static) debugAABB(posA, sizeA, posB, sizeB, coloropt)

Draw a debug axis aligned bounding box in world space

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
sizeAVector2
posBVector2
sizeBVector2
colorString<optional>
'#fff'

(static) debugCircle(pos, radiusopt, coloropt, timeopt, fillopt)

Draw a debug circle in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
radiusNumber<optional>
0
colorString<optional>
'#fff'
timeNumber<optional>
0
fillBoolean<optional>
false

(static) debugClear()

Clear all debug primitives in the list

(static) debugLine(posA, posB, coloropt, thicknessopt, timeopt)

Draw a debug line in world space

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
posBVector2
colorString<optional>
'#fff'
thicknessNumber<optional>
.1
timeNumber<optional>
0

(static) debugPoint(pos, coloropt, timeopt, angleopt)

Draw a debug point in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0

(static) debugRect(pos, sizeopt, coloropt, timeopt, angleopt, fillopt)

Draw a debug rectangle in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2()
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0
fillBoolean<optional>
false

(static) debugSaveCanvas(canvas, filenameopt, typeopt)

Save a canvas to disk

Parameters:
NameTypeAttributesDefaultDescription
canvasHTMLCanvasElement
filenameString<optional>
typeString<optional>
'image/png'

(static) debugSaveDataURL(dataURL, filename)

Save a data url to disk

Parameters:
NameTypeDescription
dataURLString
filenameString

(static) debugSaveText(text, filenameopt, typeopt)

Save a text file to disk

Parameters:
NameTypeAttributesDefaultDescription
textString
filenameString<optional>
typeString<optional>
'text/plain'

(static) debugText(text, pos, sizeopt, coloropt, timeopt, angleopt, fontopt)

Draw a debug axis aligned bounding box in world space

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorString<optional>
'#fff'
timeNumber<optional>
0
angleNumber<optional>
0
fontString<optional>
'monospace'

(static) setDebugKey(key)

Set key code used to toggle debug mode, Esc by default

Parameters:
NameTypeDescription
keyNumber

(static) setShowWatermark(show)

Set if watermark with FPS should be shown

Parameters:
NameTypeDescription
showBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Draw.html b/docs/Draw.html index fdfa80c2..15877456 100644 --- a/docs/Draw.html +++ b/docs/Draw.html @@ -1,3 +1,3 @@ Namespace: Draw
On this page

Draw

LittleJS Drawing System

  • Hybrid with both Canvas2D and WebGL available
  • Super fast tile sheet rendering with WebGL
  • Can apply rotation, mirror, color and additive color
  • Many useful utility functions

LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL. There are 3 canvas/contexts available to draw to... mainCanvas - 2D background canvas, non WebGL stuff like tile layers are drawn here. glCanvas - Used by the accelerated WebGL batch rendering system. overlayCanvas - Another 2D canvas that appears on top of the other 2 canvases.

The WebGL rendering system is very fast with some caveats...

  • The default setup supports only 1 tile sheet, to support more call glCreateTexture and glSetTexture
  • Switching blend modes (additive) or textures causes another draw call which is expensive in excess
  • Group additive rendering together using renderOrder to mitigate this issue

The LittleJS rendering solution is intentionally simple, feel free to adjust it for your needs!

Members

(static) mainCanvas :HTMLCanvasElement

The primary 2D canvas visible to the user

Type:
  • HTMLCanvasElement

(static) mainCanvasSize :Vector2

The size of the main canvas (and other secondary canvases)

Type:

(static) mainContext :CanvasRenderingContext2D

2d context for mainCanvas

Type:
  • CanvasRenderingContext2D

(static) overlayCanvas :HTMLCanvasElement

A canvas that appears on top of everything the same size as mainCanvas

Type:
  • HTMLCanvasElement

(static) overlayContext :CanvasRenderingContext2D

2d context for overlayCanvas

Type:
  • CanvasRenderingContext2D

(static, constant) tileImage :CanvasImageSource

Tile sheet for batch rendering system

Type:
  • CanvasImageSource

Methods

(static) drawCanvas2D(pos, size, angle, mirror, drawFunction, contextopt)

Draw directly to a 2d canvas context in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2
angleNumber
mirrorBoolean
drawFunctionfunction
contextCanvasRenderingContext2D<optional>
mainContext

(static) drawLine(posA, posB, thicknessopt, coloropt, useWebGLopt)

Draw colored line between two points

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
posBVector2
thicknessNumber<optional>
.1
colorColor<optional>
Color()
useWebGLBoolean<optional>
glEnable

(static) drawRect(pos, sizeopt, coloropt, angleopt, useWebGLopt)

Draw colored rect centered on pos

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
colorColor<optional>
Color()
angleNumber<optional>
0
useWebGLBoolean<optional>
glEnable

(static) drawRectScreenSpace(pos, sizeopt, coloropt, angleopt, useWebGLopt)

Draw colored rectangle in screen space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
colorColor<optional>
Color()
angleNumber<optional>
0
useWebGLBoolean<optional>
glEnable

(static) drawText(text, pos, sizeopt, coloropt, lineWidthopt, lineColoropt, textAlignopt, fontopt, contextopt)

Draw text on overlay canvas in world space Automatically splits new lines into rows

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorColor<optional>
Color()
lineWidthNumber<optional>
0
lineColorColor<optional>
Color(0,0,0)
textAlignString<optional>
'center'
fontString<optional>
fontDefault
contextCanvasRenderingContext2D<optional>
overlayContext

(static) drawTextScreen(text, pos, sizeopt, coloropt, lineWidthopt, lineColoropt, textAlignopt, fontopt, contextopt)

Draw text on overlay canvas in screen space Automatically splits new lines into rows

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorColor<optional>
Color()
lineWidthNumber<optional>
0
lineColorColor<optional>
Color(0,0,0)
textAlignString<optional>
'center'
fontString<optional>
fontDefault
contextCanvasRenderingContext2D<optional>
overlayContext

(static) drawTile(pos, sizeopt, tileIndexopt, tileSizeopt, coloropt, angleopt, mirroropt, additiveColoropt, useWebGLopt)

Draw textured tile centered in world space, with color applied if using WebGL

Parameters:
NameTypeAttributesDefaultDescription
posVector2

Center of the tile in world space

sizeVector2<optional>
Vector2(1,1)

Size of the tile in world space

tileIndexNumber<optional>
-1

Tile index to use, negative is untextured

tileSizeVector2<optional>
tileSizeDefault

Tile size in source pixels

colorColor<optional>
Color()

Color to modulate with

angleNumber<optional>
0

Angle to rotate by

mirrorBoolean<optional>
0

If true image is flipped along the Y axis

additiveColorColor<optional>
Color(0,0,0,0)

Additive color to be applied

useWebGLBoolean<optional>
glEnable

Use accelerated WebGL rendering

(static) drawTileScreenSpace(pos, sizeopt, tileIndexopt, tileSizeopt, coloropt, angleopt, mirroropt, additiveColoropt, useWebGLopt)

Draw textured tile centered on pos in screen space

Parameters:
NameTypeAttributesDefaultDescription
posVector2

Center of the tile

sizeVector2<optional>
Vector2(1,1)

Size of the tile

tileIndexNumber<optional>
-1

Tile index to use, negative is untextured

tileSizeVector2<optional>
tileSizeDefault

Tile size in source pixels

colorColor<optional>
Color()
angleNumber<optional>
0
mirrorBoolean<optional>
0
additiveColorColor<optional>
Color(0,0,0,0)
useWebGLBoolean<optional>
glEnable

(static) isFullscreen() → {Boolean}

Returns true if fullscreen mode is active

Returns:
Type: 
Boolean

(static) screenToWorld(screenPos) → {Vector2}

Convert from screen to world space coordinates

  • if calling outside of render, you may need to manually set mainCanvasSize
Parameters:
NameTypeDescription
screenPosVector2
Returns:
Type: 
Vector2

(static) setBlendMode(additiveopt, useWebGLopt)

Enable normal or additive blend mode

Parameters:
NameTypeAttributesDefaultDescription
additiveBoolean<optional>
0
useWebGLBoolean<optional>
glEnable

(static) toggleFullscreen()

Toggle fullsceen mode

(static) worldToScreen(worldPos) → {Vector2}

Convert from world to screen space coordinates

  • if calling outside of render, you may need to manually set mainCanvasSize
Parameters:
NameTypeDescription
worldPosVector2
Returns:
Type: 
Vector2
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Draw

LittleJS Drawing System

  • Hybrid system with both Canvas2D and WebGL available
  • Super fast tile sheet rendering with WebGL
  • Can apply rotation, mirror, color and additive color
  • Font rendering system with built in engine font
  • Many useful utility functions

LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL. There are 3 canvas/contexts available to draw to... mainCanvas - 2D background canvas, non WebGL stuff like tile layers are drawn here. glCanvas - Used by the accelerated WebGL batch rendering system. overlayCanvas - Another 2D canvas that appears on top of the other 2 canvases.

The WebGL rendering system is very fast with some caveats...

  • Switching blend modes (additive) or textures causes another draw call which is expensive in excess
  • Group additive rendering together using renderOrder to mitigate this issue

The LittleJS rendering solution is intentionally simple, feel free to adjust it for your needs!

Members

(static) mainCanvas :HTMLCanvasElement

The primary 2D canvas visible to the user

Type:
  • HTMLCanvasElement

(static) mainCanvasSize :Vector2

The size of the main canvas (and other secondary canvases)

Type:

(static) mainContext :CanvasRenderingContext2D

2d context for mainCanvas

Type:
  • CanvasRenderingContext2D

(static) overlayCanvas :HTMLCanvasElement

A canvas that appears on top of everything the same size as mainCanvas

Type:
  • HTMLCanvasElement

(static) overlayContext :CanvasRenderingContext2D

2d context for overlayCanvas

Type:
  • CanvasRenderingContext2D

(static, constant) tileImage :CanvasImageSource

Tile sheet for batch rendering system

Type:
  • CanvasImageSource

Methods

(static) drawCanvas2D(pos, size, angle, mirror, drawFunction, contextopt, screenSpaceopt)

Draw directly to a 2d canvas context in world space

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2
angleNumber
mirrorBoolean
drawFunctionfunction
contextCanvasRenderingContext2D<optional>
mainContext
screenSpaceBoolean<optional>
0

(static) drawLine(posA, posB, thicknessopt, coloropt, useWebGLopt, screenSpaceopt)

Draw colored line between two points

Parameters:
NameTypeAttributesDefaultDescription
posAVector2
posBVector2
thicknessNumber<optional>
.1
colorColor<optional>
Color()
useWebGLBoolean<optional>
glEnable
screenSpaceBoolean<optional>
0

(static) drawPoly(points, coloropt, useWebGLopt, screenSpaceopt)

Draw colored polygon using passed in points

Parameters:
NameTypeAttributesDefaultDescription
pointsArray

Array of Vector2 points

colorColor<optional>
Color()
useWebGLBoolean<optional>
glEnable
screenSpaceBoolean<optional>
0

(static) drawRect(pos, sizeopt, coloropt, angleopt, useWebGLopt, screenSpaceopt)

Draw colored rect centered on pos

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
colorColor<optional>
Color()
angleNumber<optional>
0
useWebGLBoolean<optional>
glEnable
screenSpaceBoolean<optional>
0

(static) drawText(text, pos, sizeopt, coloropt, lineWidthopt, lineColoropt, textAlignopt, fontopt, contextopt)

Draw text on overlay canvas in world space Automatically splits new lines into rows

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorColor<optional>
Color()
lineWidthNumber<optional>
0
lineColorColor<optional>
Color(0,0,0)
textAlignString<optional>
'center'
fontString<optional>
fontDefault
contextCanvasRenderingContext2D<optional>
overlayContext

(static) drawTextScreen(text, pos, sizeopt, coloropt, lineWidthopt, lineColoropt, textAlignopt, fontopt, contextopt)

Draw text on overlay canvas in screen space Automatically splits new lines into rows

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
sizeNumber<optional>
1
colorColor<optional>
Color()
lineWidthNumber<optional>
0
lineColorColor<optional>
Color(0,0,0)
textAlignString<optional>
'center'
fontString<optional>
fontDefault
contextCanvasRenderingContext2D<optional>
overlayContext

(static) drawTile(pos, sizeopt, tileIndexopt, tileSizeopt, coloropt, angleopt, mirroropt, additiveColoropt, useWebGLopt, screenSpaceopt)

Draw textured tile centered in world space, with color applied if using WebGL

Parameters:
NameTypeAttributesDefaultDescription
posVector2

Center of the tile in world space

sizeVector2<optional>
Vector2(1,1)

Size of the tile in world space

tileIndexNumber<optional>
-1

Tile index to use, negative is untextured

tileSizeVector2<optional>
tileSizeDefault

Tile size in source pixels

colorColor<optional>
Color()

Color to modulate with

angleNumber<optional>
0

Angle to rotate by

mirrorBoolean<optional>
0

If true image is flipped along the Y axis

additiveColorColor<optional>
Color(0,0,0,0)

Additive color to be applied

useWebGLBoolean<optional>
glEnable

Use accelerated WebGL rendering

screenSpaceBoolean<optional>
0

If true the pos and size are in screen space

(static) isFullscreen() → {Boolean}

Returns true if fullscreen mode is active

Returns:
Type: 
Boolean

(static) screenToWorld(screenPos) → {Vector2}

Convert from screen to world space coordinates

Parameters:
NameTypeDescription
screenPosVector2
Returns:
Type: 
Vector2

(static) setBlendMode(additiveopt, useWebGLopt)

Enable normal or additive blend mode

Parameters:
NameTypeAttributesDefaultDescription
additiveBoolean<optional>
0
useWebGLBoolean<optional>
glEnable

(static) toggleFullscreen()

Toggle fullsceen mode

(static) worldToScreen(worldPos) → {Vector2}

Convert from world to screen space coordinates

Parameters:
NameTypeDescription
worldPosVector2
Returns:
Type: 
Vector2
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Engine.html b/docs/Engine.html index 52751510..eb5fe310 100644 --- a/docs/Engine.html +++ b/docs/Engine.html @@ -1,3 +1,3 @@ Namespace: Engine
On this page

Engine

LittleJS - The Tiny JavaScript Game Engine That Can! MIT License - Copyright 2021 Frank Force

Engine Features

  • Object oriented system with base class engine object
  • Base class object handles update, physics, collision, rendering, etc
  • Engine helper classes and functions like Vector2, Color, and Timer
  • Super fast rendering system for tile sheets
  • Sound effects audio with zzfx and music with zzfxm
  • Input processing system with gamepad and touchscreen support
  • Tile layer rendering and collision system
  • Particle effect system
  • Medal system tracks and displays achievements
  • Debug tools and debug rendering system
  • Post processing effects
  • Call engineInit() to start it up!

Members

(static, constant) engineName :String

Name of engine

Type:
  • String
Default Value
  • LittleJS

(static) engineObjects :Array

Array containing all engine objects

Type:
  • Array

(static) engineObjectsCollide :Array

Array containing only objects that are set to collide with other objects this frame (for optimization)

Type:
  • Array

(static, constant) engineVersion :String

Version of engine

Type:
  • String
Default Value
  • 1.6.93

(static) frame :Number

Current update frame, used to calculate time

Type:
  • Number

(static, constant) frameRate :Number

Frames per second to update objects

Type:
  • Number
Default Value
  • 60

(static) paused :Boolean

Is the game paused? Causes time and objects to not be updated

Type:
  • Boolean
Default Value
  • 0

(static) time :Number

Current engine time since start in seconds, derived from frame

Type:
  • Number

(static, constant) timeDelta :Number

How many seconds each frame lasts, engine uses a fixed time step

Type:
  • Number
Default Value
  • 1/60

(static) timeReal :Number

Actual clock time since start in seconds (not affected by pause or frame rate clamping)

Type:
  • Number

Methods

(static) engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, tileImageSourceopt)

Start up LittleJS engine with your callback functions

Parameters:
NameTypeAttributesDescription
gameInitfunction

Called once after the engine starts up, setup the game

gameUpdatefunction

Called every frame at 60 frames per second, handle input and update the game state

gameUpdatePostfunction

Called after physics and objects are updated, setup camera and prepare for render

gameRenderfunction

Called before objects are rendered, draw any background effects that appear behind objects

gameRenderPostfunction

Called after objects are rendered, draw effects or hud that appear above all objects

tileImageSourceString<optional>

Tile image to use, everything starts when the image is finished loading

(static) engineObjectsCallback(posopt, sizeopt, callbackFunctionopt, objectsopt)

Triggers a callback for each object within a given area

Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

Center of test area

sizeNumber<optional>

Radius of circle if float, rectangle size if Vector2

callbackFunctionfunction<optional>

Calls this function on every object that passes the test

objectsArray<optional>
engineObjects

List of objects to check

(static) engineObjectsDestroy()

Destroy and remove all objects

(static) engineObjectsUpdate()

Update each engine object, remove destroyed objects, and update time

(static) setPaused(paused)

Set if game is paused

Parameters:
NameTypeDescription
pausedBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Engine

LittleJS - The Tiny JavaScript Game Engine That Can! MIT License - Copyright 2021 Frank Force

Engine Features

  • Object oriented system with base class engine object
  • Base class object handles update, physics, collision, rendering, etc
  • Engine helper classes and functions like Vector2, Color, and Timer
  • Super fast rendering system for tile sheets
  • Sound effects audio with zzfx and music with zzfxm
  • Input processing system with gamepad and touchscreen support
  • Tile layer rendering and collision system
  • Particle effect system
  • Medal system tracks and displays achievements
  • Debug tools and debug rendering system
  • Post processing effects
  • Call engineInit() to start it up!

Members

(static, constant) engineName :String

Name of engine

Type:
  • String
Default Value
  • LittleJS

(static) engineObjects :Array

Array containing all engine objects

Type:
  • Array

(static) engineObjectsCollide :Array

Array containing only objects that are set to collide with other objects this frame (for optimization)

Type:
  • Array

(static, constant) engineVersion :String

Version of engine

Type:
  • String
Default Value
  • 1.7.12

(static) frame :Number

Current update frame, used to calculate time

Type:
  • Number

(static, constant) frameRate :Number

Frames per second to update objects

Type:
  • Number
Default Value
  • 60

(static) paused :Boolean

Is the game paused? Causes time and objects to not be updated

Type:
  • Boolean
Default Value
  • 0

(static) time :Number

Current engine time since start in seconds, derived from frame

Type:
  • Number

(static, constant) timeDelta :Number

How many seconds each frame lasts, engine uses a fixed time step

Type:
  • Number
Default Value
  • 1/60

(static) timeReal :Number

Actual clock time since start in seconds (not affected by pause or frame rate clamping)

Type:
  • Number

Methods

(static) engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, tileImageSourceopt)

Start up LittleJS engine with your callback functions

Parameters:
NameTypeAttributesDescription
gameInitfunction

Called once after the engine starts up, setup the game

gameUpdatefunction

Called every frame at 60 frames per second, handle input and update the game state

gameUpdatePostfunction

Called after physics and objects are updated, setup camera and prepare for render

gameRenderfunction

Called before objects are rendered, draw any background effects that appear behind objects

gameRenderPostfunction

Called after objects are rendered, draw effects or hud that appear above all objects

tileImageSourceString<optional>

Tile image to use, everything starts when the image is finished loading

(static) engineObjectsCallback(posopt, sizeopt, callbackFunctionopt, objectsopt)

Triggers a callback for each object within a given area

Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

Center of test area

sizeNumber<optional>

Radius of circle if float, rectangle size if Vector2

callbackFunctionfunction<optional>

Calls this function on every object that passes the test

objectsArray<optional>
engineObjects

List of objects to check

(static) engineObjectsDestroy()

Destroy and remove all objects

(static) engineObjectsUpdate()

Update each engine object, remove destroyed objects, and update time

(static) setPaused(paused)

Set if game is paused

Parameters:
NameTypeDescription
pausedBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/EngineObject.html b/docs/EngineObject.html index 4ecf8d0d..67ae16a4 100644 --- a/docs/EngineObject.html +++ b/docs/EngineObject.html @@ -1,3 +1,3 @@ Class: EngineObject
On this page

EngineObject

LittleJS Object Base Object Class

  • Base object class used by the engine
  • Automatically adds self to object list
  • Will be updated and rendered each frame
  • Renders as a sprite from a tilesheet by default
  • Can have color and addtive color applied
  • 2d Physics and collision system
  • Sorted by renderOrder
  • Objects can have children attached
  • Parents are updated before children, and set child transform
  • Call destroy() to get rid of objects

The physics system used by objects is simple and fast with some caveats...

  • Collision uses the axis aligned size, the object's rotation angle is only for rendering
  • Objects are guaranteed to not intersect tile collision from physics
  • If an object starts or is moved inside tile collision, it will not collide with that tile
  • Collision for objects can be set to be solid to block other objects
  • Objects may get pushed into overlapping other solid objects, if so they will push away
  • Solid objects are more performance intensive and should be used sparingly

Constructor

new EngineObject(positionopt, sizeopt, tileIndexopt, tileSizeopt, angleopt, coloropt, renderOrderopt)

Create an engine object and adds it to the list of objects

Parameters:
NameTypeAttributesDefaultDescription
positionVector2<optional>
Vector2()

World space position of the object

sizeVector2<optional>
Vector2(1,1)

World space size of the object

tileIndexNumber<optional>
-1

Tile to use to render object (-1 is untextured)

tileSizeVector2<optional>
tileSizeDefault

Size of tile in source pixels

angleNumber<optional>
0

Angle the object is rotated by

colorColor<optional>
Color()

Color to apply to tile when rendered

renderOrderNumber<optional>
0

Objects sorted by renderOrder before being rendered

Example
// create an engine object, normally you would first extend the class with your own
const pos = vec2(2,3);
const object = new EngineObject(pos); 

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

color

Properties
TypeDescription
Color

Color to apply when rendered

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

EngineObject

LittleJS Object Base Object Class

  • Top level object class used by the engine
  • Automatically adds self to object list
  • Will be updated and rendered each frame
  • Renders as a sprite from a tilesheet by default
  • Can have color and addtive color applied
  • 2D Physics and collision system
  • Sorted by renderOrder
  • Objects can have children attached
  • Parents are updated before children, and set child transform
  • Call destroy() to get rid of objects

The physics system used by objects is simple and fast with some caveats...

  • Collision uses the axis aligned size, the object's rotation angle is only for rendering
  • Objects are guaranteed to not intersect tile collision from physics
  • If an object starts or is moved inside tile collision, it will not collide with that tile
  • Collision for objects can be set to be solid to block other objects
  • Objects may get pushed into overlapping other solid objects, if so they will push away
  • Solid objects are more performance intensive and should be used sparingly

Constructor

new EngineObject(positionopt, sizeopt, tileIndexopt, tileSizeopt, angleopt, coloropt, renderOrderopt)

Create an engine object and adds it to the list of objects

Parameters:
NameTypeAttributesDefaultDescription
positionVector2<optional>
Vector2()

World space position of the object

sizeVector2<optional>
Vector2(1,1)

World space size of the object

tileIndexNumber<optional>
-1

Tile to use to render object (-1 is untextured)

tileSizeVector2<optional>
tileSizeDefault

Size of tile in source pixels

angleNumber<optional>
0

Angle the object is rotated by

colorColor<optional>
Color()

Color to apply to tile when rendered

renderOrderNumber<optional>
0

Objects sorted by renderOrder before being rendered

Example
// create an engine object, normally you would first extend the class with your own
const pos = vec2(2,3);
const object = new EngineObject(pos); 

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

color

Properties
TypeDescription
Color

Color to apply when rendered

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/FontImage.html b/docs/FontImage.html index 853fd576..ca217a3d 100644 --- a/docs/FontImage.html +++ b/docs/FontImage.html @@ -1,3 +1,3 @@ Class: FontImage
On this page

FontImage

Font Image Object - Draw text on a 2D canvas by using characters in an image

  • 96 characters (from space to tilde) are stored in an image
  • Uses a default 8x8 font if none is supplied
  • You can also use fonts from the main tile sheet

Constructor

new FontImage(imageopt, tileSizeopt, paddingSizeopt, startTileIndexopt, contextopt)

Create an image font

Parameters:
NameTypeAttributesDefaultDescription
imageHTMLImageElement<optional>

Image for the font, if undefined default font is used

tileSizeVector2<optional>
vec2(8)

Size of the font source tiles

paddingSizeVector2<optional>
vec2(0,1)

How much extra space to add between characters

startTileIndexNumber<optional>
0

Tile index in image where font starts

contextCanvasRenderingContext2D<optional>
overlayContext

context to draw to

Example
// use built in font
const font = new ImageFont;

// draw text
font.drawTextScreen("LittleJS\nHello World!", vec2(200, 50));

Methods

drawText(text, pos, scaleopt, centeropt)

Draw text in world space using the image font

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
scaleNumber<optional>
.25
centerBoolean<optional>

drawTextScreen(text, pos, scaleopt, centeropt)

Draw text in screen space using the image font

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
scaleNumber<optional>
4
centerBoolean<optional>
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

FontImage

Font Image Object - Draw text on a 2D canvas by using characters in an image

  • 96 characters (from space to tilde) are stored in an image
  • Uses a default 8x8 font if none is supplied
  • You can also use fonts from the main tile sheet

Constructor

new FontImage(imageopt, tileSizeopt, paddingSizeopt, startTileIndexopt, contextopt)

Create an image font

Parameters:
NameTypeAttributesDefaultDescription
imageHTMLImageElement<optional>

Image for the font, if undefined default font is used

tileSizeVector2<optional>
vec2(8)

Size of the font source tiles

paddingSizeVector2<optional>
vec2(0,1)

How much extra space to add between characters

startTileIndexNumber<optional>
0

Tile index in image where font starts

contextCanvasRenderingContext2D<optional>
overlayContext

context to draw to

Example
// use built in font
const font = new ImageFont;

// draw text
font.drawTextScreen("LittleJS\nHello World!", vec2(200, 50));

Methods

drawText(text, pos, scaleopt, centeropt)

Draw text in world space using the image font

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
scaleNumber<optional>
.25
centerBoolean<optional>

drawTextScreen(text, pos, scaleopt, centeropt)

Draw text in screen space using the image font

Parameters:
NameTypeAttributesDefaultDescription
textString
posVector2
scaleNumber<optional>
4
centerBoolean<optional>
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Input.html b/docs/Input.html index 97d96b6a..65db6bc8 100644 --- a/docs/Input.html +++ b/docs/Input.html @@ -1,3 +1,3 @@ Namespace: Input
On this page

Input

LittleJS Input System

  • Tracks key down, pressed, and released
  • Also tracks mouse buttons, position, and wheel
  • Supports multiple gamepads
  • Virtual gamepad for touch devices with touchGamepadSize

Members

(static, constant) isTouchDevice

True if a touch device has been detected

(static) isUsingGamepad :Boolean

Returns true if user is using gamepad (has more recently pressed a gamepad button)

Type:
  • Boolean

(static) mousePos :Vector2

Mouse pos in world space

Type:

(static) mousePosScreen :Vector2

Mouse pos in screen space

Type:

(static) mouseWheel :Number

Mouse wheel delta this frame

Type:
  • Number

(static) preventDefaultInput :Boolean

Prevents input continuing to the default browser handling (false by default)

Type:
  • Boolean

Methods

(static) clearInput()

Clears all input

(static) gamepadIsDown(button, gamepadopt) → {Boolean}

Returns true if gamepad button is down

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) gamepadStick(stick, gamepadopt) → {Vector2}

Returns gamepad stick value

Parameters:
NameTypeAttributesDefaultDescription
stickNumber
gamepadNumber<optional>
0
Returns:
Type: 
Vector2

(static) gamepadWasPressed(button, gamepadopt) → {Boolean}

Returns true if gamepad button was pressed

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) gamepadWasReleased(button, gamepadopt) → {Boolean}

Returns true if gamepad button was released

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyIsDown(key, deviceopt) → {Boolean}

Returns true if device key is down

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyWasPressed(key, deviceopt) → {Boolean}

Returns true if device key was pressed this frame

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyWasReleased(key, deviceopt) → {Boolean}

Returns true if device key was released this frame

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) mouseIsDown(button) → {Boolean}

Returns true if mouse button is down

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) mouseWasPressed(button) → {Boolean}

Returns true if mouse button was pressed

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) mouseWasReleased(button) → {Boolean}

Returns true if mouse button was released

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) vibrate(patternopt)

Pulse the vibration hardware if it exists

Parameters:
NameTypeAttributesDefaultDescription
patternNumber<optional>
100

a single value in miliseconds or vibration interval array

(static) vibrateStop()

Cancel any ongoing vibration

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Input

LittleJS Input System

  • Tracks keyboard down, pressed, and released
  • Tracks mouse buttons, position, and wheel
  • Tracks multiple analog gamepads
  • Virtual gamepad for touch devices

Members

(static, constant) isTouchDevice

True if a touch device has been detected

(static) isUsingGamepad :Boolean

Returns true if user is using gamepad (has more recently pressed a gamepad button)

Type:
  • Boolean

(static) mousePos :Vector2

Mouse pos in world space

Type:

(static) mousePosScreen :Vector2

Mouse pos in screen space

Type:

(static) mouseWheel :Number

Mouse wheel delta this frame

Type:
  • Number

(static) preventDefaultInput :Boolean

Prevents input continuing to the default browser handling (false by default)

Type:
  • Boolean

Methods

(static) clearInput()

Clears all input

(static) gamepadIsDown(button, gamepadopt) → {Boolean}

Returns true if gamepad button is down

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) gamepadStick(stick, gamepadopt) → {Vector2}

Returns gamepad stick value

Parameters:
NameTypeAttributesDefaultDescription
stickNumber
gamepadNumber<optional>
0
Returns:
Type: 
Vector2

(static) gamepadWasPressed(button, gamepadopt) → {Boolean}

Returns true if gamepad button was pressed

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) gamepadWasReleased(button, gamepadopt) → {Boolean}

Returns true if gamepad button was released

Parameters:
NameTypeAttributesDefaultDescription
buttonNumber
gamepadNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyIsDown(key, deviceopt) → {Boolean}

Returns true if device key is down

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyWasPressed(key, deviceopt) → {Boolean}

Returns true if device key was pressed this frame

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) keyWasReleased(key, deviceopt) → {Boolean}

Returns true if device key was released this frame

Parameters:
NameTypeAttributesDefaultDescription
keyNumber
deviceNumber<optional>
0
Returns:
Type: 
Boolean

(static) mouseIsDown(button) → {Boolean}

Returns true if mouse button is down

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) mouseWasPressed(button) → {Boolean}

Returns true if mouse button was pressed

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) mouseWasReleased(button) → {Boolean}

Returns true if mouse button was released

Parameters:
NameTypeDescription
buttonNumber
Returns:
Type: 
Boolean

(static) vibrate(patternopt)

Pulse the vibration hardware if it exists

Parameters:
NameTypeAttributesDefaultDescription
patternNumber<optional>
100

a single value in miliseconds or vibration interval array

(static) vibrateStop()

Cancel any ongoing vibration

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Medal.html b/docs/Medal.html index 3cb176b1..3fbfa1b5 100644 --- a/docs/Medal.html +++ b/docs/Medal.html @@ -1,3 +1,3 @@ Class: Medal
On this page

Medal

Medal Object - Tracks an unlockable medal

Constructor

new Medal(id, name, descriptionopt, iconopt, srcopt)

Create an medal object and adds it to the list of medals

Parameters:
NameTypeAttributesDefaultDescription
idNumber

The unique identifier of the medal

nameString

Name of the medal

descriptionString<optional>

Description of the medal

iconString<optional>
'🏆'

Icon for the medal

srcString<optional>

Image location for the medal

Example
// create a medal
const medal_example = new Medal(0, 'Example Medal', 'More info about the medal goes here.', '🎖️');

// initialize medals
medalsInit('Example Game');

// unlock the medal
medal_example.unlock();

Methods

render(hidePercentopt)

Render a medal

Parameters:
NameTypeAttributesDefaultDescription
hidePercentNumber<optional>
0

How much to slide the medal off screen

renderIcon(x, y, sizeopt)

Render the icon for a medal

Parameters:
NameTypeAttributesDefaultDescription
xNumber

Screen space X position

yNumber

Screen space Y position

sizeNumber<optional>
medalDisplayIconSize

Screen space size

unlock()

Unlocks a medal if not already unlocked

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Medal

Medal Object - Tracks an unlockable medal

Constructor

new Medal(id, name, descriptionopt, iconopt, srcopt)

Create an medal object and adds it to the list of medals

Parameters:
NameTypeAttributesDefaultDescription
idNumber

The unique identifier of the medal

nameString

Name of the medal

descriptionString<optional>

Description of the medal

iconString<optional>
'🏆'

Icon for the medal

srcString<optional>

Image location for the medal

Example
// create a medal
const medal_example = new Medal(0, 'Example Medal', 'More info about the medal goes here.', '🎖️');

// initialize medals
medalsInit('Example Game');

// unlock the medal
medal_example.unlock();

Methods

render(hidePercentopt)

Render a medal

Parameters:
NameTypeAttributesDefaultDescription
hidePercentNumber<optional>
0

How much to slide the medal off screen

renderIcon(x, y, sizeopt)

Render the icon for a medal

Parameters:
NameTypeAttributesDefaultDescription
xNumber

Screen space X position

yNumber

Screen space Y position

sizeNumber<optional>
medalDisplayIconSize

Screen space size

unlock()

Unlocks a medal if not already unlocked

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Medals.html b/docs/Medals.html index 452fd760..837a6304 100644 --- a/docs/Medals.html +++ b/docs/Medals.html @@ -1,3 +1,3 @@ Namespace: Medals
On this page

Medals

LittleJS Medal System

  • Tracks and displays medals
  • Saves medals to local storage
  • Newgrounds integration

Members

(static, constant) medals :Array

List of all medals

Type:
  • Array

Methods

(static) medalsInit(saveName)

Initialize medals with a save name used for storage

  • Call this after creating all medals
  • Checks if medals are unlocked
Parameters:
NameTypeDescription
saveNameString

(static) newgroundsInit(app_id, cipheropt)

This can used to enable Newgrounds functionality

Parameters:
NameTypeAttributesDescription
app_idNumber

The newgrounds App ID

cipherString<optional>

The encryption Key (AES-128/Base64)

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Medals

LittleJS Medal System

  • Tracks and displays medals
  • Saves medals to local storage
  • Newgrounds integration

Members

(static, constant) medals :Array

List of all medals

Type:
  • Array

Methods

(static) medalsInit(saveName)

Initialize medals with a save name used for storage

  • Call this after creating all medals
  • Checks if medals are unlocked
Parameters:
NameTypeDescription
saveNameString

(static) newgroundsInit(app_id, cipheropt)

This can used to enable Newgrounds functionality

Parameters:
NameTypeAttributesDescription
app_idNumber

The newgrounds App ID

cipherString<optional>

The encryption Key (AES-128/Base64)

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Music.html b/docs/Music.html index 7b432ac1..daa17ecb 100644 --- a/docs/Music.html +++ b/docs/Music.html @@ -1,3 +1,3 @@ Class: Music
On this page

Music

Music Object - Stores a zzfx music track for later use

Create music with the ZzFXM tracker.

Constructor

new Music(zzfxMusic)

Create a music object and cache the zzfx music samples for later use

Parameters:
NameTypeDescription
zzfxMusicArray

Array of zzfx music parameters

Example
// create some music
const music_example = new Music(
[
    [                         // instruments
      [,0,400]                // simple note
    ], 
    [                         // patterns
        [                     // pattern 1
            [                 // channel 0
                0, -1,        // instrument 0, left speaker
                1, 0, 9, 1    // channel notes
            ], 
            [                 // channel 1
                0, 1,         // instrument 1, right speaker
                0, 12, 17, -1 // channel notes
            ]
        ],
    ],
    [0, 0, 0, 0], // sequence, play pattern 0 four times
    90            // BPM
]);

// play the music
music_example.play();

Methods

isPlaying() → {Boolean}

Check if music is playing

Returns:
Type: 
Boolean

play(volumeopt, loopopt) → {AudioBufferSourceNode}

Play the music

Parameters:
NameTypeAttributesDefaultDescription
volumeNumber<optional>
1

How much to scale volume by

loopBoolean<optional>
1

True if the music should loop when it reaches the end

Returns:
  • The audio node, can be used to stop sound later
Type: 
AudioBufferSourceNode

stop()

Stop the music

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Music

Music Object - Stores a zzfx music track for later use

Create music with the ZzFXM tracker.

Constructor

new Music(zzfxMusic)

Create a music object and cache the zzfx music samples for later use

Parameters:
NameTypeDescription
zzfxMusicArray

Array of zzfx music parameters

Example
// create some music
const music_example = new Music(
[
    [                         // instruments
      [,0,400]                // simple note
    ], 
    [                         // patterns
        [                     // pattern 1
            [                 // channel 0
                0, -1,        // instrument 0, left speaker
                1, 0, 9, 1    // channel notes
            ], 
            [                 // channel 1
                0, 1,         // instrument 1, right speaker
                0, 12, 17, -1 // channel notes
            ]
        ],
    ],
    [0, 0, 0, 0], // sequence, play pattern 0 four times
    90            // BPM
]);

// play the music
music_example.play();

Methods

isPlaying() → {Boolean}

Check if music is playing

Returns:
Type: 
Boolean

play(volumeopt, loopopt) → {AudioBufferSourceNode}

Play the music

Parameters:
NameTypeAttributesDefaultDescription
volumeNumber<optional>
1

How much to scale volume by

loopBoolean<optional>
1

True if the music should loop when it reaches the end

Returns:
  • The audio node, can be used to stop sound later
Type: 
AudioBufferSourceNode

stop()

Stop the music

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Newgrounds.html b/docs/Newgrounds.html index 97ffb0ac..1ddf65b3 100644 --- a/docs/Newgrounds.html +++ b/docs/Newgrounds.html @@ -1,3 +1,3 @@ Class: Newgrounds
On this page

Newgrounds

Newgrounds API wrapper object

Constructor

new Newgrounds(app_id, cipheropt)

Create a newgrounds object

Parameters:
NameTypeAttributesDescription
app_idNumber

The newgrounds App ID

cipherString<optional>

The encryption Key (AES-128/Base64)

Example
// create a newgrounds object, replace the app id and cipher with your own
const app_id = '53123:1ZuSTQ9l';
const cipher = 'enF0vGH@Mj/FRASKL23Q==';
newgrounds = new Newgrounds(app_id, cipher);

Methods

call(component, parametersopt, asyncopt) → {Object}

Send a message to call a component of the Newgrounds API

Parameters:
NameTypeAttributesDefaultDescription
componentString

Name of the component

parametersObject<optional>
0

Parameters to use for call

asyncBoolean<optional>
0

If true, don't wait for response before continuing (avoid stall)

Returns:
  • The response JSON object
Type: 
Object

getScores(id, useropt, socialopt, skipopt, limitopt) → {Object}

Get scores from a scoreboard

Parameters:
NameTypeAttributesDefaultDescription
idNumber

The scoreboard id

userString<optional>
0

A user's id or name

socialNumber<optional>
0

If true, only social scores will be loaded

skipNumber<optional>
0

Number of scores to skip before start

limitNumber<optional>
10

Number of scores to include in the list

Returns:
  • The response JSON object
Type: 
Object

logView()

Send message to log a view

postScore(id, value)

Send message to post score

Parameters:
NameTypeDescription
idNumber

The scoreboard id

valueNumber

The score value

unlockMedal(id)

Send message to unlock a medal by id

Parameters:
NameTypeDescription
idNumber

The medal id

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Newgrounds

Newgrounds API wrapper object

Constructor

new Newgrounds(app_id, cipheropt)

Create a newgrounds object

Parameters:
NameTypeAttributesDescription
app_idNumber

The newgrounds App ID

cipherString<optional>

The encryption Key (AES-128/Base64)

Example
// create a newgrounds object, replace the app id and cipher with your own
const app_id = '53123:1ZuSTQ9l';
const cipher = 'enF0vGH@Mj/FRASKL23Q==';
newgrounds = new Newgrounds(app_id, cipher);

Methods

call(component, parametersopt, asyncopt) → {Object}

Send a message to call a component of the Newgrounds API

Parameters:
NameTypeAttributesDefaultDescription
componentString

Name of the component

parametersObject<optional>
0

Parameters to use for call

asyncBoolean<optional>
0

If true, don't wait for response before continuing (avoid stall)

Returns:
  • The response JSON object
Type: 
Object

getScores(id, useropt, socialopt, skipopt, limitopt) → {Object}

Get scores from a scoreboard

Parameters:
NameTypeAttributesDefaultDescription
idNumber

The scoreboard id

userString<optional>
0

A user's id or name

socialNumber<optional>
0

If true, only social scores will be loaded

skipNumber<optional>
0

Number of scores to skip before start

limitNumber<optional>
10

Number of scores to include in the list

Returns:
  • The response JSON object
Type: 
Object

logView()

Send message to log a view

postScore(id, value)

Send message to post score

Parameters:
NameTypeDescription
idNumber

The scoreboard id

valueNumber

The score value

unlockMedal(id)

Send message to unlock a medal by id

Parameters:
NameTypeDescription
idNumber

The medal id

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Particle.html b/docs/Particle.html index 6d5d06d0..723f87c5 100644 --- a/docs/Particle.html +++ b/docs/Particle.html @@ -1,3 +1,3 @@ Class: Particle
On this page

Particle

Particle Object - Created automatically by Particle Emitters

Constructor

new Particle(position, tileIndexopt, tileSizeopt, angleopt)

Create a particle with the given settings

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

World space position of the particle

tileIndexNumber<optional>
-1

Tile to use to render, untextured if -1

tileSizeVector2<optional>
tileSizeDefault

Size of tile in source pixels

angleNumber<optional>
0

Angle to rotate the particle

Extends

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

color

Properties
TypeDescription
Color

Color to apply when rendered

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the particle, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Particle

Particle Object - Created automatically by Particle Emitters

Constructor

new Particle(position, tileIndexopt, tileSizeopt, angleopt)

Create a particle with the given settings

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

World space position of the particle

tileIndexNumber<optional>
-1

Tile to use to render, untextured if -1

tileSizeVector2<optional>
tileSizeDefault

Size of tile in source pixels

angleNumber<optional>
0

Angle to rotate the particle

Extends

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

color

Properties
TypeDescription
Color

Color to apply when rendered

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the particle, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/ParticleEmitter.html b/docs/ParticleEmitter.html index 0eb124fe..98932532 100644 --- a/docs/ParticleEmitter.html +++ b/docs/ParticleEmitter.html @@ -1,3 +1,3 @@ Class: ParticleEmitter
On this page

ParticleEmitter

Particle Emitter - Spawns particles with the given settings

Constructor

new ParticleEmitter(position, angleopt, emitSizeopt, emitTimeopt, emitRateopt, emitConeAngleopt, tileIndexopt, tileSizeopt, colorStartAopt, colorStartBopt, colorEndAopt, colorEndBopt, particleTimeopt, sizeStartopt, sizeEndopt, speedopt, angleSpeedopt, dampingopt, angleDampingopt, gravityScaleopt, particleConeAngleopt, fadeRateopt, randomnessopt, collideTilesopt, additiveopt, randomColorLinearopt, renderOrderopt, localSpaceopt)

Create a particle system with the given settings

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

World space position of the emitter

angleNumber<optional>
0

Angle to emit the particles

emitSizeNumber<optional>
0

World space size of the emitter (float for circle diameter, vec2 for rect)

emitTimeNumber<optional>
0

How long to stay alive (0 is forever)

emitRateNumber<optional>
100

How many particles per second to spawn, does not emit if 0

emitConeAngleNumber<optional>
PI

Local angle to apply velocity to particles from emitter

tileIndexNumber<optional>
-1

Index into tile sheet, if <0 no texture is applied

tileSizeVector2<optional>
tileSizeDefault

Tile size for particles

colorStartAColor<optional>
Color()

Color at start of life 1, randomized between start colors

colorStartBColor<optional>
Color()

Color at start of life 2, randomized between start colors

colorEndAColor<optional>
Color(1,1,1,0)

Color at end of life 1, randomized between end colors

colorEndBColor<optional>
Color(1,1,1,0)

Color at end of life 2, randomized between end colors

particleTimeNumber<optional>
.5

How long particles live

sizeStartNumber<optional>
.1

How big are particles at start

sizeEndNumber<optional>
1

How big are particles at end

speedNumber<optional>
.1

How fast are particles when spawned

angleSpeedNumber<optional>
.05

How fast are particles rotating

dampingNumber<optional>
1

How much to dampen particle speed

angleDampingNumber<optional>
1

How much to dampen particle angular speed

gravityScaleNumber<optional>
0

How much does gravity effect particles

particleConeAngleNumber<optional>
PI

Cone for start particle angle

fadeRateNumber<optional>
.1

How quick to fade in particles at start/end in percent of life

randomnessNumber<optional>
.2

Apply extra randomness percent

collideTilesBoolean<optional>
0

Do particles collide against tiles

additiveBoolean<optional>
0

Should particles use addtive blend

randomColorLinearBoolean<optional>
1

Should color be randomized linearly or across each component

renderOrderNumber<optional>
0

Render order for particles (additive is above other stuff by default)

localSpaceBoolean<optional>
0

Should it be in local space of emitter (world space is default)

Example
// create a particle emitter
let pos = vec2(2,3);
let particleEmiter = new ParticleEmitter
(
    pos, 0, 1, 0, 500, PI,  // pos, angle, emitSize, emitTime, emitRate, emiteCone
    0, vec2(16),                            // tileIndex, tileSize
    new Color(1,1,1),   new Color(0,0,0),   // colorStartA, colorStartB
    new Color(1,1,1,0), new Color(0,0,0,0), // colorEndA, colorEndB
    2, .2, .2, .1, .05,  // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed
    .99, 1, 1, PI, .05,  // damping, angleDamping, gravityScale, particleCone, fadeRate, 
    .5, 1                // randomness, collide, additive, randomColorLinear, renderOrder
);

Extends

Members

additive

Properties
TypeDescription
Number

Should particles use addtive blend

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
TypeDescription
Number

How much to dampen particle angular speed

angleSpeed

Properties
TypeDescription
Number

How fast are particles rotating

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

collideTiles

Properties
TypeDescription
Number

Do particles collide against tiles

color

Properties
TypeDescription
Color

Color to apply when rendered

colorEndA

Properties
TypeDescription
Color

Color at end of life 1, randomized between end colors

colorEndB

Properties
TypeDescription
Color

Color at end of life 2, randomized between end colors

colorStartA

Properties
TypeDescription
Color

Color at start of life 1, randomized between start colors

colorStartB

Properties
TypeDescription
Color

Color at start of life 2, randomized between start colors

damping

Properties
TypeDescription
Number

How much to dampen particle speed

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

emitConeAngle

Properties
TypeDescription
Number

Local angle to apply velocity to particles from emitter

emitRate

Properties
TypeDescription
Number

How many particles per second to spawn, does not emit if 0

emitSize

Properties
TypeDescription
Number

World space size of the emitter (float for circle diameter, vec2 for rect)

emitTime

Properties
TypeDescription
Number

How long to stay alive (0 is forever)

fadeRate

Properties
TypeDescription
Number

How quick to fade in particles at start/end in percent of life

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
TypeDescription
Number

How much does gravity effect particles

localSpace

Properties
TypeDescription
Boolean

Should it be in local space of emitter

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

particleConeAngle

Properties
TypeDescription
Number

Cone for start particle angle

particleTime

Properties
TypeDescription
Number

How long particles live

pos

Properties
TypeDescription
Vector2

World space position of the object

randomColorLinear

Properties
TypeDescription
Boolean

Should color be randomized linearly or across each component

randomness

Properties
TypeDescription
Number

Apply extra randomness percent

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

sizeEnd

Properties
TypeDescription
Number

How big are particles at end

sizeStart

Properties
TypeDescription
Number

How big are particles at start

speed

Properties
TypeDescription
Number

How fast are particles when spawned

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

trailScale

Properties
TypeDescription
Number

If set the partile is drawn as a trail, stretched in the drection of velocity

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

emitParticle() → {Particle}

Spawn one particle

Returns:
Type: 
Particle

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the emitter to spawn particles, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

ParticleEmitter

Particle Emitter - Spawns particles with the given settings

Constructor

new ParticleEmitter(position, angleopt, emitSizeopt, emitTimeopt, emitRateopt, emitConeAngleopt, tileIndexopt, tileSizeopt, colorStartAopt, colorStartBopt, colorEndAopt, colorEndBopt, particleTimeopt, sizeStartopt, sizeEndopt, speedopt, angleSpeedopt, dampingopt, angleDampingopt, gravityScaleopt, particleConeAngleopt, fadeRateopt, randomnessopt, collideTilesopt, additiveopt, randomColorLinearopt, renderOrderopt, localSpaceopt)

Create a particle system with the given settings

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

World space position of the emitter

angleNumber<optional>
0

Angle to emit the particles

emitSizeNumber<optional>
0

World space size of the emitter (float for circle diameter, vec2 for rect)

emitTimeNumber<optional>
0

How long to stay alive (0 is forever)

emitRateNumber<optional>
100

How many particles per second to spawn, does not emit if 0

emitConeAngleNumber<optional>
PI

Local angle to apply velocity to particles from emitter

tileIndexNumber<optional>
-1

Index into tile sheet, if <0 no texture is applied

tileSizeVector2<optional>
tileSizeDefault

Tile size for particles

colorStartAColor<optional>
Color()

Color at start of life 1, randomized between start colors

colorStartBColor<optional>
Color()

Color at start of life 2, randomized between start colors

colorEndAColor<optional>
Color(1,1,1,0)

Color at end of life 1, randomized between end colors

colorEndBColor<optional>
Color(1,1,1,0)

Color at end of life 2, randomized between end colors

particleTimeNumber<optional>
.5

How long particles live

sizeStartNumber<optional>
.1

How big are particles at start

sizeEndNumber<optional>
1

How big are particles at end

speedNumber<optional>
.1

How fast are particles when spawned

angleSpeedNumber<optional>
.05

How fast are particles rotating

dampingNumber<optional>
1

How much to dampen particle speed

angleDampingNumber<optional>
1

How much to dampen particle angular speed

gravityScaleNumber<optional>
0

How much does gravity effect particles

particleConeAngleNumber<optional>
PI

Cone for start particle angle

fadeRateNumber<optional>
.1

How quick to fade in particles at start/end in percent of life

randomnessNumber<optional>
.2

Apply extra randomness percent

collideTilesBoolean<optional>
0

Do particles collide against tiles

additiveBoolean<optional>
0

Should particles use addtive blend

randomColorLinearBoolean<optional>
1

Should color be randomized linearly or across each component

renderOrderNumber<optional>
0

Render order for particles (additive is above other stuff by default)

localSpaceBoolean<optional>
0

Should it be in local space of emitter (world space is default)

Example
// create a particle emitter
let pos = vec2(2,3);
let particleEmiter = new ParticleEmitter
(
    pos, 0, 1, 0, 500, PI,  // pos, angle, emitSize, emitTime, emitRate, emiteCone
    0, vec2(16),                            // tileIndex, tileSize
    new Color(1,1,1),   new Color(0,0,0),   // colorStartA, colorStartB
    new Color(1,1,1,0), new Color(0,0,0,0), // colorEndA, colorEndB
    2, .2, .2, .1, .05,  // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed
    .99, 1, 1, PI, .05,  // damping, angleDamping, gravityScale, particleCone, fadeRate, 
    .5, 1                // randomness, collide, additive, randomColorLinear, renderOrder
);

Extends

Members

additive

Properties
TypeDescription
Number

Should particles use addtive blend

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
TypeDescription
Number

How much to dampen particle angular speed

angleSpeed

Properties
TypeDescription
Number

How fast are particles rotating

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

collideTiles

Properties
TypeDescription
Number

Do particles collide against tiles

color

Properties
TypeDescription
Color

Color to apply when rendered

colorEndA

Properties
TypeDescription
Color

Color at end of life 1, randomized between end colors

colorEndB

Properties
TypeDescription
Color

Color at end of life 2, randomized between end colors

colorStartA

Properties
TypeDescription
Color

Color at start of life 1, randomized between start colors

colorStartB

Properties
TypeDescription
Color

Color at start of life 2, randomized between start colors

damping

Properties
TypeDescription
Number

How much to dampen particle speed

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

emitConeAngle

Properties
TypeDescription
Number

Local angle to apply velocity to particles from emitter

emitRate

Properties
TypeDescription
Number

How many particles per second to spawn, does not emit if 0

emitSize

Properties
TypeDescription
Number

World space size of the emitter (float for circle diameter, vec2 for rect)

emitTime

Properties
TypeDescription
Number

How long to stay alive (0 is forever)

fadeRate

Properties
TypeDescription
Number

How quick to fade in particles at start/end in percent of life

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
TypeDescription
Number

How much does gravity effect particles

localSpace

Properties
TypeDescription
Boolean

Should it be in local space of emitter

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

particleConeAngle

Properties
TypeDescription
Number

Cone for start particle angle

particleTime

Properties
TypeDescription
Number

How long particles live

pos

Properties
TypeDescription
Vector2

World space position of the object

randomColorLinear

Properties
TypeDescription
Boolean

Should color be randomized linearly or across each component

randomness

Properties
TypeDescription
Number

Apply extra randomness percent

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

size

Properties
TypeDescription
Vector2

World space width and height of the object

sizeEnd

Properties
TypeDescription
Number

How big are particles at end

sizeStart

Properties
TypeDescription
Number

How big are particles at start

speed

Properties
TypeDescription
Number

How fast are particles when spawned

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

trailScale

Properties
TypeDescription
Number

If set the partile is drawn as a trail, stretched in the drection of velocity

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

emitParticle() → {Particle}

Spawn one particle

Returns:
Type: 
Particle

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the emitter to spawn particles, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Random.html b/docs/Random.html index 40525192..3bc51af0 100644 --- a/docs/Random.html +++ b/docs/Random.html @@ -1,3 +1,3 @@ Namespace: Random
On this page

Random

Random global functions

Methods

(static) rand(valueAopt, valueBopt) → {Number}

Returns a random value between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber<optional>
1
valueBNumber<optional>
0
Returns:
Type: 
Number

(static) randColor(colorAopt, colorBopt, linearopt) → {Color}

Returns a random color between the two passed in colors, combine components if linear

Parameters:
NameTypeAttributesDefaultDescription
colorAColor<optional>
Color()
colorBColor<optional>
Color(0,0,0,1)
linearBoolean<optional>
Returns:
Type: 
Color

(static) randInCircle(radiusopt, minRadiusopt) → {Vector2}

Returns a random Vector2 within a circular shape

Parameters:
NameTypeAttributesDefaultDescription
radiusNumber<optional>
1
minRadiusNumber<optional>
0
Returns:
Type: 
Vector2

(static) randInt(valueA, valueBopt) → {Number}

Returns a floored random value the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber<optional>
0
Returns:
Type: 
Number

(static) randSign() → {Number}

Randomly returns either -1 or 1

Returns:
Type: 
Number

(static) randVector(lengthopt) → {Vector2}

Returns a random Vector2 with the passed in length

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Random

Random global functions

Methods

(static) rand(valueAopt, valueBopt) → {Number}

Returns a random value between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber<optional>
1
valueBNumber<optional>
0
Returns:
Type: 
Number

(static) randColor(colorAopt, colorBopt, linearopt) → {Color}

Returns a random color between the two passed in colors, combine components if linear

Parameters:
NameTypeAttributesDefaultDescription
colorAColor<optional>
Color()
colorBColor<optional>
Color(0,0,0,1)
linearBoolean<optional>
Returns:
Type: 
Color

(static) randInCircle(radiusopt, minRadiusopt) → {Vector2}

Returns a random Vector2 within a circular shape

Parameters:
NameTypeAttributesDefaultDescription
radiusNumber<optional>
1
minRadiusNumber<optional>
0
Returns:
Type: 
Vector2

(static) randInt(valueA, valueBopt) → {Number}

Returns a floored random value the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber<optional>
0
Returns:
Type: 
Number

(static) randSign() → {Number}

Randomly returns either -1 or 1

Returns:
Type: 
Number

(static) randVector(lengthopt) → {Vector2}

Returns a random Vector2 with the passed in length

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/RandomGenerator.html b/docs/RandomGenerator.html index 6e3ad191..3715c73a 100644 --- a/docs/RandomGenerator.html +++ b/docs/RandomGenerator.html @@ -1,3 +1,3 @@ Class: RandomGenerator
On this page

RandomGenerator

Seeded random number generator

  • Can be used to create a deterministic random number sequence

Constructor

new RandomGenerator(seed)

Create a random number generator with the seed passed in

Parameters:
NameTypeDescription
seedNumber

Starting seed

Example
let r = new RandomGenerator(123); // random number generator with seed 123
let a = r.rand();                 // random value between 0 and 1
let b = r.randInt(10);            // random integer between 0 and 9
r.seed = 123;                     // reset the seed
let c = r.rand();                 // the same value as a

Members

seed

Properties
TypeDescription
Number

random seed

Methods

rand(valueAopt, valueBopt) → {Number}

Returns a seeded random value between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber<optional>
1
valueBNumber<optional>
0
Returns:
Type: 
Number

randInt(valueA, valueBopt) → {Number}

Returns a floored seeded random value the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber<optional>
0
Returns:
Type: 
Number

randSign() → {Number}

Randomly returns either -1 or 1 deterministically

Returns:
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

RandomGenerator

Seeded random number generator

  • Can be used to create a deterministic random number sequence

Constructor

new RandomGenerator(seed)

Create a random number generator with the seed passed in

Parameters:
NameTypeDescription
seedNumber

Starting seed

Example
let r = new RandomGenerator(123); // random number generator with seed 123
let a = r.rand();                 // random value between 0 and 1
let b = r.randInt(10);            // random integer between 0 and 9
r.seed = 123;                     // reset the seed
let c = r.rand();                 // the same value as a

Members

seed

Properties
TypeDescription
Number

random seed

Methods

float(valueAopt, valueBopt) → {Number}

Returns a seeded random value between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber<optional>
1
valueBNumber<optional>
0
Returns:
Type: 
Number

int(valueA, valueBopt) → {Number}

Returns a floored seeded random value the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber<optional>
0
Returns:
Type: 
Number

sign() → {Number}

Randomly returns either -1 or 1 deterministically

Returns:
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Settings.html b/docs/Settings.html index 79089927..2f16d7e4 100644 --- a/docs/Settings.html +++ b/docs/Settings.html @@ -1,3 +1,3 @@ Namespace: Settings
On this page

Settings

LittleJS Engine Settings

Members

(static) cameraPos :Vector2

Position of camera in world space

Type:
Default Value
  • Vector2()

(static) cameraScale :Number

Scale of camera in world space

Type:
  • Number
Default Value
  • 32

(static) canvasFixedSize :Vector2

Fixed size of the canvas, if enabled canvas size never changes

  • you may also need to set mainCanvasSize if using screen space coords in startup
Type:
Default Value
  • Vector2()

(static) canvasMaxSize :Vector2

The max size of the canvas, centered if window is larger

Type:
Default Value
  • Vector2(1920,1200)

(static) canvasPixelated :Boolean

Disables filtering for crisper pixel art if true

Type:
  • Boolean
Default Value
  • 1

(static) enablePhysicsSolver :Boolean

Enable physics solver for collisions between objects

Type:
  • Boolean
Default Value
  • 1

(static) fontDefault :String

Default font used for text rendering

Type:
  • String
Default Value
  • arial

(static) gamepadDirectionEmulateStick :Boolean

If true, the dpad input is also routed to the left analog stick (for better accessability)

Type:
  • Boolean
Default Value
  • 1

(static) gamepadsEnable :Boolean

Should gamepads be allowed

Type:
  • Boolean
Default Value
  • 1

(static) glEnable :Boolean

Enable webgl rendering, webgl can be disabled and removed from build (with some features disabled)

Type:
  • Boolean
Default Value
  • 1

(static) glOverlay :Boolean

Fixes slow rendering in some browsers by not compositing the WebGL canvas

Type:
  • Boolean
Default Value
  • 1

(static) gravity :Number

How much gravity to apply to objects along the Y axis, negative is down

Type:
  • Number
Default Value
  • 0

(static) inputWASDEmulateDirection :Boolean

If true the WASD keys are also routed to the direction keys (for better accessability)

Type:
  • Boolean
Default Value
  • 1

(static) medalDisplayIconSize :Number

Size of icon in medal display

Type:
  • Number
Default Value
  • 50

(static) medalDisplaySize :Vector2

Size of medal display

Type:
Default Value
  • Vector2(640,80)

(static) medalDisplaySlideTime :Number

How quickly to slide on/off medals in seconds

Type:
  • Number
Default Value
  • 0.5

(static) medalDisplayTime :Number

How long to show medals for in seconds

Type:
  • Number
Default Value
  • 5

(static) medalsPreventUnlock :Boolean

Set to stop medals from being unlockable (like if cheats are enabled)

Type:
  • Boolean
Default Value
  • 0

(static) objectDefaultAngleDamping :Number

How much to slow angular velocity each frame (0-1)

Type:
  • Number
Default Value
  • 1

(static) objectDefaultDamping :Number

How much to slow velocity by each frame (0-1)

Type:
  • Number
Default Value
  • 1

(static) objectDefaultElasticity :Number

How much to bounce when a collision occurs (0-1)

Type:
  • Number
Default Value
  • 0

(static) objectDefaultFriction :Number

How much to slow when touching (0-1)

Type:
  • Number
Default Value
  • 0.8

(static) objectDefaultMass :Number

Default object mass for collison calcuations (how heavy objects are)

Type:
  • Number
Default Value
  • 1

(static) objectMaxSpeed :Number

Clamp max speed to avoid fast objects missing collisions

Type:
  • Number
Default Value
  • 1

(static) particleEmitRateScale :Number

Scales emit rate of particles, useful for low graphics mode (0 disables particle emitters)

Type:
  • Number
Default Value
  • 1

(static) soundDefaultRange :Number

Default range where sound no longer plays

Type:
  • Number
Default Value
  • 40

(static) soundDefaultTaper :Number

Default range percent to start tapering off sound (0-1)

Type:
  • Number
Default Value
  • 0.7

(static) soundEnable :Boolean

All audio code can be disabled and removed from build

Type:
  • Boolean
Default Value
  • 1

(static) soundVolume :Number

Volume scale to apply to all sound, music and speech

Type:
  • Number
Default Value
  • 0.5

(static) tileFixBleedScale :Number

Prevent tile bleeding from neighbors in pixels

Type:
  • Number
Default Value
  • 0.3

(static) tileSizeDefault :Vector2

Default size of tiles in pixels

Type:
Default Value
  • Vector2(16,16)

(static) touchGamepadAlpha :Number

Transparency of touch gamepad overlay

Type:
  • Number
Default Value
  • 0.3

(static) touchGamepadAnalog :Boolean

True if touch gamepad should be analog stick or false to use if 8 way dpad

Type:
  • Boolean
Default Value
  • 1

(static) touchGamepadEnable :Boolean

True if touch gamepad should appear on mobile devices

  • Supports left analog stick, 4 face buttons and start button (button 9)
  • Must be set by end of gameInit to be activated
Type:
  • Boolean
Default Value
  • 0

(static) touchGamepadSize :Number

Size of virutal gamepad for touch devices in pixels

Type:
  • Number
Default Value
  • 99

(static) vibrateEnable :Boolean

Allow vibration hardware if it exists

Type:
  • Boolean
Default Value
  • 1

Methods

(static) setCameraPos(pos)

Set position of camera in world space

Parameters:
NameTypeDescription
posVector2

(static) setCameraScale(scale)

Set scale of camera in world space

Parameters:
NameTypeDescription
scaleNumber

(static) setCanvasFixedSize(size)

Set fixed size of the canvas

Parameters:
NameTypeDescription
sizeVector2

(static) setCanvasMaxSize(size)

Set max size of the canvas

Parameters:
NameTypeDescription
sizeVector2

(static) setCanvasPixelated(pixelated)

Disables anti aliasing for pixel art if true

Parameters:
NameTypeDescription
pixelatedBoolean

(static) setEnablePhysicsSolver(enable)

Set if collisions between objects are enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setFontDefault(font)

Set default font used for text rendering

Parameters:
NameTypeDescription
fontString

(static) setGamepadDirectionEmulateStick(enable)

Set if the dpad input is also routed to the left analog stick

Parameters:
NameTypeDescription
enableBoolean

(static) setGamepadsEnable(enable)

Set if gamepads are enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setGlEnable(enable)

Set if webgl rendering is enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setGlOverlay(overlay)

Set to not composite the WebGL canvas

Parameters:
NameTypeDescription
overlayBoolean

(static) setGravity(gravity)

Set how much gravity to apply to objects along the Y axis

Parameters:
NameTypeDescription
gravityNumber

(static) setInputWASDEmulateDirection(enable)

Set if true the WASD keys are also routed to the direction keys

Parameters:
NameTypeDescription
enableBoolean

(static) setMedalDisplayIconSize(size)

Set size of icon in medal display

Parameters:
NameTypeDescription
sizeNumber

(static) setMedalDisplaySize(size)

Set size of medal display

Parameters:
NameTypeDescription
sizeVector2

(static) setMedalDisplaySlideTime(time)

Set how quickly to slide on/off medals in seconds

Parameters:
NameTypeDescription
timeNumber

(static) setMedalDisplayTime(time)

Set how long to show medals for in seconds

Parameters:
NameTypeDescription
timeNumber

(static) setMedalsPreventUnlock(preventUnlock)

Set to stop medals from being unlockable

Parameters:
NameTypeDescription
preventUnlockBoolean

(static) setObjectDefaultAngleDamping(damping)

Set how much to slow angular velocity each frame

Parameters:
NameTypeDescription
dampingNumber

(static) setObjectDefaultDamping(damping)

Set how much to slow velocity by each frame

Parameters:
NameTypeDescription
dampingNumber

(static) setObjectDefaultElasticity(elasticity)

Set how much to bounce when a collision occur

Parameters:
NameTypeDescription
elasticityNumber

(static) setObjectDefaultFriction(friction)

Set how much to slow when touching

Parameters:
NameTypeDescription
frictionNumber

(static) setObjectDefaultMass(mass)

Set default object mass for collison calcuations

Parameters:
NameTypeDescription
massNumber

(static) setObjectMaxSpeed(speed)

Set max speed to avoid fast objects missing collisions

Parameters:
NameTypeDescription
speedNumber

(static) setParticleEmitRateScale(scale)

Set to scales emit rate of particles

Parameters:
NameTypeDescription
scaleNumber

(static) setSoundDefaultRange(range)

Set default range where sound no longer plays

Parameters:
NameTypeDescription
rangeNumber

(static) setSoundDefaultTaper(taper)

Set default range percent to start tapering off sound

Parameters:
NameTypeDescription
taperNumber

(static) setSoundEnable(enable)

Set to disable all audio code

Parameters:
NameTypeDescription
enableBoolean

(static) setSoundVolume(volume)

Set volume scale to apply to all sound, music and speech

Parameters:
NameTypeDescription
volumeNumber

(static) setTileFixBleedScale(scale)

Set to prevent tile bleeding from neighbors in pixels

Parameters:
NameTypeDescription
scaleNumber

(static) setTileSizeDefault(size)

Set default size of tiles in pixels

Parameters:
NameTypeDescription
sizeVector2

(static) setTouchGamepadAlpha(alpha)

Set transparency of touch gamepad overlay

Parameters:
NameTypeDescription
alphaNumber

(static) setTouchGamepadAnalog(analog)

Set if touch gamepad should be analog stick or 8 way dpad

Parameters:
NameTypeDescription
analogBoolean

(static) setTouchGamepadEnable(enable)

Set if touch gamepad should appear on mobile devices

Parameters:
NameTypeDescription
enableBoolean

(static) setTouchGamepadSize(size)

Set size of virutal gamepad for touch devices in pixels

Parameters:
NameTypeDescription
sizeNumber

(static) setVibrateEnable(enable)

Set to allow vibration hardware if it exists

Parameters:
NameTypeDescription
enableBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Settings

LittleJS Engine Settings

  • All settings for the engine are here

Members

(static) cameraPos :Vector2

Position of camera in world space

Type:
Default Value
  • Vector2()

(static) cameraScale :Number

Scale of camera in world space

Type:
  • Number
Default Value
  • 32

(static) canvasFixedSize :Vector2

Fixed size of the canvas, if enabled canvas size never changes

  • you may also need to set mainCanvasSize if using screen space coords in startup
Type:
Default Value
  • Vector2()

(static) canvasMaxSize :Vector2

The max size of the canvas, centered if window is larger

Type:
Default Value
  • Vector2(1920,1200)

(static) canvasPixelated :Boolean

Disables filtering for crisper pixel art if true

Type:
  • Boolean
Default Value
  • 1

(static) enablePhysicsSolver :Boolean

Enable physics solver for collisions between objects

Type:
  • Boolean
Default Value
  • 1

(static) fontDefault :String

Default font used for text rendering

Type:
  • String
Default Value
  • arial

(static) gamepadDirectionEmulateStick :Boolean

If true, the dpad input is also routed to the left analog stick (for better accessability)

Type:
  • Boolean
Default Value
  • 1

(static) gamepadsEnable :Boolean

Should gamepads be allowed

Type:
  • Boolean
Default Value
  • 1

(static) glEnable :Boolean

Enable webgl rendering, webgl can be disabled and removed from build (with some features disabled)

Type:
  • Boolean
Default Value
  • 1

(static) glOverlay :Boolean

Fixes slow rendering in some browsers by not compositing the WebGL canvas

Type:
  • Boolean
Default Value
  • 1

(static) gravity :Number

How much gravity to apply to objects along the Y axis, negative is down

Type:
  • Number
Default Value
  • 0

(static) inputWASDEmulateDirection :Boolean

If true the WASD keys are also routed to the direction keys (for better accessability)

Type:
  • Boolean
Default Value
  • 1

(static) medalDisplayIconSize :Number

Size of icon in medal display

Type:
  • Number
Default Value
  • 50

(static) medalDisplaySize :Vector2

Size of medal display

Type:
Default Value
  • Vector2(640,80)

(static) medalDisplaySlideTime :Number

How quickly to slide on/off medals in seconds

Type:
  • Number
Default Value
  • 0.5

(static) medalDisplayTime :Number

How long to show medals for in seconds

Type:
  • Number
Default Value
  • 5

(static) medalsPreventUnlock :Boolean

Set to stop medals from being unlockable (like if cheats are enabled)

Type:
  • Boolean
Default Value
  • 0

(static) objectDefaultAngleDamping :Number

How much to slow angular velocity each frame (0-1)

Type:
  • Number
Default Value
  • 1

(static) objectDefaultDamping :Number

How much to slow velocity by each frame (0-1)

Type:
  • Number
Default Value
  • 1

(static) objectDefaultElasticity :Number

How much to bounce when a collision occurs (0-1)

Type:
  • Number
Default Value
  • 0

(static) objectDefaultFriction :Number

How much to slow when touching (0-1)

Type:
  • Number
Default Value
  • 0.8

(static) objectDefaultMass :Number

Default object mass for collison calcuations (how heavy objects are)

Type:
  • Number
Default Value
  • 1

(static) objectMaxSpeed :Number

Clamp max speed to avoid fast objects missing collisions

Type:
  • Number
Default Value
  • 1

(static) particleEmitRateScale :Number

Scales emit rate of particles, useful for low graphics mode (0 disables particle emitters)

Type:
  • Number
Default Value
  • 1

(static) soundDefaultRange :Number

Default range where sound no longer plays

Type:
  • Number
Default Value
  • 40

(static) soundDefaultTaper :Number

Default range percent to start tapering off sound (0-1)

Type:
  • Number
Default Value
  • 0.7

(static) soundEnable :Boolean

All audio code can be disabled and removed from build

Type:
  • Boolean
Default Value
  • 1

(static) soundVolume :Number

Volume scale to apply to all sound, music and speech

Type:
  • Number
Default Value
  • 0.5

(static) tileFixBleedScale :Number

Prevent tile bleeding from neighbors in pixels

Type:
  • Number
Default Value
  • 0.3

(static) tileSizeDefault :Vector2

Default size of tiles in pixels

Type:
Default Value
  • Vector2(16,16)

(static) touchGamepadAlpha :Number

Transparency of touch gamepad overlay

Type:
  • Number
Default Value
  • 0.3

(static) touchGamepadAnalog :Boolean

True if touch gamepad should be analog stick or false to use if 8 way dpad

Type:
  • Boolean
Default Value
  • 1

(static) touchGamepadEnable :Boolean

True if touch gamepad should appear on mobile devices

  • Supports left analog stick, 4 face buttons and start button (button 9)
  • Must be set by end of gameInit to be activated
Type:
  • Boolean
Default Value
  • 0

(static) touchGamepadSize :Number

Size of virutal gamepad for touch devices in pixels

Type:
  • Number
Default Value
  • 99

(static) vibrateEnable :Boolean

Allow vibration hardware if it exists

Type:
  • Boolean
Default Value
  • 1

Methods

(static) setCameraPos(pos)

Set position of camera in world space

Parameters:
NameTypeDescription
posVector2

(static) setCameraScale(scale)

Set scale of camera in world space

Parameters:
NameTypeDescription
scaleNumber

(static) setCanvasFixedSize(size)

Set fixed size of the canvas

Parameters:
NameTypeDescription
sizeVector2

(static) setCanvasMaxSize(size)

Set max size of the canvas

Parameters:
NameTypeDescription
sizeVector2

(static) setCanvasPixelated(pixelated)

Disables anti aliasing for pixel art if true

Parameters:
NameTypeDescription
pixelatedBoolean

(static) setEnablePhysicsSolver(enable)

Set if collisions between objects are enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setFontDefault(font)

Set default font used for text rendering

Parameters:
NameTypeDescription
fontString

(static) setGamepadDirectionEmulateStick(enable)

Set if the dpad input is also routed to the left analog stick

Parameters:
NameTypeDescription
enableBoolean

(static) setGamepadsEnable(enable)

Set if gamepads are enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setGlEnable(enable)

Set if webgl rendering is enabled

Parameters:
NameTypeDescription
enableBoolean

(static) setGlOverlay(overlay)

Set to not composite the WebGL canvas

Parameters:
NameTypeDescription
overlayBoolean

(static) setGravity(gravity)

Set how much gravity to apply to objects along the Y axis

Parameters:
NameTypeDescription
gravityNumber

(static) setInputWASDEmulateDirection(enable)

Set if true the WASD keys are also routed to the direction keys

Parameters:
NameTypeDescription
enableBoolean

(static) setMedalDisplayIconSize(size)

Set size of icon in medal display

Parameters:
NameTypeDescription
sizeNumber

(static) setMedalDisplaySize(size)

Set size of medal display

Parameters:
NameTypeDescription
sizeVector2

(static) setMedalDisplaySlideTime(time)

Set how quickly to slide on/off medals in seconds

Parameters:
NameTypeDescription
timeNumber

(static) setMedalDisplayTime(time)

Set how long to show medals for in seconds

Parameters:
NameTypeDescription
timeNumber

(static) setMedalsPreventUnlock(preventUnlock)

Set to stop medals from being unlockable

Parameters:
NameTypeDescription
preventUnlockBoolean

(static) setObjectDefaultAngleDamping(damping)

Set how much to slow angular velocity each frame

Parameters:
NameTypeDescription
dampingNumber

(static) setObjectDefaultDamping(damping)

Set how much to slow velocity by each frame

Parameters:
NameTypeDescription
dampingNumber

(static) setObjectDefaultElasticity(elasticity)

Set how much to bounce when a collision occur

Parameters:
NameTypeDescription
elasticityNumber

(static) setObjectDefaultFriction(friction)

Set how much to slow when touching

Parameters:
NameTypeDescription
frictionNumber

(static) setObjectDefaultMass(mass)

Set default object mass for collison calcuations

Parameters:
NameTypeDescription
massNumber

(static) setObjectMaxSpeed(speed)

Set max speed to avoid fast objects missing collisions

Parameters:
NameTypeDescription
speedNumber

(static) setParticleEmitRateScale(scale)

Set to scales emit rate of particles

Parameters:
NameTypeDescription
scaleNumber

(static) setSoundDefaultRange(range)

Set default range where sound no longer plays

Parameters:
NameTypeDescription
rangeNumber

(static) setSoundDefaultTaper(taper)

Set default range percent to start tapering off sound

Parameters:
NameTypeDescription
taperNumber

(static) setSoundEnable(enable)

Set to disable all audio code

Parameters:
NameTypeDescription
enableBoolean

(static) setSoundVolume(volume)

Set volume scale to apply to all sound, music and speech

Parameters:
NameTypeDescription
volumeNumber

(static) setTileFixBleedScale(scale)

Set to prevent tile bleeding from neighbors in pixels

Parameters:
NameTypeDescription
scaleNumber

(static) setTileSizeDefault(size)

Set default size of tiles in pixels

Parameters:
NameTypeDescription
sizeVector2

(static) setTouchGamepadAlpha(alpha)

Set transparency of touch gamepad overlay

Parameters:
NameTypeDescription
alphaNumber

(static) setTouchGamepadAnalog(analog)

Set if touch gamepad should be analog stick or 8 way dpad

Parameters:
NameTypeDescription
analogBoolean

(static) setTouchGamepadEnable(enable)

Set if touch gamepad should appear on mobile devices

Parameters:
NameTypeDescription
enableBoolean

(static) setTouchGamepadSize(size)

Set size of virutal gamepad for touch devices in pixels

Parameters:
NameTypeDescription
sizeNumber

(static) setVibrateEnable(enable)

Set to allow vibration hardware if it exists

Parameters:
NameTypeDescription
enableBoolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Sound.html b/docs/Sound.html index cc58ee8b..a533808a 100644 --- a/docs/Sound.html +++ b/docs/Sound.html @@ -1,3 +1,3 @@ Class: Sound
On this page

Sound

Sound Object - Stores a zzfx sound for later use and can be played positionally

Create sounds using the ZzFX Sound Designer.

Constructor

new Sound(zzfxSound, rangeopt, taperopt)

Create a sound object and cache the zzfx samples for later use

Parameters:
NameTypeAttributesDefaultDescription
zzfxSoundArray

Array of zzfx parameters, ex. [.5,.5]

rangeNumber<optional>
soundDefaultRange

World space max range of sound, will not play if camera is farther away

taperNumber<optional>
soundDefaultTaper

At what percentage of range should it start tapering off

Example
// create a sound
const sound_example = new Sound([.5,.5]);

// play the sound
sound_example.play();

Members

range

Properties
TypeDescription
Number

World space max range of sound, will not play if camera is farther away

taper

Properties
TypeDescription
Number

At what percentage of range should it start tapering off

Methods

play(posopt, volumeopt, pitchopt, randomnessScaleopt) → {AudioBufferSourceNode}

Play the sound

Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

World space position to play the sound, sound is not attenuated if null

volumeNumber<optional>
1

How much to scale volume by (in addition to range fade)

pitchNumber<optional>
1

How much to scale pitch by (also adjusted by this.randomness)

randomnessScaleNumber<optional>
1

How much to scale randomness

Returns:
  • The audio, can be used to stop sound later
Type: 
AudioBufferSourceNode

playNote(semitoneOffset, posopt, volumeopt) → {AudioBufferSourceNode}

Play the sound as a note with a semitone offset

Parameters:
NameTypeAttributesDefaultDescription
semitoneOffsetNumber

How many semitones to offset pitch

posVector2<optional>

World space position to play the sound, sound is not attenuated if null

volumeNumber<optional>
1

How much to scale volume by (in addition to range fade)

Returns:
  • The audio, can be used to stop sound later
Type: 
AudioBufferSourceNode
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Sound

Sound Object - Stores a zzfx sound for later use and can be played positionally

Create sounds using the ZzFX Sound Designer.

Constructor

new Sound(zzfxSound, rangeopt, taperopt)

Create a sound object and cache the zzfx samples for later use

Parameters:
NameTypeAttributesDefaultDescription
zzfxSoundArray

Array of zzfx parameters, ex. [.5,.5]

rangeNumber<optional>
soundDefaultRange

World space max range of sound, will not play if camera is farther away

taperNumber<optional>
soundDefaultTaper

At what percentage of range should it start tapering off

Example
// create a sound
const sound_example = new Sound([.5,.5]);

// play the sound
sound_example.play();

Members

randomness

Properties
TypeDescription
Number

How much to randomize frequency each time sound plays

range

Properties
TypeDescription
Number

World space max range of sound, will not play if camera is farther away

taper

Properties
TypeDescription
Number

At what percentage of range should it start tapering off

Methods

play(posopt, volumeopt, pitchopt, randomnessScaleopt) → {AudioBufferSourceNode}

Play the sound

Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

World space position to play the sound, sound is not attenuated if null

volumeNumber<optional>
1

How much to scale volume by (in addition to range fade)

pitchNumber<optional>
1

How much to scale pitch by (also adjusted by this.randomness)

randomnessScaleNumber<optional>
1

How much to scale randomness

Returns:
  • The audio, can be used to stop sound later
Type: 
AudioBufferSourceNode

playNote(semitoneOffset, posopt, volumeopt) → {AudioBufferSourceNode}

Play the sound as a note with a semitone offset

Parameters:
NameTypeAttributesDefaultDescription
semitoneOffsetNumber

How many semitones to offset pitch

posVector2<optional>

World space position to play the sound, sound is not attenuated if null

volumeNumber<optional>
1

How much to scale volume by (in addition to range fade)

Returns:
  • The audio, can be used to stop sound later
Type: 
AudioBufferSourceNode
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/SoundWave.html b/docs/SoundWave.html new file mode 100644 index 00000000..935e670d --- /dev/null +++ b/docs/SoundWave.html @@ -0,0 +1,3 @@ +Class: SoundWave
On this page

SoundWave

Sound Wave Object - Stores a wave sound for later use and can be played positionally

Constructor

new SoundWave(waveFilename, randomnessopt, rangeopt, taperopt)

Create a sound object and cache the wave file for later use

Parameters:
NameTypeAttributesDefaultDescription
waveFilenameString

Filename of wave file to load

randomnessNumber<optional>
.05

How much to randomize frequency each time sound plays

rangeNumber<optional>
soundDefaultRange

World space max range of sound, will not play if camera is farther away

taperNumber<optional>
soundDefaultTaper

At what percentage of range should it start tapering off

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/TileCollision.html b/docs/TileCollision.html index be10671b..d64c6548 100644 --- a/docs/TileCollision.html +++ b/docs/TileCollision.html @@ -1,3 +1,3 @@ Namespace: TileCollision
On this page

TileCollision

LittleJS Tile Layer System

  • Caches arrays of tiles to off screen canvas for fast rendering
  • Unlimted numbers of layers, allocates canvases as needed
  • Interfaces with EngineObject for collision
  • Collision layer is separate from visible layers
  • It is recommended to have a visible layer that matches the collision
  • Tile layers can be drawn to using their context with canvas2d
  • Drawn directly to the main canvas without using WebGL

Members

(static) tileCollision :Array

The tile collision layer array, use setTileCollisionData and getTileCollisionData to access

Type:
  • Array

(static) tileCollisionSize :Vector2

Size of the tile collision layer

Type:

Methods

(static) getTileCollisionData(pos) → {Number}

Get tile collision data

Parameters:
NameTypeDescription
posVector2
Returns:
Type: 
Number

(static) initTileCollision(size)

Clear and initialize tile collision

Parameters:
NameTypeDescription
sizeVector2

(static) setTileCollisionData(pos, dataopt)

Set tile collision data

Parameters:
NameTypeAttributesDefaultDescription
posVector2
dataNumber<optional>
0

(static) tileCollisionRaycast(posStart, posEnd, objectopt) → {Vector2}

Return the center of tile if any that is hit (does not return the exact intersection)

Parameters:
NameTypeAttributesDescription
posStartVector2
posEndVector2
objectEngineObject<optional>
Returns:
Type: 
Vector2

(static) tileCollisionTest(pos, sizeopt, objectopt) → {Boolean}

Check if collision with another object should occur

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
objectEngineObject<optional>
Returns:
Type: 
Boolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

TileCollision

LittleJS Tile Layer System

  • Caches arrays of tiles to off screen canvas for fast rendering
  • Unlimted numbers of layers, allocates canvases as needed
  • Interfaces with EngineObject for collision
  • Collision layer is separate from visible layers
  • It is recommended to have a visible layer that matches the collision
  • Tile layers can be drawn to using their context with canvas2d
  • Drawn directly to the main canvas without using WebGL

Members

(static) tileCollision :Array

The tile collision layer array, use setTileCollisionData and getTileCollisionData to access

Type:
  • Array

(static) tileCollisionSize :Vector2

Size of the tile collision layer

Type:

Methods

(static) getTileCollisionData(pos) → {Number}

Get tile collision data

Parameters:
NameTypeDescription
posVector2
Returns:
Type: 
Number

(static) initTileCollision(size)

Clear and initialize tile collision

Parameters:
NameTypeDescription
sizeVector2

(static) setTileCollisionData(pos, dataopt)

Set tile collision data

Parameters:
NameTypeAttributesDefaultDescription
posVector2
dataNumber<optional>
0

(static) tileCollisionRaycast(posStart, posEnd, objectopt) → {Vector2}

Return the center of tile if any that is hit (does not return the exact intersection)

Parameters:
NameTypeAttributesDescription
posStartVector2
posEndVector2
objectEngineObject<optional>
Returns:
Type: 
Vector2

(static) tileCollisionTest(pos, sizeopt, objectopt) → {Boolean}

Check if collision with another object should occur

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
objectEngineObject<optional>
Returns:
Type: 
Boolean
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/TileLayer.html b/docs/TileLayer.html index 0074e8cc..7d5f1ee9 100644 --- a/docs/TileLayer.html +++ b/docs/TileLayer.html @@ -1,3 +1,3 @@ Class: TileLayer
On this page

TileLayer

Tile layer object - cached rendering system for tile layers

  • Each Tile layer is rendered to an off screen canvas
  • To allow dynamic modifications, layers are rendered using canvas 2d
  • Some devices like mobile phones are limited to 4k texture resolution
  • So with 16x16 tiles this limits layers to 256x256 on mobile devices

Constructor

new TileLayer(positionopt, sizeopt, tileSizeopt, scaleopt, renderOrderopt)

Create a tile layer object

Parameters:
NameTypeAttributesDefaultDescription
positionVector2<optional>
Vector2()

World space position

sizeVector2<optional>
tileCollisionSize

World space size

tileSizeVector2<optional>
tileSizeDefault

Size of tiles in source pixels

scaleVector2<optional>
Vector2(1,1)

How much to scale this layer when rendered

renderOrderNumber<optional>
0

Objects sorted by renderOrder before being rendered

Example
// create tile collision and visible tile layer
initTileCollision(vec2(200,100));
const tileLayer = new TileLayer();

Extends

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

canvas

Properties
TypeDescription
HTMLCanvasElement

The canvas used by this tile layer

color

Properties
TypeDescription
Color

Color to apply when rendered

context

Properties
TypeDescription
CanvasRenderingContext2D

The 2D canvas context used by this tile layer

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

isOverlay

Properties
NameTypeAttributesDefaultDescription
isOverlayBoolean<optional>
0

If true this layer will render to overlay canvas and appear above all objects

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

scale

Properties
TypeDescription
Vector2

How much to scale this layer when rendered

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

drawAllTileData()

Draw all the tiles in this layer

drawCanvas2D(pos, size, angleopt, mirroropt, drawFunction)

Draw directly to the 2D canvas in world space (bipass webgl)

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2
angleNumber<optional>
0
mirrorBoolean<optional>
0
drawFunctionfunction

drawRect(pos, sizeopt, coloropt, angleopt)

Draw a rectangle directly onto the layer canvas

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
colorColor<optional>
Color()
angleNumber<optional>
0

drawTile(pos, sizeopt, tileIndexopt, tileSizeopt, coloropt, angleopt, mirroropt)

Draw a tile directly onto the layer canvas

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
tileIndexNumber<optional>
-1
tileSizeVector2<optional>
tileSizeDefault
colorColor<optional>
Color()
angleNumber<optional>
0
mirrorBoolean<optional>
0

drawTileData(layerPos)

Draw the tile at a given position

Parameters:
NameTypeDescription
layerPosVector2

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getData(layerPos) → {TileLayerData}

Get data at a given position in the array

Parameters:
NameTypeDescription
layerPosVector2

Local position in array

Returns:
Type: 
TileLayerData

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

redraw()

Draw all the tile data to an offscreen canvas

  • This may be slow in some browsers

redrawEnd()

Call to end the redraw process

redrawStart(clearopt)

Call to start the redraw process

Parameters:
NameTypeAttributesDefaultDescription
clearBoolean<optional>
0

Should it clear the canvas before drawing

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

setData(position, data, redrawopt)

Set data at a given position in the array

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

Local position in array

dataTileLayerData

Data to set

redrawBoolean<optional>
0

Force the tile to redraw if true

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

TileLayer

Tile layer object - cached rendering system for tile layers

  • Each Tile layer is rendered to an off screen canvas
  • To allow dynamic modifications, layers are rendered using canvas 2d
  • Some devices like mobile phones are limited to 4k texture resolution
  • So with 16x16 tiles this limits layers to 256x256 on mobile devices

Constructor

new TileLayer(positionopt, sizeopt, tileSizeopt, scaleopt, renderOrderopt)

Create a tile layer object

Parameters:
NameTypeAttributesDefaultDescription
positionVector2<optional>
Vector2()

World space position

sizeVector2<optional>
tileCollisionSize

World space size

tileSizeVector2<optional>
tileSizeDefault

Size of tiles in source pixels

scaleVector2<optional>
Vector2(1,1)

How much to scale this layer when rendered

renderOrderNumber<optional>
0

Objects sorted by renderOrder before being rendered

Example
// create tile collision and visible tile layer
initTileCollision(vec2(200,100));
const tileLayer = new TileLayer();

Extends

Members

additiveColor

Properties
TypeDescription
Color

Additive color to apply when rendered

angle

Properties
TypeDescription
Number

Angle to rotate the object

angleDamping

Properties
NameTypeAttributesDefaultDescription
angleDampingNumber<optional>
objectDefaultAngleDamping

How much to slow down rotation each frame (0-1)

angleVelocity

Properties
NameTypeAttributesDefaultDescription
angleVelocityNumber<optional>
0

Angular velocity of the object

canvas

Properties
TypeDescription
HTMLCanvasElement

The canvas used by this tile layer

color

Properties
TypeDescription
Color

Color to apply when rendered

context

Properties
TypeDescription
CanvasRenderingContext2D

The 2D canvas context used by this tile layer

damping

Properties
NameTypeAttributesDefaultDescription
dampingNumber<optional>
objectDefaultDamping

How much to slow down velocity each frame (0-1)

drawSize

Properties
TypeDescription
Vector2

Size of object used for drawing, uses size if not set

elasticity

Properties
NameTypeAttributesDefaultDescription
elasticityNumber<optional>
objectDefaultElasticity

How bouncy the object is when colliding (0-1)

friction

Properties
NameTypeAttributesDefaultDescription
frictionNumber<optional>
objectDefaultFriction

How much friction to apply when sliding (0-1)

gravityScale

Properties
NameTypeAttributesDefaultDescription
gravityScaleNumber<optional>
1

How much to scale gravity by for this object

isOverlay

Properties
NameTypeAttributesDefaultDescription
isOverlayBoolean<optional>
0

If true this layer will render to overlay canvas and appear above all objects

mass

Properties
NameTypeAttributesDefaultDescription
massNumber<optional>
objectDefaultMass

How heavy the object is, static if 0

pos

Properties
TypeDescription
Vector2

World space position of the object

renderOrder

Properties
NameTypeAttributesDefaultDescription
renderOrderNumber<optional>
0

Objects are sorted by render order

scale

Properties
TypeDescription
Vector2

How much to scale this layer when rendered

size

Properties
TypeDescription
Vector2

World space width and height of the object

tileIndex

Properties
TypeDescription
Number

Tile to use to render object (-1 is untextured)

tileSize

Properties
TypeDescription
Vector2

Size of tile in source pixels

velocity

Properties
NameTypeAttributesDefaultDescription
velocityVector2<optional>
Vector2()

Velocity of the object

Methods

addChild(child, localPosopt, localAngleopt)

Attaches a child to this with a given local transform

Parameters:
NameTypeAttributesDefaultDescription
childEngineObject
localPosVector2<optional>
Vector2()
localAngleNumber<optional>
0

applyAcceleration(acceleration)

Apply acceleration to this object (adjust velocity, not affected by mass)

Parameters:
NameTypeDescription
accelerationVector2

applyForce(force)

Apply force to this object (adjust velocity, affected by mass)

Parameters:
NameTypeDescription
forceVector2

collideWithObject(object) → {Boolean}

Called to check if a object collision should be resolved

Parameters:
NameTypeDescription
objectEngineObject

the object to test against

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTile(tileData, pos) → {Boolean}

Called to check if a tile collision should be resolved

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the collision occured

Returns:
  • true if the collision should be resolved
Type: 
Boolean

collideWithTileRaycast(tileData, pos) → {Boolean}

Called to check if a tile raycast hit

Parameters:
NameTypeDescription
tileDataNumber

the value of the tile at the position

posVector2

tile where the raycast is

Returns:
  • true if the raycast should hit
Type: 
Boolean

destroy()

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

drawAllTileData()

Draw all the tiles in this layer

drawCanvas2D(pos, size, angleopt, mirroropt, drawFunction)

Draw directly to the 2D canvas in world space (bipass webgl)

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2
angleNumber<optional>
0
mirrorBoolean<optional>
0
drawFunctionfunction

drawRect(pos, sizeopt, coloropt, angleopt)

Draw a rectangle directly onto the layer canvas

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
colorColor<optional>
Color()
angleNumber<optional>
0

drawTile(pos, sizeopt, tileIndexopt, tileSizeopt, coloropt, angleopt, mirroropt)

Draw a tile directly onto the layer canvas

Parameters:
NameTypeAttributesDefaultDescription
posVector2
sizeVector2<optional>
Vector2(1,1)
tileIndexNumber<optional>
-1
tileSizeVector2<optional>
tileSizeDefault
colorColor<optional>
Color()
angleNumber<optional>
0
mirrorBoolean<optional>
0

drawTileData(layerPos)

Draw the tile at a given position

Parameters:
NameTypeDescription
layerPosVector2

getAliveTime() → {Number}

How long since the object was created

Returns:
Type: 
Number

getData(layerPos) → {TileLayerData}

Get data at a given position in the array

Parameters:
NameTypeDescription
layerPosVector2

Local position in array

Returns:
Type: 
TileLayerData

getMirrorSign() → {Number}

Get the direction of the mirror

Returns:

-1 if this.mirror is true, or 1 if not mirrored

Type: 
Number

redraw()

Draw all the tile data to an offscreen canvas

  • This may be slow in some browsers

redrawEnd()

Call to end the redraw process

redrawStart(clearopt)

Call to start the redraw process

Parameters:
NameTypeAttributesDefaultDescription
clearBoolean<optional>
0

Should it clear the canvas before drawing

removeChild(child)

Removes a child from this one

Parameters:
NameTypeDescription
childEngineObject

render()

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

setCollision(collideSolidObjectsopt, isSolidopt, collideTilesopt)

Set how this object collides

Parameters:
NameTypeAttributesDefaultDescription
collideSolidObjectsBoolean<optional>
1

Does it collide with solid objects

isSolidBoolean<optional>
1

Does it collide with and block other objects (expensive in large numbers)

collideTilesBoolean<optional>
1

Does it collide with the tile collision

setData(position, data, redrawopt)

Set data at a given position in the array

Parameters:
NameTypeAttributesDefaultDescription
positionVector2

Local position in array

dataTileLayerData

Data to set

redrawBoolean<optional>
0

Force the tile to redraw if true

toString() → {String}

Returns string containg info about this object for debugging

Returns:
Type: 
String

update()

Update the object transform and physics, called automatically by engine once each frame

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/TileLayerData.html b/docs/TileLayerData.html index 630889c1..4651748a 100644 --- a/docs/TileLayerData.html +++ b/docs/TileLayerData.html @@ -1,3 +1,3 @@ Class: TileLayerData
On this page

TileLayerData

Tile layer data object stores info about how to render a tile

Constructor

new TileLayerData(tileopt, directionopt, mirroropt, coloropt)

Create a tile layer data object, one for each tile in a TileLayer

Parameters:
NameTypeAttributesDefaultDescription
tileNumber<optional>

The tile to use, untextured if undefined

directionNumber<optional>
0

Integer direction of tile, in 90 degree increments

mirrorBoolean<optional>
0

If the tile should be mirrored along the x axis

colorColor<optional>
Color()

Color of the tile

Example
// create tile layer data with tile index 0 and random orientation and color
const tileIndex = 0;
const direction = randInt(4)
const mirror = randInt(2);
const color = randColor();
const data = new TileLayerData(tileIndex, direction, mirror, color);

Members

color

Properties
TypeDescription
Color

Color of the tile

direction

Properties
TypeDescription
Number

Integer direction of tile, in 90 degree increments

mirror

Properties
TypeDescription
Boolean

If the tile should be mirrored along the x axis

tile

Properties
TypeDescription
Number

The tile to use, untextured if undefined

Methods

clear()

Set this tile to clear, it will not be rendered

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

TileLayerData

Tile layer data object stores info about how to render a tile

Constructor

new TileLayerData(tileopt, directionopt, mirroropt, coloropt)

Create a tile layer data object, one for each tile in a TileLayer

Parameters:
NameTypeAttributesDefaultDescription
tileNumber<optional>

The tile to use, untextured if undefined

directionNumber<optional>
0

Integer direction of tile, in 90 degree increments

mirrorBoolean<optional>
0

If the tile should be mirrored along the x axis

colorColor<optional>
Color()

Color of the tile

Example
// create tile layer data with tile index 0 and random orientation and color
const tileIndex = 0;
const direction = randInt(4)
const mirror = randInt(2);
const color = randColor();
const data = new TileLayerData(tileIndex, direction, mirror, color);

Members

color

Properties
TypeDescription
Color

Color of the tile

direction

Properties
TypeDescription
Number

Integer direction of tile, in 90 degree increments

mirror

Properties
TypeDescription
Boolean

If the tile should be mirrored along the x axis

tile

Properties
TypeDescription
Number

The tile to use, untextured if undefined

Methods

clear()

Set this tile to clear, it will not be rendered

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Timer.html b/docs/Timer.html index 8e2e56cc..4282bc86 100644 --- a/docs/Timer.html +++ b/docs/Timer.html @@ -1,3 +1,3 @@ Class: Timer
On this page

Timer

Timer object tracks how long has passed since it was set

Constructor

new Timer(timeLeftopt)

Create a timer object set time passed in

Parameters:
NameTypeAttributesDescription
timeLeftNumber<optional>

How much time left before the timer elapses in seconds

Example
let a = new Timer;    // creates a timer that is not set
a.set(3);             // sets the timer to 3 seconds

let b = new Timer(1); // creates a timer with 1 second left
b.unset();            // unsets the timer

Methods

active() → {Boolean}

Returns true if set and has not elapsed

Returns:
Type: 
Boolean

elapsed() → {Boolean}

Returns true if set and elapsed

Returns:
Type: 
Boolean

get() → {Number}

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

Returns:
Type: 
Number

getPercent() → {Number}

Get percentage elapsed based on time it was set to, returns 0 if not set

Returns:
Type: 
Number

isSet() → {Boolean}

Returns true if set

Returns:
Type: 
Boolean

set(timeLeftopt)

Set the timer with seconds passed in

Parameters:
NameTypeAttributesDefaultDescription
timeLeftNumber<optional>
0

How much time left before the timer is elapsed in seconds

toString() → {String}

Returns this timer expressed as a string

Returns:
Type: 
String

unset()

Unset the timer

valueOf() → {Number}

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

Returns:
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Timer

Timer object tracks how long has passed since it was set

Constructor

new Timer(timeLeftopt)

Create a timer object set time passed in

Parameters:
NameTypeAttributesDescription
timeLeftNumber<optional>

How much time left before the timer elapses in seconds

Example
let a = new Timer;    // creates a timer that is not set
a.set(3);             // sets the timer to 3 seconds

let b = new Timer(1); // creates a timer with 1 second left
b.unset();            // unsets the timer

Methods

active() → {Boolean}

Returns true if set and has not elapsed

Returns:
Type: 
Boolean

elapsed() → {Boolean}

Returns true if set and elapsed

Returns:
Type: 
Boolean

get() → {Number}

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

Returns:
Type: 
Number

getPercent() → {Number}

Get percentage elapsed based on time it was set to, returns 0 if not set

Returns:
Type: 
Number

isSet() → {Boolean}

Returns true if set

Returns:
Type: 
Boolean

set(timeLeftopt)

Set the timer with seconds passed in

Parameters:
NameTypeAttributesDefaultDescription
timeLeftNumber<optional>
0

How much time left before the timer is elapsed in seconds

toString() → {String}

Returns this timer expressed as a string

Returns:
Type: 
String

unset()

Unset the timer

valueOf() → {Number}

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

Returns:
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Utilities.html b/docs/Utilities.html index 34882030..f6a81eb4 100644 --- a/docs/Utilities.html +++ b/docs/Utilities.html @@ -1,3 +1,3 @@ Namespace: Utilities
On this page

Utilities

LittleJS Utility Classes and Functions

  • General purpose math library
  • Vector2 - fast, simple, easy 2D vector class
  • Color - holds a rgba color with some math functions
  • Timer - tracks time automatically

Members

(static, constant) PI :Number

A shortcut to get Math.PI

Type:
  • Number
Default Value
  • Math.PI

Methods

(static) abs(value) → {Number}

Returns absoulte value of value passed in

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) clamp(value, minopt, maxopt) → {Number}

Clamps the value beween max and min

Parameters:
NameTypeAttributesDefaultDescription
valueNumber
minNumber<optional>
0
maxNumber<optional>
1
Returns:
Type: 
Number

(static) distanceAngle(angleA, angleB) → {Number}

Returns signed wrapped distance between the two angles passed in

Parameters:
NameTypeDescription
angleANumber
angleBNumber
Returns:
Type: 
Number

(static) distanceWrap(valueA, valueB, wrapSizeopt) → {Number}

Returns signed wrapped distance between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber
wrapSizeNumber<optional>
1
Returns:
Type: 
Number

(static) formatTime(t) → {String}

Formats seconds to mm:ss style for display purposes

Parameters:
NameTypeDescription
tNumber

time in seconds

Returns:
Type: 
String

(static) hsl(hopt, sopt, lopt, aopt) → {Color}

Create a color object with HSLA values

Parameters:
NameTypeAttributesDefaultDescription
hNumber<optional>
0

hue

sNumber<optional>
0

saturation

lNumber<optional>
1

lightness

aNumber<optional>
1

alpha

Returns:
Type: 
Color

(static) isOverlapping(pointA, sizeA, pointB, sizeB) → {Boolean}

Returns true if two axis aligned bounding boxes are overlapping

Parameters:
NameTypeDescription
pointAVector2

Center of box A

sizeAVector2

Size of box A

pointBVector2

Center of box B

sizeBVector2

Size of box B

Returns:
  • True if overlapping
Type: 
Boolean

(static) isVector2(v) → {Boolean}

Check if object is a valid Vector2

Parameters:
NameTypeDescription
vVector2
Returns:
Type: 
Boolean

(static) lerp(percent, valueA, valueB) → {Number}

Linearly interpolates between values passed in using percent

Parameters:
NameTypeDescription
percentNumber
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) lerpAngle(percent, angleA, angleB) → {Number}

Linearly interpolates between the angles passed in with wrappping

Parameters:
NameTypeDescription
percentNumber
angleANumber
angleBNumber
Returns:
Type: 
Number

(static) lerpWrap(percent, valueA, valueB, wrapSizeopt) → {Number}

Linearly interpolates between values passed in with wrappping

Parameters:
NameTypeAttributesDefaultDescription
percentNumber
valueANumber
valueBNumber
wrapSizeNumber<optional>
1
Returns:
Type: 
Number

(static) max(valueA, valueB) → {Number}

Returns highest of two values passed in

Parameters:
NameTypeDescription
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) min(valueA, valueB) → {Number}

Returns lowest of two values passed in

Parameters:
NameTypeDescription
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) mod(dividend, divisoropt) → {Number}

Returns first parm modulo the second param, but adjusted so negative numbers work as expected

Parameters:
NameTypeAttributesDefaultDescription
dividendNumber
divisorNumber<optional>
1
Returns:
Type: 
Number

(static) nearestPowerOfTwo(value) → {Number}

Returns the nearest power of two not less then the value

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) percent(value, valueA, valueB) → {Number}

Returns what percentage the value is between valueA and valueB

Parameters:
NameTypeDescription
valueNumber
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) rgb(ropt, gopt, bopt, aopt) → {Color}

Create a color object with RGBA values

Parameters:
NameTypeAttributesDefaultDescription
rNumber<optional>
1

red

gNumber<optional>
1

green

bNumber<optional>
1

blue

aNumber<optional>
1

alpha

Returns:
Type: 
Color

(static) sign(value) → {Number}

Returns the sign of value passed in (also returns 1 if 0)

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) smoothStep(percent) → {Number}

Applies smoothstep function to the percentage value

Parameters:
NameTypeDescription
percentNumber
Returns:
Type: 
Number

(static) vec2(xopt, yopt) → {Vector2}

Create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar

Parameters:
NameTypeAttributesDefaultDescription
xNumber<optional>
0
yNumber<optional>
0
Returns:
Type: 
Vector2
Example
let a = vec2(0, 1); // vector with coordinates (0, 1)
let b = vec2(a);    // copy a into b
a = vec2(5);        // set a to (5, 5)
b = vec2();         // set b to (0, 0)

(static) wave(frequencyopt, amplitudeopt, topt) → {Number}

Returns an oscillating wave between 0 and amplitude with frequency of 1 Hz by default

Parameters:
NameTypeAttributesDefaultDescription
frequencyNumber<optional>
1

Frequency of the wave in Hz

amplitudeNumber<optional>
1

Amplitude (max height) of the wave

tNumber<optional>
time

Value to use for time of the wave

Returns:
  • Value waving between 0 and amplitude
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Utilities

LittleJS Utility Classes and Functions

  • General purpose math library
  • Vector2 - fast, simple, easy 2D vector class
  • Color - holds a rgba color with some math functions
  • Timer - tracks time automatically
  • RandomGenerator - seeded random number generator

Members

(static, constant) PI :Number

A shortcut to get Math.PI

Type:
  • Number
Default Value
  • Math.PI

Methods

(static) abs(value) → {Number}

Returns absoulte value of value passed in

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) clamp(value, minopt, maxopt) → {Number}

Clamps the value beween max and min

Parameters:
NameTypeAttributesDefaultDescription
valueNumber
minNumber<optional>
0
maxNumber<optional>
1
Returns:
Type: 
Number

(static) distanceAngle(angleA, angleB) → {Number}

Returns signed wrapped distance between the two angles passed in

Parameters:
NameTypeDescription
angleANumber
angleBNumber
Returns:
Type: 
Number

(static) distanceWrap(valueA, valueB, wrapSizeopt) → {Number}

Returns signed wrapped distance between the two values passed in

Parameters:
NameTypeAttributesDefaultDescription
valueANumber
valueBNumber
wrapSizeNumber<optional>
1
Returns:
Type: 
Number

(static) formatTime(t) → {String}

Formats seconds to mm:ss style for display purposes

Parameters:
NameTypeDescription
tNumber

time in seconds

Returns:
Type: 
String

(static) hsl(hopt, sopt, lopt, aopt) → {Color}

Create a color object with HSLA values

Parameters:
NameTypeAttributesDefaultDescription
hNumber<optional>
0

hue

sNumber<optional>
0

saturation

lNumber<optional>
1

lightness

aNumber<optional>
1

alpha

Returns:
Type: 
Color

(static) isOverlapping(pointA, sizeA, pointB, sizeB) → {Boolean}

Returns true if two axis aligned bounding boxes are overlapping

Parameters:
NameTypeDescription
pointAVector2

Center of box A

sizeAVector2

Size of box A

pointBVector2

Center of box B

sizeBVector2

Size of box B

Returns:
  • True if overlapping
Type: 
Boolean

(static) isVector2(v) → {Boolean}

Check if object is a valid Vector2

Parameters:
NameTypeDescription
vVector2
Returns:
Type: 
Boolean

(static) lerp(percent, valueA, valueB) → {Number}

Linearly interpolates between values passed in using percent

Parameters:
NameTypeDescription
percentNumber
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) lerpAngle(percent, angleA, angleB) → {Number}

Linearly interpolates between the angles passed in with wrappping

Parameters:
NameTypeDescription
percentNumber
angleANumber
angleBNumber
Returns:
Type: 
Number

(static) lerpWrap(percent, valueA, valueB, wrapSizeopt) → {Number}

Linearly interpolates between values passed in with wrappping

Parameters:
NameTypeAttributesDefaultDescription
percentNumber
valueANumber
valueBNumber
wrapSizeNumber<optional>
1
Returns:
Type: 
Number

(static) max(valueA, valueB) → {Number}

Returns highest of two values passed in

Parameters:
NameTypeDescription
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) min(valueA, valueB) → {Number}

Returns lowest of two values passed in

Parameters:
NameTypeDescription
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) mod(dividend, divisoropt) → {Number}

Returns first parm modulo the second param, but adjusted so negative numbers work as expected

Parameters:
NameTypeAttributesDefaultDescription
dividendNumber
divisorNumber<optional>
1
Returns:
Type: 
Number

(static) nearestPowerOfTwo(value) → {Number}

Returns the nearest power of two not less then the value

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) percent(value, valueA, valueB) → {Number}

Returns what percentage the value is between valueA and valueB

Parameters:
NameTypeDescription
valueNumber
valueANumber
valueBNumber
Returns:
Type: 
Number

(static) rgb(ropt, gopt, bopt, aopt) → {Color}

Create a color object with RGBA values

Parameters:
NameTypeAttributesDefaultDescription
rNumber<optional>
1

red

gNumber<optional>
1

green

bNumber<optional>
1

blue

aNumber<optional>
1

alpha

Returns:
Type: 
Color

(static) sign(value) → {Number}

Returns the sign of value passed in (also returns 1 if 0)

Parameters:
NameTypeDescription
valueNumber
Returns:
Type: 
Number

(static) smoothStep(percent) → {Number}

Applies smoothstep function to the percentage value

Parameters:
NameTypeDescription
percentNumber
Returns:
Type: 
Number

(static) vec2(xopt, yopt) → {Vector2}

Create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar

Parameters:
NameTypeAttributesDefaultDescription
xNumber<optional>
0
yNumber<optional>
0
Returns:
Type: 
Vector2
Example
let a = vec2(0, 1); // vector with coordinates (0, 1)
let b = vec2(a);    // copy a into b
a = vec2(5);        // set a to (5, 5)
b = vec2();         // set b to (0, 0)

(static) wave(frequencyopt, amplitudeopt, topt) → {Number}

Returns an oscillating wave between 0 and amplitude with frequency of 1 Hz by default

Parameters:
NameTypeAttributesDefaultDescription
frequencyNumber<optional>
1

Frequency of the wave in Hz

amplitudeNumber<optional>
1

Amplitude (max height) of the wave

tNumber<optional>
time

Value to use for time of the wave

Returns:
  • Value waving between 0 and amplitude
Type: 
Number
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/Vector2.html b/docs/Vector2.html index 45cb3257..ab1b4086 100644 --- a/docs/Vector2.html +++ b/docs/Vector2.html @@ -1,3 +1,3 @@ Class: Vector2
On this page

Vector2

2D Vector object with vector math library

  • Functions do not change this so they can be chained together

Constructor

new Vector2(xopt, yopt)

Create a 2D vector with the x and y passed in, can also be created with vec2()

Parameters:
NameTypeAttributesDefaultDescription
xNumber<optional>
0

X axis location

yNumber<optional>
0

Y axis location

Example
let a = new Vector2(2, 3); // vector with coordinates (2, 3)
let b = new Vector2;       // vector with coordinates (0, 0)
let c = vec2(4, 2);        // use the vec2 function to make a Vector2
let d = a.add(b).scale(5); // operators can be chained

Members

x

Properties
TypeDescription
Number

X axis location

y

Properties
TypeDescription
Number

Y axis location

Methods

add(v) → {Vector2}

Returns a copy of this vector plus the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

angle() → {Number}

Returns the angle of this vector, up is angle 0

Returns:
Type: 
Number

area() → {Number}

Returns the area this vector covers as a rectangle

Returns:
Type: 
Number

arrayCheck(arraySize) → {Boolean}

Returns true if this vector is within the bounds of an array size passed in

Parameters:
NameTypeDescription
arraySizeVector2
Returns:
Type: 
Boolean

clampLength(lengthopt) → {Vector2}

Returns a new vector clamped to length passed in

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2

copy() → {Vector2}

Returns a new vector that is a copy of this

Returns:
Type: 
Vector2

cross(v) → {Number}

Returns the cross product of this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

direction() → {Number}

Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)

Returns:
Type: 
Number

distance(v) → {Number}

Returns the distance from this vector to vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

distanceSquared(v) → {Number}

Returns the distance squared from this vector to vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

divide(v) → {Vector2}

Returns a copy of this vector divided by the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

dot(v) → {Number}

Returns the dot product of this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

floor() → {Vector2}

Returns a copy of this vector with each axis floored

Returns:
Type: 
Vector2

invert() → {Vector2}

Returns a copy of this vector that has been inverted

Returns:
Type: 
Vector2

length() → {Number}

Returns the length of this vector

Returns:
Type: 
Number

lengthSquared() → {Number}

Returns the length of this vector squared

Returns:
Type: 
Number

lerp(v, percent) → {Vector2}

Returns a new vector that is p percent between this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

percentNumber
Returns:
Type: 
Vector2

multiply(v) → {Vector2}

Returns a copy of this vector times the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

normalize(lengthopt) → {Vector2}

Returns a new vector in same direction as this one with the length passed in

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2

rotate(angle) → {Vector2}

Returns copy of this vector rotated by the angle passed in

Parameters:
NameTypeDescription
angleNumber
Returns:
Type: 
Vector2

scale(s) → {Vector2}

Returns a copy of this vector scaled by the vector passed in

Parameters:
NameTypeDescription
sNumber

scale

Returns:
Type: 
Vector2

setAngle(angleopt, lengthopt) → {Vector2}

Sets this vector with angle and length passed in

Parameters:
NameTypeAttributesDefaultDescription
angleNumber<optional>
0
lengthNumber<optional>
1
Returns:
Type: 
Vector2

subtract(v) → {Vector2}

Returns a copy of this vector minus the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

toString(digits) → {String}

Returns this vector expressed as a string

Parameters:
NameTypeDefaultDescription
digitsfloat3

precision to display

Returns:
Type: 
String
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

Vector2

2D Vector object with vector math library

  • Functions do not change this so they can be chained together

Constructor

new Vector2(xopt, yopt)

Create a 2D vector with the x and y passed in, can also be created with vec2()

Parameters:
NameTypeAttributesDefaultDescription
xNumber<optional>
0

X axis location

yNumber<optional>
0

Y axis location

Example
let a = new Vector2(2, 3); // vector with coordinates (2, 3)
let b = new Vector2;       // vector with coordinates (0, 0)
let c = vec2(4, 2);        // use the vec2 function to make a Vector2
let d = a.add(b).scale(5); // operators can be chained

Members

x

Properties
TypeDescription
Number

X axis location

y

Properties
TypeDescription
Number

Y axis location

Methods

add(v) → {Vector2}

Returns a copy of this vector plus the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

angle() → {Number}

Returns the angle of this vector, up is angle 0

Returns:
Type: 
Number

area() → {Number}

Returns the area this vector covers as a rectangle

Returns:
Type: 
Number

arrayCheck(arraySize) → {Boolean}

Returns true if this vector is within the bounds of an array size passed in

Parameters:
NameTypeDescription
arraySizeVector2
Returns:
Type: 
Boolean

clampLength(lengthopt) → {Vector2}

Returns a new vector clamped to length passed in

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2

copy() → {Vector2}

Returns a new vector that is a copy of this

Returns:
Type: 
Vector2

cross(v) → {Number}

Returns the cross product of this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

direction() → {Number}

Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)

Returns:
Type: 
Number

distance(v) → {Number}

Returns the distance from this vector to vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

distanceSquared(v) → {Number}

Returns the distance squared from this vector to vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

divide(v) → {Vector2}

Returns a copy of this vector divided by the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

dot(v) → {Number}

Returns the dot product of this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Number

floor() → {Vector2}

Returns a copy of this vector with each axis floored

Returns:
Type: 
Vector2

invert() → {Vector2}

Returns a copy of this vector that has been inverted

Returns:
Type: 
Vector2

length() → {Number}

Returns the length of this vector

Returns:
Type: 
Number

lengthSquared() → {Number}

Returns the length of this vector squared

Returns:
Type: 
Number

lerp(v, percent) → {Vector2}

Returns a new vector that is p percent between this and the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

percentNumber
Returns:
Type: 
Vector2

multiply(v) → {Vector2}

Returns a copy of this vector times the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

normalize(lengthopt) → {Vector2}

Returns a new vector in same direction as this one with the length passed in

Parameters:
NameTypeAttributesDefaultDescription
lengthNumber<optional>
1
Returns:
Type: 
Vector2

rotate(angle) → {Vector2}

Returns copy of this vector rotated by the angle passed in

Parameters:
NameTypeDescription
angleNumber
Returns:
Type: 
Vector2

scale(s) → {Vector2}

Returns a copy of this vector scaled by the vector passed in

Parameters:
NameTypeDescription
sNumber

scale

Returns:
Type: 
Vector2

setAngle(angleopt, lengthopt) → {Vector2}

Sets this vector with angle and length passed in

Parameters:
NameTypeAttributesDefaultDescription
angleNumber<optional>
0
lengthNumber<optional>
1
Returns:
Type: 
Vector2

subtract(v) → {Vector2}

Returns a copy of this vector minus the vector passed in

Parameters:
NameTypeDescription
vVector2

other vector

Returns:
Type: 
Vector2

toString(digits) → {String}

Returns this vector expressed as a string

Parameters:
NameTypeDefaultDescription
digitsfloat3

precision to display

Returns:
Type: 
String
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/WebGL.html b/docs/WebGL.html index 830446fe..4a7f07f0 100644 --- a/docs/WebGL.html +++ b/docs/WebGL.html @@ -1,3 +1,3 @@ Namespace: WebGL
On this page

WebGL

LittleJS WebGL Interface

  • All webgl used by the engine is wrapped up here
  • For normal stuff you won't need to see or call anything in this file
  • For advanced stuff there are helper functions to create shaders, textures, etc
  • Can be disabled with glEnable to revert to 2D canvas rendering
  • Batches sprite rendering on GPU for incredibly fast performance
  • Sprite transform math is done in the shader where possible

Members

(static) glCanvas :HTMLCanvasElement

The WebGL canvas which appears above the main canvas and below the overlay canvas

Type:
  • HTMLCanvasElement

(static) glContext :WebGLRenderingContext

2d context for glCanvas

Type:
  • WebGLRenderingContext

(static) glTileTexture :WebGLTexture

Main tile sheet texture automatically loaded by engine

Type:
  • WebGLTexture

Methods

(static) glCompileShader(source, type) → {WebGLShader}

Compile WebGL shader of the given type, will throw errors if in debug mode

Parameters:
NameTypeDescription
sourceString
type
Returns:
Type: 
WebGLShader

(static) glCopyToContext(context, forceDrawopt)

Draw any sprites still in the buffer, copy to main canvas and clear

Parameters:
NameTypeAttributesDefaultDescription
contextCanvasRenderingContext2D
forceDrawBoolean<optional>
0

(static) glCreateProgram(vsSource, fsSource) → {WebGLProgram}

Create WebGL program with given shaders

Parameters:
NameTypeDescription
vsSourceWebGLShader
fsSourceWebGLShader
Returns:
Type: 
WebGLProgram

(static) glCreateTexture(image) → {WebGLTexture}

Create WebGL texture from an image and set the texture settings

Parameters:
NameTypeDescription
imageImage
Returns:
Type: 
WebGLTexture

(static) glDraw(x, y, sizeX, sizeY, angle, uv0X, uv0Y, uv1X, uv1Y, rgba, rgbaAdditiveopt)

Add a sprite to the gl draw list, used by all gl draw functions

Parameters:
NameTypeAttributesDefaultDescription
x
y
sizeX
sizeY
angle
uv0X
uv0Y
uv1X
uv1Y
rgba
rgbaAdditive<optional>
0

(static) glFlush()

Draw all sprites and clear out the buffer, called automatically by the system whenever necessary

(static) glInitPostProcess(shaderCode, includeOverlay)

Set up a post processing shader

Parameters:
NameTypeDescription
shaderCodeString
includeOverlayBoolean

(static) glSetBlendMode(additiveopt)

Set the WebGl blend mode, normally you should call setBlendMode instead

Parameters:
NameTypeAttributesDefaultDescription
additiveBoolean<optional>
0

(static) glSetTexture(textureopt)

Set the WebGl texture, not normally necessary unless multiple tile sheets are used

  • This may also flush the gl buffer resulting in more draw calls and worse performance
Parameters:
NameTypeAttributesDefaultDescription
textureWebGLTexture<optional>
glTileTexture
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file +
On this page

WebGL

LittleJS WebGL Interface

  • All webgl used by the engine is wrapped up here
  • For normal stuff you won't need to see or call anything in this file
  • For advanced stuff there are helper functions to create shaders, textures, etc
  • Can be disabled with glEnable to revert to 2D canvas rendering
  • Batches sprite rendering on GPU for incredibly fast performance
  • Sprite transform math is done in the shader where possible

Members

(static) glCanvas :HTMLCanvasElement

The WebGL canvas which appears above the main canvas and below the overlay canvas

Type:
  • HTMLCanvasElement

(static) glContext :WebGLRenderingContext

2d context for glCanvas

Type:
  • WebGLRenderingContext

(static) glTileTexture :WebGLTexture

Main tile sheet texture automatically loaded by engine

Type:
  • WebGLTexture

Methods

(static) glCompileShader(source, type) → {WebGLShader}

Compile WebGL shader of the given type, will throw errors if in debug mode

Parameters:
NameTypeDescription
sourceString
type
Returns:
Type: 
WebGLShader

(static) glCopyToContext(context, forceDrawopt)

Draw any sprites still in the buffer, copy to main canvas and clear

Parameters:
NameTypeAttributesDefaultDescription
contextCanvasRenderingContext2D
forceDrawBoolean<optional>
0

(static) glCreateProgram(vsSource, fsSource) → {WebGLProgram}

Create WebGL program with given shaders

Parameters:
NameTypeDescription
vsSourceWebGLShader
fsSourceWebGLShader
Returns:
Type: 
WebGLProgram

(static) glCreateTexture(image) → {WebGLTexture}

Create WebGL texture from an image and set the texture settings

Parameters:
NameTypeDescription
imageImage
Returns:
Type: 
WebGLTexture

(static) glDraw(x, y, sizeX, sizeY, angle, uv0X, uv0Y, uv1X, uv1Y, rgba, rgbaAdditiveopt)

Add a sprite to the gl draw list, used by all gl draw functions

Parameters:
NameTypeAttributesDefaultDescription
xNumber
yNumber
sizeXNumber
sizeYNumber
angleNumber
uv0XNumber
uv0YNumber
uv1XNumber
uv1YNumber
rgbaNumber
rgbaAdditiveNumber<optional>
0

(static) glDrawPoints(points, rgba)

Add a convex polygon to the gl draw list

Parameters:
NameTypeDescription
pointsArray

Array of Vector2 points

rgbaNumber

Color of the polygon

(static) glFlush()

Draw all sprites and clear out the buffer, called automatically by the system whenever necessary

(static) glInitPostProcess(shaderCode, includeOverlay)

Set up a post processing shader

Parameters:
NameTypeDescription
shaderCodeString
includeOverlayBoolean

(static) glSetBlendMode(additiveopt)

Set the WebGl blend mode, normally you should call setBlendMode instead

Parameters:
NameTypeAttributesDefaultDescription
additiveBoolean<optional>
0

(static) glSetTexture(textureopt)

Set the WebGl texture, not normally necessary unless multiple tile sheets are used

  • This may also flush the gl buffer resulting in more draw calls and worse performance
Parameters:
NameTypeAttributesDefaultDescription
textureWebGLTexture<optional>
glTileTexture
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/data/search.json b/docs/data/search.json index 43859fa1..b79c9463 100644 --- a/docs/data/search.json +++ b/docs/data/search.json @@ -1 +1 @@ -{"list":[{"title":"Audio","link":"Audio","description":"

LittleJS Audio System

\n"},{"title":"Audio.audioContext","link":"audioContext","description":"

Audio context used by the engine

"},{"title":"Audio.getNoteFrequency","link":"getNoteFrequency","description":"

Get frequency of a note on a musical scale

"},{"title":"Audio.playAudioFile","link":"playAudioFile","description":"

Play an mp3 or wav audio from a local file or url

"},{"title":"Audio.playSamples","link":"playSamples","description":"

Play cached audio samples with given settings

"},{"title":"Audio.speak","link":"speak","description":"

Speak text with passed in settings

"},{"title":"Audio.speakStop","link":"speakStop","description":"

Stop all queued speech

"},{"title":"Audio.zzfx","link":"zzfx","description":"

Generate and play a ZzFX sound

\n

Create sounds using the ZzFX Sound Designer.

"},{"title":"Audio.zzfxG","link":"zzfxG","description":"

Generate samples for a ZzFX sound

"},{"title":"Audio.zzfxM","link":"zzfxM","description":"

Generate samples for a ZzFM song with given parameters

"},{"title":"Audio.zzfxR","link":"zzfxR","description":"

Sample rate used for all ZzFX sounds

"},{"title":"Color","link":"Color","description":"

Create a color with the rgba components passed in, white by default

"},{"title":"Color#a","link":"a"},{"title":"Color#add","link":"add","description":"

Returns a copy of this color plus the color passed in

"},{"title":"Color#b","link":"b"},{"title":"Color#clamp","link":"clamp","description":"

Returns a copy of this color clamped to the valid range between 0 and 1

"},{"title":"Color#copy","link":"copy","description":"

Returns a new color that is a copy of this

"},{"title":"Color#divide","link":"divide","description":"

Returns a copy of this color divided by the color passed in

"},{"title":"Color#g","link":"g"},{"title":"Color#getHSLA","link":"getHSLA","description":"

Returns this color expressed in hsla format

"},{"title":"Color#lerp","link":"lerp","description":"

Returns a new color that is p percent between this and the color passed in

"},{"title":"Color#multiply","link":"multiply","description":"

Returns a copy of this color times the color passed in

"},{"title":"Color#mutate","link":"mutate","description":"

Returns a new color that has each component randomly adjusted

"},{"title":"Color#r","link":"r"},{"title":"Color#rgbaInt","link":"rgbaInt","description":"

Returns this color expressed as 32 bit RGBA value

"},{"title":"Color#scale","link":"scale","description":"

Returns a copy of this color scaled by the value passed in, alpha can be scaled separately

"},{"title":"Color#setHSLA","link":"setHSLA","description":"

Sets this color given a hue, saturation, lightness, and alpha

"},{"title":"Color#setHex","link":"setHex","description":"

Set this color from a hex code

"},{"title":"Color#subtract","link":"subtract","description":"

Returns a copy of this color minus the color passed in

"},{"title":"Color#toString","link":"toString","description":"

Returns this color expressed as a hex color code

"},{"title":"Debug","link":"Debug","description":"

LittleJS Debug System

\n"},{"title":"Debug.ASSERT","link":"ASSERT","description":"

Asserts if the experssion is false, does not do anything in release builds

"},{"title":"Debug.debug","link":"debug","description":"

True if debug is enabled

"},{"title":"Debug.debugAABB","link":"debugAABB","description":"

Draw a debug axis aligned bounding box in world space

"},{"title":"Debug.debugCircle","link":"debugCircle","description":"

Draw a debug circle in world space

"},{"title":"Debug.debugClear","link":"debugClear","description":"

Clear all debug primitives in the list

"},{"title":"Debug.debugKey","link":"debugKey","description":"

Key code used to toggle debug mode, Esc by default

"},{"title":"Debug.debugLine","link":"debugLine","description":"

Draw a debug line in world space

"},{"title":"Debug.debugPoint","link":"debugPoint","description":"

Draw a debug point in world space

"},{"title":"Debug.debugPointSize","link":"debugPointSize","description":"

Size to render debug points by default

"},{"title":"Debug.debugRect","link":"debugRect","description":"

Draw a debug rectangle in world space

"},{"title":"Debug.debugSaveCanvas","link":"debugSaveCanvas","description":"

Save a canvas to disk

"},{"title":"Debug.debugText","link":"debugText","description":"

Draw a debug axis aligned bounding box in world space

"},{"title":"Debug.enableAsserts","link":"enableAsserts","description":"

True if asserts are enaled

"},{"title":"Debug.setDebugKey","link":"setDebugKey","description":"

Set key code used to toggle debug mode, Esc by default

"},{"title":"Debug.setShowWatermark","link":"setShowWatermark","description":"

Set if watermark with FPS should be shown

"},{"title":"Debug.showWatermark","link":"showWatermark","description":"

True if watermark with FPS should be shown, false in release builds

"},{"title":"Draw","link":"Draw","description":"

LittleJS Drawing System

\n\n

LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL.\nThere are 3 canvas/contexts available to draw to...\nmainCanvas - 2D background canvas, non WebGL stuff like tile layers are drawn here.\nglCanvas - Used by the accelerated WebGL batch rendering system.\noverlayCanvas - Another 2D canvas that appears on top of the other 2 canvases.

\n

The WebGL rendering system is very fast with some caveats...

\n\n

The LittleJS rendering solution is intentionally simple, feel free to adjust it for your needs!

"},{"title":"Draw.drawCanvas2D","link":"drawCanvas2D","description":"

Draw directly to a 2d canvas context in world space

"},{"title":"Draw.drawLine","link":"drawLine","description":"

Draw colored line between two points

"},{"title":"Draw.drawRect","link":"drawRect","description":"

Draw colored rect centered on pos

"},{"title":"Draw.drawRectScreenSpace","link":"drawRectScreenSpace","description":"

Draw colored rectangle in screen space

"},{"title":"Draw.drawText","link":"drawText","description":"

Draw text on overlay canvas in world space\nAutomatically splits new lines into rows

"},{"title":"Draw.drawTextScreen","link":"drawTextScreen","description":"

Draw text on overlay canvas in screen space\nAutomatically splits new lines into rows

"},{"title":"Draw.drawTile","link":"drawTile","description":"

Draw textured tile centered in world space, with color applied if using WebGL

"},{"title":"Draw.drawTileScreenSpace","link":"drawTileScreenSpace","description":"

Draw textured tile centered on pos in screen space

"},{"title":"Draw.isFullscreen","link":"isFullscreen","description":"

Returns true if fullscreen mode is active

"},{"title":"Draw.mainCanvas","link":"mainCanvas","description":"

The primary 2D canvas visible to the user

"},{"title":"Draw.mainCanvasSize","link":"mainCanvasSize","description":"

The size of the main canvas (and other secondary canvases)

"},{"title":"Draw.mainContext","link":"mainContext","description":"

2d context for mainCanvas

"},{"title":"Draw.overlayCanvas","link":"overlayCanvas","description":"

A canvas that appears on top of everything the same size as mainCanvas

"},{"title":"Draw.overlayContext","link":"overlayContext","description":"

2d context for overlayCanvas

"},{"title":"Draw.screenToWorld","link":"screenToWorld","description":"

Convert from screen to world space coordinates

\n"},{"title":"Draw.setBlendMode","link":"setBlendMode","description":"

Enable normal or additive blend mode

"},{"title":"Draw.tileImage","link":"tileImage","description":"

Tile sheet for batch rendering system

"},{"title":"Draw.toggleFullscreen","link":"toggleFullscreen","description":"

Toggle fullsceen mode

"},{"title":"Draw.worldToScreen","link":"worldToScreen","description":"

Convert from world to screen space coordinates

\n"},{"title":"Engine","link":"Engine","description":"

LittleJS - The Tiny JavaScript Game Engine That Can!\nMIT License - Copyright 2021 Frank Force

\n

Engine Features

\n"},{"title":"Engine.engineInit","link":"engineInit","description":"

Start up LittleJS engine with your callback functions

"},{"title":"Engine.engineName","link":"engineName","description":"

Name of engine

"},{"title":"Engine.engineObjects","link":"engineObjects","description":"

Array containing all engine objects

"},{"title":"Engine.engineObjectsCallback","link":"engineObjectsCallback","description":"

Triggers a callback for each object within a given area

"},{"title":"Engine.engineObjectsCollide","link":"engineObjectsCollide","description":"

Array containing only objects that are set to collide with other objects this frame (for optimization)

"},{"title":"Engine.engineObjectsDestroy","link":"engineObjectsDestroy","description":"

Destroy and remove all objects

"},{"title":"Engine.engineObjectsUpdate","link":"engineObjectsUpdate","description":"

Update each engine object, remove destroyed objects, and update time

"},{"title":"Engine.engineVersion","link":"engineVersion","description":"

Version of engine

"},{"title":"Engine.frame","link":"frame","description":"

Current update frame, used to calculate time

"},{"title":"Engine.frameRate","link":"frameRate","description":"

Frames per second to update objects

"},{"title":"Engine.paused","link":"paused","description":"

Is the game paused? Causes time and objects to not be updated

"},{"title":"Engine.setPaused","link":"setPaused","description":"

Set if game is paused

"},{"title":"Engine.time","link":"time","description":"

Current engine time since start in seconds, derived from frame

"},{"title":"Engine.timeDelta","link":"timeDelta","description":"

How many seconds each frame lasts, engine uses a fixed time step

"},{"title":"Engine.timeReal","link":"timeReal","description":"

Actual clock time since start in seconds (not affected by pause or frame rate clamping)

"},{"title":"EngineObject","link":"EngineObject","description":"

Create an engine object and adds it to the list of objects

"},{"title":"EngineObject#addChild","link":"addChild","description":"

Attaches a child to this with a given local transform

"},{"title":"EngineObject#additiveColor","link":"additiveColor"},{"title":"EngineObject#angle","link":"angle"},{"title":"EngineObject#angleDamping","link":"angleDamping"},{"title":"EngineObject#angleVelocity","link":"angleVelocity"},{"title":"EngineObject#applyAcceleration","link":"applyAcceleration","description":"

Apply acceleration to this object (adjust velocity, not affected by mass)

"},{"title":"EngineObject#applyForce","link":"applyForce","description":"

Apply force to this object (adjust velocity, affected by mass)

"},{"title":"EngineObject#collideWithObject","link":"collideWithObject","description":"

Called to check if a object collision should be resolved

"},{"title":"EngineObject#collideWithTile","link":"collideWithTile","description":"

Called to check if a tile collision should be resolved

"},{"title":"EngineObject#collideWithTileRaycast","link":"collideWithTileRaycast","description":"

Called to check if a tile raycast hit

"},{"title":"EngineObject#color","link":"color"},{"title":"EngineObject#damping","link":"damping"},{"title":"EngineObject#destroy","link":"destroy","description":"

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

"},{"title":"EngineObject#drawSize","link":"drawSize"},{"title":"EngineObject#elasticity","link":"elasticity"},{"title":"EngineObject#friction","link":"friction"},{"title":"EngineObject#getAliveTime","link":"getAliveTime","description":"

How long since the object was created

"},{"title":"EngineObject#getMirrorSign","link":"getMirrorSign","description":"

Get the direction of the mirror

"},{"title":"EngineObject#gravityScale","link":"gravityScale"},{"title":"EngineObject#mass","link":"mass"},{"title":"EngineObject#pos","link":"pos"},{"title":"EngineObject#removeChild","link":"removeChild","description":"

Removes a child from this one

"},{"title":"EngineObject#render","link":"render","description":"

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

"},{"title":"EngineObject#renderOrder","link":"renderOrder"},{"title":"EngineObject#setCollision","link":"setCollision","description":"

Set how this object collides

"},{"title":"EngineObject#size","link":"size"},{"title":"EngineObject#tileIndex","link":"tileIndex"},{"title":"EngineObject#tileSize","link":"tileSize"},{"title":"EngineObject#toString","link":"toString","description":"

Returns string containg info about this object for debugging

"},{"title":"EngineObject#update","link":"update","description":"

Update the object transform and physics, called automatically by engine once each frame

"},{"title":"EngineObject#velocity","link":"velocity"},{"title":"FontImage","link":"FontImage","description":"

Create an image font

"},{"title":"FontImage#drawText","link":"drawText","description":"

Draw text in world space using the image font

"},{"title":"FontImage#drawTextScreen","link":"drawTextScreen","description":"

Draw text in screen space using the image font

"},{"title":"Input","link":"Input","description":"

LittleJS Input System

\n"},{"title":"Input.clearInput","link":"clearInput","description":"

Clears all input

"},{"title":"Input.gamepadIsDown","link":"gamepadIsDown","description":"

Returns true if gamepad button is down

"},{"title":"Input.gamepadStick","link":"gamepadStick","description":"

Returns gamepad stick value

"},{"title":"Input.gamepadWasPressed","link":"gamepadWasPressed","description":"

Returns true if gamepad button was pressed

"},{"title":"Input.gamepadWasReleased","link":"gamepadWasReleased","description":"

Returns true if gamepad button was released

"},{"title":"Input.isTouchDevice","link":"isTouchDevice","description":"

True if a touch device has been detected

"},{"title":"Input.isUsingGamepad","link":"isUsingGamepad","description":"

Returns true if user is using gamepad (has more recently pressed a gamepad button)

"},{"title":"Input.keyIsDown","link":"keyIsDown","description":"

Returns true if device key is down

"},{"title":"Input.keyWasPressed","link":"keyWasPressed","description":"

Returns true if device key was pressed this frame

"},{"title":"Input.keyWasReleased","link":"keyWasReleased","description":"

Returns true if device key was released this frame

"},{"title":"Input.mouseIsDown","link":"mouseIsDown","description":"

Returns true if mouse button is down

"},{"title":"Input.mousePos","link":"mousePos","description":"

Mouse pos in world space

"},{"title":"Input.mousePosScreen","link":"mousePosScreen","description":"

Mouse pos in screen space

"},{"title":"Input.mouseWasPressed","link":"mouseWasPressed","description":"

Returns true if mouse button was pressed

"},{"title":"Input.mouseWasReleased","link":"mouseWasReleased","description":"

Returns true if mouse button was released

"},{"title":"Input.mouseWheel","link":"mouseWheel","description":"

Mouse wheel delta this frame

"},{"title":"Input.preventDefaultInput","link":"preventDefaultInput","description":"

Prevents input continuing to the default browser handling (false by default)

"},{"title":"Input.vibrate","link":"vibrate","description":"

Pulse the vibration hardware if it exists

"},{"title":"Input.vibrateStop","link":"vibrateStop","description":"

Cancel any ongoing vibration

"},{"title":"Medal","link":"Medal","description":"

Create an medal object and adds it to the list of medals

"},{"title":"Medal#render","link":"render","description":"

Render a medal

"},{"title":"Medal#renderIcon","link":"renderIcon","description":"

Render the icon for a medal

"},{"title":"Medal#unlock","link":"unlock","description":"

Unlocks a medal if not already unlocked

"},{"title":"Medals","link":"Medals","description":"

LittleJS Medal System

\n"},{"title":"Medals.medals","link":"medals","description":"

List of all medals

"},{"title":"Medals.medalsInit","link":"medalsInit","description":"

Initialize medals with a save name used for storage

\n"},{"title":"Medals.newgroundsInit","link":"newgroundsInit","description":"

This can used to enable Newgrounds functionality

"},{"title":"Music","link":"Music","description":"

Create a music object and cache the zzfx music samples for later use

"},{"title":"Music#isPlaying","link":"isPlaying","description":"

Check if music is playing

"},{"title":"Music#play","link":"play","description":"

Play the music

"},{"title":"Music#stop","link":"stop","description":"

Stop the music

"},{"title":"Newgrounds","link":"Newgrounds","description":"

Create a newgrounds object

"},{"title":"Newgrounds#call","link":"call","description":"

Send a message to call a component of the Newgrounds API

"},{"title":"Newgrounds#getScores","link":"getScores","description":"

Get scores from a scoreboard

"},{"title":"Newgrounds#logView","link":"logView","description":"

Send message to log a view

"},{"title":"Newgrounds#postScore","link":"postScore","description":"

Send message to post score

"},{"title":"Newgrounds#unlockMedal","link":"unlockMedal","description":"

Send message to unlock a medal by id

"},{"title":"Particle","link":"Particle","description":"

Create a particle with the given settings

"},{"title":"Particle#render","link":"render","description":"

Render the particle, automatically called each frame, sorted by renderOrder

"},{"title":"ParticleEmitter","link":"ParticleEmitter","description":"

Create a particle system with the given settings

"},{"title":"ParticleEmitter#additive","link":"additive"},{"title":"ParticleEmitter#angleDamping","link":"angleDamping"},{"title":"ParticleEmitter#angleSpeed","link":"angleSpeed"},{"title":"ParticleEmitter#collideTiles","link":"collideTiles"},{"title":"ParticleEmitter#colorEndA","link":"colorEndA"},{"title":"ParticleEmitter#colorEndB","link":"colorEndB"},{"title":"ParticleEmitter#colorStartA","link":"colorStartA"},{"title":"ParticleEmitter#colorStartB","link":"colorStartB"},{"title":"ParticleEmitter#damping","link":"damping"},{"title":"ParticleEmitter#emitConeAngle","link":"emitConeAngle"},{"title":"ParticleEmitter#emitParticle","link":"emitParticle","description":"

Spawn one particle

"},{"title":"ParticleEmitter#emitRate","link":"emitRate"},{"title":"ParticleEmitter#emitSize","link":"emitSize"},{"title":"ParticleEmitter#emitTime","link":"emitTime"},{"title":"ParticleEmitter#fadeRate","link":"fadeRate"},{"title":"ParticleEmitter#gravityScale","link":"gravityScale"},{"title":"ParticleEmitter#localSpace","link":"localSpace"},{"title":"ParticleEmitter#particleConeAngle","link":"particleConeAngle"},{"title":"ParticleEmitter#particleTime","link":"particleTime"},{"title":"ParticleEmitter#randomColorLinear","link":"randomColorLinear"},{"title":"ParticleEmitter#randomness","link":"randomness"},{"title":"ParticleEmitter#sizeEnd","link":"sizeEnd"},{"title":"ParticleEmitter#sizeStart","link":"sizeStart"},{"title":"ParticleEmitter#speed","link":"speed"},{"title":"ParticleEmitter#trailScale","link":"trailScale"},{"title":"ParticleEmitter#update","link":"update","description":"

Update the emitter to spawn particles, called automatically by engine once each frame

"},{"title":"Random","link":"Random","description":"

Random global functions

"},{"title":"Random.rand","link":"rand","description":"

Returns a random value between the two values passed in

"},{"title":"Random.randColor","link":"randColor","description":"

Returns a random color between the two passed in colors, combine components if linear

"},{"title":"Random.randInCircle","link":"randInCircle","description":"

Returns a random Vector2 within a circular shape

"},{"title":"Random.randInt","link":"randInt","description":"

Returns a floored random value the two values passed in

"},{"title":"Random.randSign","link":"randSign","description":"

Randomly returns either -1 or 1

"},{"title":"Random.randVector","link":"randVector","description":"

Returns a random Vector2 with the passed in length

"},{"title":"RandomGenerator","link":"RandomGenerator","description":"

Create a random number generator with the seed passed in

"},{"title":"RandomGenerator#rand","link":"rand","description":"

Returns a seeded random value between the two values passed in

"},{"title":"RandomGenerator#randInt","link":"randInt","description":"

Returns a floored seeded random value the two values passed in

"},{"title":"RandomGenerator#randSign","link":"randSign","description":"

Randomly returns either -1 or 1 deterministically

"},{"title":"RandomGenerator#seed","link":"seed"},{"title":"Settings","link":"Settings","description":"

LittleJS Engine Settings

"},{"title":"Settings.cameraPos","link":"cameraPos","description":"

Position of camera in world space

"},{"title":"Settings.cameraScale","link":"cameraScale","description":"

Scale of camera in world space

"},{"title":"Settings.canvasFixedSize","link":"canvasFixedSize","description":"

Fixed size of the canvas, if enabled canvas size never changes

\n"},{"title":"Settings.canvasMaxSize","link":"canvasMaxSize","description":"

The max size of the canvas, centered if window is larger

"},{"title":"Settings.canvasPixelated","link":"canvasPixelated","description":"

Disables filtering for crisper pixel art if true

"},{"title":"Settings.enablePhysicsSolver","link":"enablePhysicsSolver","description":"

Enable physics solver for collisions between objects

"},{"title":"Settings.fontDefault","link":"fontDefault","description":"

Default font used for text rendering

"},{"title":"Settings.gamepadDirectionEmulateStick","link":"gamepadDirectionEmulateStick","description":"

If true, the dpad input is also routed to the left analog stick (for better accessability)

"},{"title":"Settings.gamepadsEnable","link":"gamepadsEnable","description":"

Should gamepads be allowed

"},{"title":"Settings.glEnable","link":"glEnable","description":"

Enable webgl rendering, webgl can be disabled and removed from build (with some features disabled)

"},{"title":"Settings.glOverlay","link":"glOverlay","description":"

Fixes slow rendering in some browsers by not compositing the WebGL canvas

"},{"title":"Settings.gravity","link":"gravity","description":"

How much gravity to apply to objects along the Y axis, negative is down

"},{"title":"Settings.inputWASDEmulateDirection","link":"inputWASDEmulateDirection","description":"

If true the WASD keys are also routed to the direction keys (for better accessability)

"},{"title":"Settings.medalDisplayIconSize","link":"medalDisplayIconSize","description":"

Size of icon in medal display

"},{"title":"Settings.medalDisplaySize","link":"medalDisplaySize","description":"

Size of medal display

"},{"title":"Settings.medalDisplaySlideTime","link":"medalDisplaySlideTime","description":"

How quickly to slide on/off medals in seconds

"},{"title":"Settings.medalDisplayTime","link":"medalDisplayTime","description":"

How long to show medals for in seconds

"},{"title":"Settings.medalsPreventUnlock","link":"medalsPreventUnlock","description":"

Set to stop medals from being unlockable (like if cheats are enabled)

"},{"title":"Settings.objectDefaultAngleDamping","link":"objectDefaultAngleDamping","description":"

How much to slow angular velocity each frame (0-1)

"},{"title":"Settings.objectDefaultDamping","link":"objectDefaultDamping","description":"

How much to slow velocity by each frame (0-1)

"},{"title":"Settings.objectDefaultElasticity","link":"objectDefaultElasticity","description":"

How much to bounce when a collision occurs (0-1)

"},{"title":"Settings.objectDefaultFriction","link":"objectDefaultFriction","description":"

How much to slow when touching (0-1)

"},{"title":"Settings.objectDefaultMass","link":"objectDefaultMass","description":"

Default object mass for collison calcuations (how heavy objects are)

"},{"title":"Settings.objectMaxSpeed","link":"objectMaxSpeed","description":"

Clamp max speed to avoid fast objects missing collisions

"},{"title":"Settings.particleEmitRateScale","link":"particleEmitRateScale","description":"

Scales emit rate of particles, useful for low graphics mode (0 disables particle emitters)

"},{"title":"Settings.setCameraPos","link":"setCameraPos","description":"

Set position of camera in world space

"},{"title":"Settings.setCameraScale","link":"setCameraScale","description":"

Set scale of camera in world space

"},{"title":"Settings.setCanvasFixedSize","link":"setCanvasFixedSize","description":"

Set fixed size of the canvas

"},{"title":"Settings.setCanvasMaxSize","link":"setCanvasMaxSize","description":"

Set max size of the canvas

"},{"title":"Settings.setCanvasPixelated","link":"setCanvasPixelated","description":"

Disables anti aliasing for pixel art if true

"},{"title":"Settings.setEnablePhysicsSolver","link":"setEnablePhysicsSolver","description":"

Set if collisions between objects are enabled

"},{"title":"Settings.setFontDefault","link":"setFontDefault","description":"

Set default font used for text rendering

"},{"title":"Settings.setGamepadDirectionEmulateStick","link":"setGamepadDirectionEmulateStick","description":"

Set if the dpad input is also routed to the left analog stick

"},{"title":"Settings.setGamepadsEnable","link":"setGamepadsEnable","description":"

Set if gamepads are enabled

"},{"title":"Settings.setGlEnable","link":"setGlEnable","description":"

Set if webgl rendering is enabled

"},{"title":"Settings.setGlOverlay","link":"setGlOverlay","description":"

Set to not composite the WebGL canvas

"},{"title":"Settings.setGravity","link":"setGravity","description":"

Set how much gravity to apply to objects along the Y axis

"},{"title":"Settings.setInputWASDEmulateDirection","link":"setInputWASDEmulateDirection","description":"

Set if true the WASD keys are also routed to the direction keys

"},{"title":"Settings.setMedalDisplayIconSize","link":"setMedalDisplayIconSize","description":"

Set size of icon in medal display

"},{"title":"Settings.setMedalDisplaySize","link":"setMedalDisplaySize","description":"

Set size of medal display

"},{"title":"Settings.setMedalDisplaySlideTime","link":"setMedalDisplaySlideTime","description":"

Set how quickly to slide on/off medals in seconds

"},{"title":"Settings.setMedalDisplayTime","link":"setMedalDisplayTime","description":"

Set how long to show medals for in seconds

"},{"title":"Settings.setMedalsPreventUnlock","link":"setMedalsPreventUnlock","description":"

Set to stop medals from being unlockable

"},{"title":"Settings.setObjectDefaultAngleDamping","link":"setObjectDefaultAngleDamping","description":"

Set how much to slow angular velocity each frame

"},{"title":"Settings.setObjectDefaultDamping","link":"setObjectDefaultDamping","description":"

Set how much to slow velocity by each frame

"},{"title":"Settings.setObjectDefaultElasticity","link":"setObjectDefaultElasticity","description":"

Set how much to bounce when a collision occur

"},{"title":"Settings.setObjectDefaultFriction","link":"setObjectDefaultFriction","description":"

Set how much to slow when touching

"},{"title":"Settings.setObjectDefaultMass","link":"setObjectDefaultMass","description":"

Set default object mass for collison calcuations

"},{"title":"Settings.setObjectMaxSpeed","link":"setObjectMaxSpeed","description":"

Set max speed to avoid fast objects missing collisions

"},{"title":"Settings.setParticleEmitRateScale","link":"setParticleEmitRateScale","description":"

Set to scales emit rate of particles

"},{"title":"Settings.setSoundDefaultRange","link":"setSoundDefaultRange","description":"

Set default range where sound no longer plays

"},{"title":"Settings.setSoundDefaultTaper","link":"setSoundDefaultTaper","description":"

Set default range percent to start tapering off sound

"},{"title":"Settings.setSoundEnable","link":"setSoundEnable","description":"

Set to disable all audio code

"},{"title":"Settings.setSoundVolume","link":"setSoundVolume","description":"

Set volume scale to apply to all sound, music and speech

"},{"title":"Settings.setTileFixBleedScale","link":"setTileFixBleedScale","description":"

Set to prevent tile bleeding from neighbors in pixels

"},{"title":"Settings.setTileSizeDefault","link":"setTileSizeDefault","description":"

Set default size of tiles in pixels

"},{"title":"Settings.setTouchGamepadAlpha","link":"setTouchGamepadAlpha","description":"

Set transparency of touch gamepad overlay

"},{"title":"Settings.setTouchGamepadAnalog","link":"setTouchGamepadAnalog","description":"

Set if touch gamepad should be analog stick or 8 way dpad

"},{"title":"Settings.setTouchGamepadEnable","link":"setTouchGamepadEnable","description":"

Set if touch gamepad should appear on mobile devices

"},{"title":"Settings.setTouchGamepadSize","link":"setTouchGamepadSize","description":"

Set size of virutal gamepad for touch devices in pixels

"},{"title":"Settings.setVibrateEnable","link":"setVibrateEnable","description":"

Set to allow vibration hardware if it exists

"},{"title":"Settings.soundDefaultRange","link":"soundDefaultRange","description":"

Default range where sound no longer plays

"},{"title":"Settings.soundDefaultTaper","link":"soundDefaultTaper","description":"

Default range percent to start tapering off sound (0-1)

"},{"title":"Settings.soundEnable","link":"soundEnable","description":"

All audio code can be disabled and removed from build

"},{"title":"Settings.soundVolume","link":"soundVolume","description":"

Volume scale to apply to all sound, music and speech

"},{"title":"Settings.tileFixBleedScale","link":"tileFixBleedScale","description":"

Prevent tile bleeding from neighbors in pixels

"},{"title":"Settings.tileSizeDefault","link":"tileSizeDefault","description":"

Default size of tiles in pixels

"},{"title":"Settings.touchGamepadAlpha","link":"touchGamepadAlpha","description":"

Transparency of touch gamepad overlay

"},{"title":"Settings.touchGamepadAnalog","link":"touchGamepadAnalog","description":"

True if touch gamepad should be analog stick or false to use if 8 way dpad

"},{"title":"Settings.touchGamepadEnable","link":"touchGamepadEnable","description":"

True if touch gamepad should appear on mobile devices

\n"},{"title":"Settings.touchGamepadSize","link":"touchGamepadSize","description":"

Size of virutal gamepad for touch devices in pixels

"},{"title":"Settings.vibrateEnable","link":"vibrateEnable","description":"

Allow vibration hardware if it exists

"},{"title":"Sound","link":"Sound","description":"

Create a sound object and cache the zzfx samples for later use

"},{"title":"Sound#play","link":"play","description":"

Play the sound

"},{"title":"Sound#playNote","link":"playNote","description":"

Play the sound as a note with a semitone offset

"},{"title":"Sound#range","link":"range"},{"title":"Sound#taper","link":"taper"},{"title":"TileCollision","link":"TileCollision","description":"

LittleJS Tile Layer System

\n"},{"title":"TileCollision.getTileCollisionData","link":"getTileCollisionData","description":"

Get tile collision data

"},{"title":"TileCollision.initTileCollision","link":"initTileCollision","description":"

Clear and initialize tile collision

"},{"title":"TileCollision.setTileCollisionData","link":"setTileCollisionData","description":"

Set tile collision data

"},{"title":"TileCollision.tileCollision","link":"tileCollision","description":"

The tile collision layer array, use setTileCollisionData and getTileCollisionData to access

"},{"title":"TileCollision.tileCollisionRaycast","link":"tileCollisionRaycast","description":"

Return the center of tile if any that is hit (does not return the exact intersection)

"},{"title":"TileCollision.tileCollisionSize","link":"tileCollisionSize","description":"

Size of the tile collision layer

"},{"title":"TileCollision.tileCollisionTest","link":"tileCollisionTest","description":"

Check if collision with another object should occur

"},{"title":"TileLayer","link":"TileLayer","description":"

Create a tile layer object

"},{"title":"TileLayer#canvas","link":"canvas"},{"title":"TileLayer#context","link":"context"},{"title":"TileLayer#drawAllTileData","link":"drawAllTileData","description":"

Draw all the tiles in this layer

"},{"title":"TileLayer#drawCanvas2D","link":"drawCanvas2D","description":"

Draw directly to the 2D canvas in world space (bipass webgl)

"},{"title":"TileLayer#drawRect","link":"drawRect","description":"

Draw a rectangle directly onto the layer canvas

"},{"title":"TileLayer#drawTile","link":"drawTile","description":"

Draw a tile directly onto the layer canvas

"},{"title":"TileLayer#drawTileData","link":"drawTileData","description":"

Draw the tile at a given position

"},{"title":"TileLayer#getData","link":"getData","description":"

Get data at a given position in the array

"},{"title":"TileLayer#isOverlay","link":"isOverlay"},{"title":"TileLayer#redraw","link":"redraw","description":"

Draw all the tile data to an offscreen canvas

\n"},{"title":"TileLayer#redrawEnd","link":"redrawEnd","description":"

Call to end the redraw process

"},{"title":"TileLayer#redrawStart","link":"redrawStart","description":"

Call to start the redraw process

"},{"title":"TileLayer#scale","link":"scale"},{"title":"TileLayer#setData","link":"setData","description":"

Set data at a given position in the array

"},{"title":"TileLayerData","link":"TileLayerData","description":"

Create a tile layer data object, one for each tile in a TileLayer

"},{"title":"TileLayerData#clear","link":"clear","description":"

Set this tile to clear, it will not be rendered

"},{"title":"TileLayerData#color","link":"color"},{"title":"TileLayerData#direction","link":"direction"},{"title":"TileLayerData#mirror","link":"mirror"},{"title":"TileLayerData#tile","link":"tile"},{"title":"Timer","link":"Timer","description":"

Create a timer object set time passed in

"},{"title":"Timer#active","link":"active","description":"

Returns true if set and has not elapsed

"},{"title":"Timer#elapsed","link":"elapsed","description":"

Returns true if set and elapsed

"},{"title":"Timer#get","link":"get","description":"

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

"},{"title":"Timer#getPercent","link":"getPercent","description":"

Get percentage elapsed based on time it was set to, returns 0 if not set

"},{"title":"Timer#isSet","link":"isSet","description":"

Returns true if set

"},{"title":"Timer#set","link":"set","description":"

Set the timer with seconds passed in

"},{"title":"Timer#toString","link":"toString","description":"

Returns this timer expressed as a string

"},{"title":"Timer#unset","link":"unset","description":"

Unset the timer

"},{"title":"Timer#valueOf","link":"valueOf","description":"

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

"},{"title":"Utilities","link":"Utilities","description":"

LittleJS Utility Classes and Functions

\n"},{"title":"Utilities.PI","link":"PI","description":"

A shortcut to get Math.PI

"},{"title":"Utilities.abs","link":"abs","description":"

Returns absoulte value of value passed in

"},{"title":"Utilities.clamp","link":"clamp","description":"

Clamps the value beween max and min

"},{"title":"Utilities.distanceAngle","link":"distanceAngle","description":"

Returns signed wrapped distance between the two angles passed in

"},{"title":"Utilities.distanceWrap","link":"distanceWrap","description":"

Returns signed wrapped distance between the two values passed in

"},{"title":"Utilities.formatTime","link":"formatTime","description":"

Formats seconds to mm:ss style for display purposes

"},{"title":"Utilities.hsl","link":"hsl","description":"

Create a color object with HSLA values

"},{"title":"Utilities.isOverlapping","link":"isOverlapping","description":"

Returns true if two axis aligned bounding boxes are overlapping

"},{"title":"Utilities.isVector2","link":"isVector2","description":"

Check if object is a valid Vector2

"},{"title":"Utilities.lerp","link":"lerp","description":"

Linearly interpolates between values passed in using percent

"},{"title":"Utilities.lerpAngle","link":"lerpAngle","description":"

Linearly interpolates between the angles passed in with wrappping

"},{"title":"Utilities.lerpWrap","link":"lerpWrap","description":"

Linearly interpolates between values passed in with wrappping

"},{"title":"Utilities.max","link":"max","description":"

Returns highest of two values passed in

"},{"title":"Utilities.min","link":"min","description":"

Returns lowest of two values passed in

"},{"title":"Utilities.mod","link":"mod","description":"

Returns first parm modulo the second param, but adjusted so negative numbers work as expected

"},{"title":"Utilities.nearestPowerOfTwo","link":"nearestPowerOfTwo","description":"

Returns the nearest power of two not less then the value

"},{"title":"Utilities.percent","link":"percent","description":"

Returns what percentage the value is between valueA and valueB

"},{"title":"Utilities.rgb","link":"rgb","description":"

Create a color object with RGBA values

"},{"title":"Utilities.sign","link":"sign","description":"

Returns the sign of value passed in (also returns 1 if 0)

"},{"title":"Utilities.smoothStep","link":"smoothStep","description":"

Applies smoothstep function to the percentage value

"},{"title":"Utilities.vec2","link":"vec2","description":"

Create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar

"},{"title":"Utilities.wave","link":"wave","description":"

Returns an oscillating wave between 0 and amplitude with frequency of 1 Hz by default

"},{"title":"Vector2","link":"Vector2","description":"

Create a 2D vector with the x and y passed in, can also be created with vec2()

"},{"title":"Vector2#add","link":"add","description":"

Returns a copy of this vector plus the vector passed in

"},{"title":"Vector2#angle","link":"angle","description":"

Returns the angle of this vector, up is angle 0

"},{"title":"Vector2#area","link":"area","description":"

Returns the area this vector covers as a rectangle

"},{"title":"Vector2#arrayCheck","link":"arrayCheck","description":"

Returns true if this vector is within the bounds of an array size passed in

"},{"title":"Vector2#clampLength","link":"clampLength","description":"

Returns a new vector clamped to length passed in

"},{"title":"Vector2#copy","link":"copy","description":"

Returns a new vector that is a copy of this

"},{"title":"Vector2#cross","link":"cross","description":"

Returns the cross product of this and the vector passed in

"},{"title":"Vector2#direction","link":"direction","description":"

Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)

"},{"title":"Vector2#distance","link":"distance","description":"

Returns the distance from this vector to vector passed in

"},{"title":"Vector2#distanceSquared","link":"distanceSquared","description":"

Returns the distance squared from this vector to vector passed in

"},{"title":"Vector2#divide","link":"divide","description":"

Returns a copy of this vector divided by the vector passed in

"},{"title":"Vector2#dot","link":"dot","description":"

Returns the dot product of this and the vector passed in

"},{"title":"Vector2#floor","link":"floor","description":"

Returns a copy of this vector with each axis floored

"},{"title":"Vector2#invert","link":"invert","description":"

Returns a copy of this vector that has been inverted

"},{"title":"Vector2#length","link":"length","description":"

Returns the length of this vector

"},{"title":"Vector2#lengthSquared","link":"lengthSquared","description":"

Returns the length of this vector squared

"},{"title":"Vector2#lerp","link":"lerp","description":"

Returns a new vector that is p percent between this and the vector passed in

"},{"title":"Vector2#multiply","link":"multiply","description":"

Returns a copy of this vector times the vector passed in

"},{"title":"Vector2#normalize","link":"normalize","description":"

Returns a new vector in same direction as this one with the length passed in

"},{"title":"Vector2#rotate","link":"rotate","description":"

Returns copy of this vector rotated by the angle passed in

"},{"title":"Vector2#scale","link":"scale","description":"

Returns a copy of this vector scaled by the vector passed in

"},{"title":"Vector2#setAngle","link":"setAngle","description":"

Sets this vector with angle and length passed in

"},{"title":"Vector2#subtract","link":"subtract","description":"

Returns a copy of this vector minus the vector passed in

"},{"title":"Vector2#toString","link":"toString","description":"

Returns this vector expressed as a string

"},{"title":"Vector2#x","link":"x"},{"title":"Vector2#y","link":"y"},{"title":"WebGL","link":"WebGL","description":"

LittleJS WebGL Interface

\n"},{"title":"WebGL.glCanvas","link":"glCanvas","description":"

The WebGL canvas which appears above the main canvas and below the overlay canvas

"},{"title":"WebGL.glCompileShader","link":"glCompileShader","description":"

Compile WebGL shader of the given type, will throw errors if in debug mode

"},{"title":"WebGL.glContext","link":"glContext","description":"

2d context for glCanvas

"},{"title":"WebGL.glCopyToContext","link":"glCopyToContext","description":"

Draw any sprites still in the buffer, copy to main canvas and clear

"},{"title":"WebGL.glCreateProgram","link":"glCreateProgram","description":"

Create WebGL program with given shaders

"},{"title":"WebGL.glCreateTexture","link":"glCreateTexture","description":"

Create WebGL texture from an image and set the texture settings

"},{"title":"WebGL.glDraw","link":"glDraw","description":"

Add a sprite to the gl draw list, used by all gl draw functions

"},{"title":"WebGL.glFlush","link":"glFlush","description":"

Draw all sprites and clear out the buffer, called automatically by the system whenever necessary

"},{"title":"WebGL.glInitPostProcess","link":"glInitPostProcess","description":"

Set up a post processing shader

"},{"title":"WebGL.glSetBlendMode","link":"glSetBlendMode","description":"

Set the WebGl blend mode, normally you should call setBlendMode instead

"},{"title":"WebGL.glSetTexture","link":"glSetTexture","description":"

Set the WebGl texture, not normally necessary unless multiple tile sheets are used

\n"},{"title":"WebGL.glTileTexture","link":"glTileTexture","description":"

Main tile sheet texture automatically loaded by engine

"}]} \ No newline at end of file +{"list":[{"title":"Audio","link":"Audio","description":"

LittleJS Audio System

\n"},{"title":"Audio.audioContext","link":"audioContext","description":"

Audio context used by the engine

"},{"title":"Audio.getNoteFrequency","link":"getNoteFrequency","description":"

Get frequency of a note on a musical scale

"},{"title":"Audio.playAudioFile","link":"playAudioFile","description":"

Play an mp3 or wav audio from a local file or url

"},{"title":"Audio.playSamples","link":"playSamples","description":"

Play cached audio samples with given settings

"},{"title":"Audio.speak","link":"speak","description":"

Speak text with passed in settings

"},{"title":"Audio.speakStop","link":"speakStop","description":"

Stop all queued speech

"},{"title":"Audio.zzfx","link":"zzfx","description":"

Generate and play a ZzFX sound

\n

Create sounds using the ZzFX Sound Designer.

"},{"title":"Audio.zzfxG","link":"zzfxG","description":"

Generate samples for a ZzFX sound

"},{"title":"Audio.zzfxM","link":"zzfxM","description":"

Generate samples for a ZzFM song with given parameters

"},{"title":"Audio.zzfxR","link":"zzfxR","description":"

Sample rate used for all ZzFX sounds

"},{"title":"Color","link":"Color","description":"

Create a color with the rgba components passed in, white by default

"},{"title":"Color#a","link":"a"},{"title":"Color#add","link":"add","description":"

Returns a copy of this color plus the color passed in

"},{"title":"Color#b","link":"b"},{"title":"Color#clamp","link":"clamp","description":"

Returns a copy of this color clamped to the valid range between 0 and 1

"},{"title":"Color#copy","link":"copy","description":"

Returns a new color that is a copy of this

"},{"title":"Color#divide","link":"divide","description":"

Returns a copy of this color divided by the color passed in

"},{"title":"Color#g","link":"g"},{"title":"Color#getHSLA","link":"getHSLA","description":"

Returns this color expressed in hsla format

"},{"title":"Color#lerp","link":"lerp","description":"

Returns a new color that is p percent between this and the color passed in

"},{"title":"Color#multiply","link":"multiply","description":"

Returns a copy of this color times the color passed in

"},{"title":"Color#mutate","link":"mutate","description":"

Returns a new color that has each component randomly adjusted

"},{"title":"Color#r","link":"r"},{"title":"Color#rgbaInt","link":"rgbaInt","description":"

Returns this color expressed as 32 bit RGBA value

"},{"title":"Color#scale","link":"scale","description":"

Returns a copy of this color scaled by the value passed in, alpha can be scaled separately

"},{"title":"Color#setHSLA","link":"setHSLA","description":"

Sets this color given a hue, saturation, lightness, and alpha

"},{"title":"Color#setHex","link":"setHex","description":"

Set this color from a hex code

"},{"title":"Color#subtract","link":"subtract","description":"

Returns a copy of this color minus the color passed in

"},{"title":"Color#toString","link":"toString","description":"

Returns this color expressed as a hex color code

"},{"title":"Debug","link":"Debug","description":"

LittleJS Debug System

\n"},{"title":"Debug.ASSERT","link":"ASSERT","description":"

Asserts if the experssion is false, does not do anything in release builds

"},{"title":"Debug.debug","link":"debug","description":"

True if debug is enabled

"},{"title":"Debug.debugAABB","link":"debugAABB","description":"

Draw a debug axis aligned bounding box in world space

"},{"title":"Debug.debugCircle","link":"debugCircle","description":"

Draw a debug circle in world space

"},{"title":"Debug.debugClear","link":"debugClear","description":"

Clear all debug primitives in the list

"},{"title":"Debug.debugKey","link":"debugKey","description":"

Key code used to toggle debug mode, Esc by default

"},{"title":"Debug.debugLine","link":"debugLine","description":"

Draw a debug line in world space

"},{"title":"Debug.debugPoint","link":"debugPoint","description":"

Draw a debug point in world space

"},{"title":"Debug.debugPointSize","link":"debugPointSize","description":"

Size to render debug points by default

"},{"title":"Debug.debugRect","link":"debugRect","description":"

Draw a debug rectangle in world space

"},{"title":"Debug.debugSaveCanvas","link":"debugSaveCanvas","description":"

Save a canvas to disk

"},{"title":"Debug.debugSaveDataURL","link":"debugSaveDataURL","description":"

Save a data url to disk

"},{"title":"Debug.debugSaveText","link":"debugSaveText","description":"

Save a text file to disk

"},{"title":"Debug.debugText","link":"debugText","description":"

Draw a debug axis aligned bounding box in world space

"},{"title":"Debug.enableAsserts","link":"enableAsserts","description":"

True if asserts are enaled

"},{"title":"Debug.setDebugKey","link":"setDebugKey","description":"

Set key code used to toggle debug mode, Esc by default

"},{"title":"Debug.setShowWatermark","link":"setShowWatermark","description":"

Set if watermark with FPS should be shown

"},{"title":"Debug.showWatermark","link":"showWatermark","description":"

True if watermark with FPS should be shown, false in release builds

"},{"title":"Draw","link":"Draw","description":"

LittleJS Drawing System

\n\n

LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL.\nThere are 3 canvas/contexts available to draw to...\nmainCanvas - 2D background canvas, non WebGL stuff like tile layers are drawn here.\nglCanvas - Used by the accelerated WebGL batch rendering system.\noverlayCanvas - Another 2D canvas that appears on top of the other 2 canvases.

\n

The WebGL rendering system is very fast with some caveats...

\n\n

The LittleJS rendering solution is intentionally simple, feel free to adjust it for your needs!

"},{"title":"Draw.drawCanvas2D","link":"drawCanvas2D","description":"

Draw directly to a 2d canvas context in world space

"},{"title":"Draw.drawLine","link":"drawLine","description":"

Draw colored line between two points

"},{"title":"Draw.drawPoly","link":"drawPoly","description":"

Draw colored polygon using passed in points

"},{"title":"Draw.drawRect","link":"drawRect","description":"

Draw colored rect centered on pos

"},{"title":"Draw.drawText","link":"drawText","description":"

Draw text on overlay canvas in world space\nAutomatically splits new lines into rows

"},{"title":"Draw.drawTextScreen","link":"drawTextScreen","description":"

Draw text on overlay canvas in screen space\nAutomatically splits new lines into rows

"},{"title":"Draw.drawTile","link":"drawTile","description":"

Draw textured tile centered in world space, with color applied if using WebGL

"},{"title":"Draw.isFullscreen","link":"isFullscreen","description":"

Returns true if fullscreen mode is active

"},{"title":"Draw.mainCanvas","link":"mainCanvas","description":"

The primary 2D canvas visible to the user

"},{"title":"Draw.mainCanvasSize","link":"mainCanvasSize","description":"

The size of the main canvas (and other secondary canvases)

"},{"title":"Draw.mainContext","link":"mainContext","description":"

2d context for mainCanvas

"},{"title":"Draw.overlayCanvas","link":"overlayCanvas","description":"

A canvas that appears on top of everything the same size as mainCanvas

"},{"title":"Draw.overlayContext","link":"overlayContext","description":"

2d context for overlayCanvas

"},{"title":"Draw.screenToWorld","link":"screenToWorld","description":"

Convert from screen to world space coordinates

"},{"title":"Draw.setBlendMode","link":"setBlendMode","description":"

Enable normal or additive blend mode

"},{"title":"Draw.tileImage","link":"tileImage","description":"

Tile sheet for batch rendering system

"},{"title":"Draw.toggleFullscreen","link":"toggleFullscreen","description":"

Toggle fullsceen mode

"},{"title":"Draw.worldToScreen","link":"worldToScreen","description":"

Convert from world to screen space coordinates

"},{"title":"Engine","link":"Engine","description":"

LittleJS - The Tiny JavaScript Game Engine That Can!\nMIT License - Copyright 2021 Frank Force

\n

Engine Features

\n"},{"title":"Engine.engineInit","link":"engineInit","description":"

Start up LittleJS engine with your callback functions

"},{"title":"Engine.engineName","link":"engineName","description":"

Name of engine

"},{"title":"Engine.engineObjects","link":"engineObjects","description":"

Array containing all engine objects

"},{"title":"Engine.engineObjectsCallback","link":"engineObjectsCallback","description":"

Triggers a callback for each object within a given area

"},{"title":"Engine.engineObjectsCollide","link":"engineObjectsCollide","description":"

Array containing only objects that are set to collide with other objects this frame (for optimization)

"},{"title":"Engine.engineObjectsDestroy","link":"engineObjectsDestroy","description":"

Destroy and remove all objects

"},{"title":"Engine.engineObjectsUpdate","link":"engineObjectsUpdate","description":"

Update each engine object, remove destroyed objects, and update time

"},{"title":"Engine.engineVersion","link":"engineVersion","description":"

Version of engine

"},{"title":"Engine.frame","link":"frame","description":"

Current update frame, used to calculate time

"},{"title":"Engine.frameRate","link":"frameRate","description":"

Frames per second to update objects

"},{"title":"Engine.paused","link":"paused","description":"

Is the game paused? Causes time and objects to not be updated

"},{"title":"Engine.setPaused","link":"setPaused","description":"

Set if game is paused

"},{"title":"Engine.time","link":"time","description":"

Current engine time since start in seconds, derived from frame

"},{"title":"Engine.timeDelta","link":"timeDelta","description":"

How many seconds each frame lasts, engine uses a fixed time step

"},{"title":"Engine.timeReal","link":"timeReal","description":"

Actual clock time since start in seconds (not affected by pause or frame rate clamping)

"},{"title":"EngineObject","link":"EngineObject","description":"

Create an engine object and adds it to the list of objects

"},{"title":"EngineObject#addChild","link":"addChild","description":"

Attaches a child to this with a given local transform

"},{"title":"EngineObject#additiveColor","link":"additiveColor"},{"title":"EngineObject#angle","link":"angle"},{"title":"EngineObject#angleDamping","link":"angleDamping"},{"title":"EngineObject#angleVelocity","link":"angleVelocity"},{"title":"EngineObject#applyAcceleration","link":"applyAcceleration","description":"

Apply acceleration to this object (adjust velocity, not affected by mass)

"},{"title":"EngineObject#applyForce","link":"applyForce","description":"

Apply force to this object (adjust velocity, affected by mass)

"},{"title":"EngineObject#collideWithObject","link":"collideWithObject","description":"

Called to check if a object collision should be resolved

"},{"title":"EngineObject#collideWithTile","link":"collideWithTile","description":"

Called to check if a tile collision should be resolved

"},{"title":"EngineObject#collideWithTileRaycast","link":"collideWithTileRaycast","description":"

Called to check if a tile raycast hit

"},{"title":"EngineObject#color","link":"color"},{"title":"EngineObject#damping","link":"damping"},{"title":"EngineObject#destroy","link":"destroy","description":"

Destroy this object, destroy it's children, detach it's parent, and mark it for removal

"},{"title":"EngineObject#drawSize","link":"drawSize"},{"title":"EngineObject#elasticity","link":"elasticity"},{"title":"EngineObject#friction","link":"friction"},{"title":"EngineObject#getAliveTime","link":"getAliveTime","description":"

How long since the object was created

"},{"title":"EngineObject#getMirrorSign","link":"getMirrorSign","description":"

Get the direction of the mirror

"},{"title":"EngineObject#gravityScale","link":"gravityScale"},{"title":"EngineObject#mass","link":"mass"},{"title":"EngineObject#pos","link":"pos"},{"title":"EngineObject#removeChild","link":"removeChild","description":"

Removes a child from this one

"},{"title":"EngineObject#render","link":"render","description":"

Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder

"},{"title":"EngineObject#renderOrder","link":"renderOrder"},{"title":"EngineObject#setCollision","link":"setCollision","description":"

Set how this object collides

"},{"title":"EngineObject#size","link":"size"},{"title":"EngineObject#tileIndex","link":"tileIndex"},{"title":"EngineObject#tileSize","link":"tileSize"},{"title":"EngineObject#toString","link":"toString","description":"

Returns string containg info about this object for debugging

"},{"title":"EngineObject#update","link":"update","description":"

Update the object transform and physics, called automatically by engine once each frame

"},{"title":"EngineObject#velocity","link":"velocity"},{"title":"FontImage","link":"FontImage","description":"

Create an image font

"},{"title":"FontImage#drawText","link":"drawText","description":"

Draw text in world space using the image font

"},{"title":"FontImage#drawTextScreen","link":"drawTextScreen","description":"

Draw text in screen space using the image font

"},{"title":"Input","link":"Input","description":"

LittleJS Input System

\n"},{"title":"Input.clearInput","link":"clearInput","description":"

Clears all input

"},{"title":"Input.gamepadIsDown","link":"gamepadIsDown","description":"

Returns true if gamepad button is down

"},{"title":"Input.gamepadStick","link":"gamepadStick","description":"

Returns gamepad stick value

"},{"title":"Input.gamepadWasPressed","link":"gamepadWasPressed","description":"

Returns true if gamepad button was pressed

"},{"title":"Input.gamepadWasReleased","link":"gamepadWasReleased","description":"

Returns true if gamepad button was released

"},{"title":"Input.isTouchDevice","link":"isTouchDevice","description":"

True if a touch device has been detected

"},{"title":"Input.isUsingGamepad","link":"isUsingGamepad","description":"

Returns true if user is using gamepad (has more recently pressed a gamepad button)

"},{"title":"Input.keyIsDown","link":"keyIsDown","description":"

Returns true if device key is down

"},{"title":"Input.keyWasPressed","link":"keyWasPressed","description":"

Returns true if device key was pressed this frame

"},{"title":"Input.keyWasReleased","link":"keyWasReleased","description":"

Returns true if device key was released this frame

"},{"title":"Input.mouseIsDown","link":"mouseIsDown","description":"

Returns true if mouse button is down

"},{"title":"Input.mousePos","link":"mousePos","description":"

Mouse pos in world space

"},{"title":"Input.mousePosScreen","link":"mousePosScreen","description":"

Mouse pos in screen space

"},{"title":"Input.mouseWasPressed","link":"mouseWasPressed","description":"

Returns true if mouse button was pressed

"},{"title":"Input.mouseWasReleased","link":"mouseWasReleased","description":"

Returns true if mouse button was released

"},{"title":"Input.mouseWheel","link":"mouseWheel","description":"

Mouse wheel delta this frame

"},{"title":"Input.preventDefaultInput","link":"preventDefaultInput","description":"

Prevents input continuing to the default browser handling (false by default)

"},{"title":"Input.vibrate","link":"vibrate","description":"

Pulse the vibration hardware if it exists

"},{"title":"Input.vibrateStop","link":"vibrateStop","description":"

Cancel any ongoing vibration

"},{"title":"Medal","link":"Medal","description":"

Create an medal object and adds it to the list of medals

"},{"title":"Medal#render","link":"render","description":"

Render a medal

"},{"title":"Medal#renderIcon","link":"renderIcon","description":"

Render the icon for a medal

"},{"title":"Medal#unlock","link":"unlock","description":"

Unlocks a medal if not already unlocked

"},{"title":"Medals","link":"Medals","description":"

LittleJS Medal System

\n"},{"title":"Medals.medals","link":"medals","description":"

List of all medals

"},{"title":"Medals.medalsInit","link":"medalsInit","description":"

Initialize medals with a save name used for storage

\n"},{"title":"Medals.newgroundsInit","link":"newgroundsInit","description":"

This can used to enable Newgrounds functionality

"},{"title":"Music","link":"Music","description":"

Create a music object and cache the zzfx music samples for later use

"},{"title":"Music#isPlaying","link":"isPlaying","description":"

Check if music is playing

"},{"title":"Music#play","link":"play","description":"

Play the music

"},{"title":"Music#stop","link":"stop","description":"

Stop the music

"},{"title":"Newgrounds","link":"Newgrounds","description":"

Create a newgrounds object

"},{"title":"Newgrounds#call","link":"call","description":"

Send a message to call a component of the Newgrounds API

"},{"title":"Newgrounds#getScores","link":"getScores","description":"

Get scores from a scoreboard

"},{"title":"Newgrounds#logView","link":"logView","description":"

Send message to log a view

"},{"title":"Newgrounds#postScore","link":"postScore","description":"

Send message to post score

"},{"title":"Newgrounds#unlockMedal","link":"unlockMedal","description":"

Send message to unlock a medal by id

"},{"title":"Particle","link":"Particle","description":"

Create a particle with the given settings

"},{"title":"Particle#render","link":"render","description":"

Render the particle, automatically called each frame, sorted by renderOrder

"},{"title":"ParticleEmitter","link":"ParticleEmitter","description":"

Create a particle system with the given settings

"},{"title":"ParticleEmitter#additive","link":"additive"},{"title":"ParticleEmitter#angleDamping","link":"angleDamping"},{"title":"ParticleEmitter#angleSpeed","link":"angleSpeed"},{"title":"ParticleEmitter#collideTiles","link":"collideTiles"},{"title":"ParticleEmitter#colorEndA","link":"colorEndA"},{"title":"ParticleEmitter#colorEndB","link":"colorEndB"},{"title":"ParticleEmitter#colorStartA","link":"colorStartA"},{"title":"ParticleEmitter#colorStartB","link":"colorStartB"},{"title":"ParticleEmitter#damping","link":"damping"},{"title":"ParticleEmitter#emitConeAngle","link":"emitConeAngle"},{"title":"ParticleEmitter#emitParticle","link":"emitParticle","description":"

Spawn one particle

"},{"title":"ParticleEmitter#emitRate","link":"emitRate"},{"title":"ParticleEmitter#emitSize","link":"emitSize"},{"title":"ParticleEmitter#emitTime","link":"emitTime"},{"title":"ParticleEmitter#fadeRate","link":"fadeRate"},{"title":"ParticleEmitter#gravityScale","link":"gravityScale"},{"title":"ParticleEmitter#localSpace","link":"localSpace"},{"title":"ParticleEmitter#particleConeAngle","link":"particleConeAngle"},{"title":"ParticleEmitter#particleTime","link":"particleTime"},{"title":"ParticleEmitter#randomColorLinear","link":"randomColorLinear"},{"title":"ParticleEmitter#randomness","link":"randomness"},{"title":"ParticleEmitter#sizeEnd","link":"sizeEnd"},{"title":"ParticleEmitter#sizeStart","link":"sizeStart"},{"title":"ParticleEmitter#speed","link":"speed"},{"title":"ParticleEmitter#trailScale","link":"trailScale"},{"title":"ParticleEmitter#update","link":"update","description":"

Update the emitter to spawn particles, called automatically by engine once each frame

"},{"title":"Random","link":"Random","description":"

Random global functions

"},{"title":"Random.rand","link":"rand","description":"

Returns a random value between the two values passed in

"},{"title":"Random.randColor","link":"randColor","description":"

Returns a random color between the two passed in colors, combine components if linear

"},{"title":"Random.randInCircle","link":"randInCircle","description":"

Returns a random Vector2 within a circular shape

"},{"title":"Random.randInt","link":"randInt","description":"

Returns a floored random value the two values passed in

"},{"title":"Random.randSign","link":"randSign","description":"

Randomly returns either -1 or 1

"},{"title":"Random.randVector","link":"randVector","description":"

Returns a random Vector2 with the passed in length

"},{"title":"RandomGenerator","link":"RandomGenerator","description":"

Create a random number generator with the seed passed in

"},{"title":"RandomGenerator#float","link":"float","description":"

Returns a seeded random value between the two values passed in

"},{"title":"RandomGenerator#int","link":"int","description":"

Returns a floored seeded random value the two values passed in

"},{"title":"RandomGenerator#seed","link":"seed"},{"title":"RandomGenerator#sign","link":"sign","description":"

Randomly returns either -1 or 1 deterministically

"},{"title":"Settings","link":"Settings","description":"

LittleJS Engine Settings

\n"},{"title":"Settings.cameraPos","link":"cameraPos","description":"

Position of camera in world space

"},{"title":"Settings.cameraScale","link":"cameraScale","description":"

Scale of camera in world space

"},{"title":"Settings.canvasFixedSize","link":"canvasFixedSize","description":"

Fixed size of the canvas, if enabled canvas size never changes

\n"},{"title":"Settings.canvasMaxSize","link":"canvasMaxSize","description":"

The max size of the canvas, centered if window is larger

"},{"title":"Settings.canvasPixelated","link":"canvasPixelated","description":"

Disables filtering for crisper pixel art if true

"},{"title":"Settings.enablePhysicsSolver","link":"enablePhysicsSolver","description":"

Enable physics solver for collisions between objects

"},{"title":"Settings.fontDefault","link":"fontDefault","description":"

Default font used for text rendering

"},{"title":"Settings.gamepadDirectionEmulateStick","link":"gamepadDirectionEmulateStick","description":"

If true, the dpad input is also routed to the left analog stick (for better accessability)

"},{"title":"Settings.gamepadsEnable","link":"gamepadsEnable","description":"

Should gamepads be allowed

"},{"title":"Settings.glEnable","link":"glEnable","description":"

Enable webgl rendering, webgl can be disabled and removed from build (with some features disabled)

"},{"title":"Settings.glOverlay","link":"glOverlay","description":"

Fixes slow rendering in some browsers by not compositing the WebGL canvas

"},{"title":"Settings.gravity","link":"gravity","description":"

How much gravity to apply to objects along the Y axis, negative is down

"},{"title":"Settings.inputWASDEmulateDirection","link":"inputWASDEmulateDirection","description":"

If true the WASD keys are also routed to the direction keys (for better accessability)

"},{"title":"Settings.medalDisplayIconSize","link":"medalDisplayIconSize","description":"

Size of icon in medal display

"},{"title":"Settings.medalDisplaySize","link":"medalDisplaySize","description":"

Size of medal display

"},{"title":"Settings.medalDisplaySlideTime","link":"medalDisplaySlideTime","description":"

How quickly to slide on/off medals in seconds

"},{"title":"Settings.medalDisplayTime","link":"medalDisplayTime","description":"

How long to show medals for in seconds

"},{"title":"Settings.medalsPreventUnlock","link":"medalsPreventUnlock","description":"

Set to stop medals from being unlockable (like if cheats are enabled)

"},{"title":"Settings.objectDefaultAngleDamping","link":"objectDefaultAngleDamping","description":"

How much to slow angular velocity each frame (0-1)

"},{"title":"Settings.objectDefaultDamping","link":"objectDefaultDamping","description":"

How much to slow velocity by each frame (0-1)

"},{"title":"Settings.objectDefaultElasticity","link":"objectDefaultElasticity","description":"

How much to bounce when a collision occurs (0-1)

"},{"title":"Settings.objectDefaultFriction","link":"objectDefaultFriction","description":"

How much to slow when touching (0-1)

"},{"title":"Settings.objectDefaultMass","link":"objectDefaultMass","description":"

Default object mass for collison calcuations (how heavy objects are)

"},{"title":"Settings.objectMaxSpeed","link":"objectMaxSpeed","description":"

Clamp max speed to avoid fast objects missing collisions

"},{"title":"Settings.particleEmitRateScale","link":"particleEmitRateScale","description":"

Scales emit rate of particles, useful for low graphics mode (0 disables particle emitters)

"},{"title":"Settings.setCameraPos","link":"setCameraPos","description":"

Set position of camera in world space

"},{"title":"Settings.setCameraScale","link":"setCameraScale","description":"

Set scale of camera in world space

"},{"title":"Settings.setCanvasFixedSize","link":"setCanvasFixedSize","description":"

Set fixed size of the canvas

"},{"title":"Settings.setCanvasMaxSize","link":"setCanvasMaxSize","description":"

Set max size of the canvas

"},{"title":"Settings.setCanvasPixelated","link":"setCanvasPixelated","description":"

Disables anti aliasing for pixel art if true

"},{"title":"Settings.setEnablePhysicsSolver","link":"setEnablePhysicsSolver","description":"

Set if collisions between objects are enabled

"},{"title":"Settings.setFontDefault","link":"setFontDefault","description":"

Set default font used for text rendering

"},{"title":"Settings.setGamepadDirectionEmulateStick","link":"setGamepadDirectionEmulateStick","description":"

Set if the dpad input is also routed to the left analog stick

"},{"title":"Settings.setGamepadsEnable","link":"setGamepadsEnable","description":"

Set if gamepads are enabled

"},{"title":"Settings.setGlEnable","link":"setGlEnable","description":"

Set if webgl rendering is enabled

"},{"title":"Settings.setGlOverlay","link":"setGlOverlay","description":"

Set to not composite the WebGL canvas

"},{"title":"Settings.setGravity","link":"setGravity","description":"

Set how much gravity to apply to objects along the Y axis

"},{"title":"Settings.setInputWASDEmulateDirection","link":"setInputWASDEmulateDirection","description":"

Set if true the WASD keys are also routed to the direction keys

"},{"title":"Settings.setMedalDisplayIconSize","link":"setMedalDisplayIconSize","description":"

Set size of icon in medal display

"},{"title":"Settings.setMedalDisplaySize","link":"setMedalDisplaySize","description":"

Set size of medal display

"},{"title":"Settings.setMedalDisplaySlideTime","link":"setMedalDisplaySlideTime","description":"

Set how quickly to slide on/off medals in seconds

"},{"title":"Settings.setMedalDisplayTime","link":"setMedalDisplayTime","description":"

Set how long to show medals for in seconds

"},{"title":"Settings.setMedalsPreventUnlock","link":"setMedalsPreventUnlock","description":"

Set to stop medals from being unlockable

"},{"title":"Settings.setObjectDefaultAngleDamping","link":"setObjectDefaultAngleDamping","description":"

Set how much to slow angular velocity each frame

"},{"title":"Settings.setObjectDefaultDamping","link":"setObjectDefaultDamping","description":"

Set how much to slow velocity by each frame

"},{"title":"Settings.setObjectDefaultElasticity","link":"setObjectDefaultElasticity","description":"

Set how much to bounce when a collision occur

"},{"title":"Settings.setObjectDefaultFriction","link":"setObjectDefaultFriction","description":"

Set how much to slow when touching

"},{"title":"Settings.setObjectDefaultMass","link":"setObjectDefaultMass","description":"

Set default object mass for collison calcuations

"},{"title":"Settings.setObjectMaxSpeed","link":"setObjectMaxSpeed","description":"

Set max speed to avoid fast objects missing collisions

"},{"title":"Settings.setParticleEmitRateScale","link":"setParticleEmitRateScale","description":"

Set to scales emit rate of particles

"},{"title":"Settings.setSoundDefaultRange","link":"setSoundDefaultRange","description":"

Set default range where sound no longer plays

"},{"title":"Settings.setSoundDefaultTaper","link":"setSoundDefaultTaper","description":"

Set default range percent to start tapering off sound

"},{"title":"Settings.setSoundEnable","link":"setSoundEnable","description":"

Set to disable all audio code

"},{"title":"Settings.setSoundVolume","link":"setSoundVolume","description":"

Set volume scale to apply to all sound, music and speech

"},{"title":"Settings.setTileFixBleedScale","link":"setTileFixBleedScale","description":"

Set to prevent tile bleeding from neighbors in pixels

"},{"title":"Settings.setTileSizeDefault","link":"setTileSizeDefault","description":"

Set default size of tiles in pixels

"},{"title":"Settings.setTouchGamepadAlpha","link":"setTouchGamepadAlpha","description":"

Set transparency of touch gamepad overlay

"},{"title":"Settings.setTouchGamepadAnalog","link":"setTouchGamepadAnalog","description":"

Set if touch gamepad should be analog stick or 8 way dpad

"},{"title":"Settings.setTouchGamepadEnable","link":"setTouchGamepadEnable","description":"

Set if touch gamepad should appear on mobile devices

"},{"title":"Settings.setTouchGamepadSize","link":"setTouchGamepadSize","description":"

Set size of virutal gamepad for touch devices in pixels

"},{"title":"Settings.setVibrateEnable","link":"setVibrateEnable","description":"

Set to allow vibration hardware if it exists

"},{"title":"Settings.soundDefaultRange","link":"soundDefaultRange","description":"

Default range where sound no longer plays

"},{"title":"Settings.soundDefaultTaper","link":"soundDefaultTaper","description":"

Default range percent to start tapering off sound (0-1)

"},{"title":"Settings.soundEnable","link":"soundEnable","description":"

All audio code can be disabled and removed from build

"},{"title":"Settings.soundVolume","link":"soundVolume","description":"

Volume scale to apply to all sound, music and speech

"},{"title":"Settings.tileFixBleedScale","link":"tileFixBleedScale","description":"

Prevent tile bleeding from neighbors in pixels

"},{"title":"Settings.tileSizeDefault","link":"tileSizeDefault","description":"

Default size of tiles in pixels

"},{"title":"Settings.touchGamepadAlpha","link":"touchGamepadAlpha","description":"

Transparency of touch gamepad overlay

"},{"title":"Settings.touchGamepadAnalog","link":"touchGamepadAnalog","description":"

True if touch gamepad should be analog stick or false to use if 8 way dpad

"},{"title":"Settings.touchGamepadEnable","link":"touchGamepadEnable","description":"

True if touch gamepad should appear on mobile devices

\n"},{"title":"Settings.touchGamepadSize","link":"touchGamepadSize","description":"

Size of virutal gamepad for touch devices in pixels

"},{"title":"Settings.vibrateEnable","link":"vibrateEnable","description":"

Allow vibration hardware if it exists

"},{"title":"Sound","link":"Sound","description":"

Create a sound object and cache the zzfx samples for later use

"},{"title":"Sound#play","link":"play","description":"

Play the sound

"},{"title":"Sound#playNote","link":"playNote","description":"

Play the sound as a note with a semitone offset

"},{"title":"Sound#randomness","link":"randomness"},{"title":"Sound#range","link":"range"},{"title":"Sound#taper","link":"taper"},{"title":"SoundWave","link":"SoundWave","description":"

Create a sound object and cache the wave file for later use

"},{"title":"TileCollision","link":"TileCollision","description":"

LittleJS Tile Layer System

\n"},{"title":"TileCollision.getTileCollisionData","link":"getTileCollisionData","description":"

Get tile collision data

"},{"title":"TileCollision.initTileCollision","link":"initTileCollision","description":"

Clear and initialize tile collision

"},{"title":"TileCollision.setTileCollisionData","link":"setTileCollisionData","description":"

Set tile collision data

"},{"title":"TileCollision.tileCollision","link":"tileCollision","description":"

The tile collision layer array, use setTileCollisionData and getTileCollisionData to access

"},{"title":"TileCollision.tileCollisionRaycast","link":"tileCollisionRaycast","description":"

Return the center of tile if any that is hit (does not return the exact intersection)

"},{"title":"TileCollision.tileCollisionSize","link":"tileCollisionSize","description":"

Size of the tile collision layer

"},{"title":"TileCollision.tileCollisionTest","link":"tileCollisionTest","description":"

Check if collision with another object should occur

"},{"title":"TileLayer","link":"TileLayer","description":"

Create a tile layer object

"},{"title":"TileLayer#canvas","link":"canvas"},{"title":"TileLayer#context","link":"context"},{"title":"TileLayer#drawAllTileData","link":"drawAllTileData","description":"

Draw all the tiles in this layer

"},{"title":"TileLayer#drawCanvas2D","link":"drawCanvas2D","description":"

Draw directly to the 2D canvas in world space (bipass webgl)

"},{"title":"TileLayer#drawRect","link":"drawRect","description":"

Draw a rectangle directly onto the layer canvas

"},{"title":"TileLayer#drawTile","link":"drawTile","description":"

Draw a tile directly onto the layer canvas

"},{"title":"TileLayer#drawTileData","link":"drawTileData","description":"

Draw the tile at a given position

"},{"title":"TileLayer#getData","link":"getData","description":"

Get data at a given position in the array

"},{"title":"TileLayer#isOverlay","link":"isOverlay"},{"title":"TileLayer#redraw","link":"redraw","description":"

Draw all the tile data to an offscreen canvas

\n"},{"title":"TileLayer#redrawEnd","link":"redrawEnd","description":"

Call to end the redraw process

"},{"title":"TileLayer#redrawStart","link":"redrawStart","description":"

Call to start the redraw process

"},{"title":"TileLayer#scale","link":"scale"},{"title":"TileLayer#setData","link":"setData","description":"

Set data at a given position in the array

"},{"title":"TileLayerData","link":"TileLayerData","description":"

Create a tile layer data object, one for each tile in a TileLayer

"},{"title":"TileLayerData#clear","link":"clear","description":"

Set this tile to clear, it will not be rendered

"},{"title":"TileLayerData#color","link":"color"},{"title":"TileLayerData#direction","link":"direction"},{"title":"TileLayerData#mirror","link":"mirror"},{"title":"TileLayerData#tile","link":"tile"},{"title":"Timer","link":"Timer","description":"

Create a timer object set time passed in

"},{"title":"Timer#active","link":"active","description":"

Returns true if set and has not elapsed

"},{"title":"Timer#elapsed","link":"elapsed","description":"

Returns true if set and elapsed

"},{"title":"Timer#get","link":"get","description":"

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

"},{"title":"Timer#getPercent","link":"getPercent","description":"

Get percentage elapsed based on time it was set to, returns 0 if not set

"},{"title":"Timer#isSet","link":"isSet","description":"

Returns true if set

"},{"title":"Timer#set","link":"set","description":"

Set the timer with seconds passed in

"},{"title":"Timer#toString","link":"toString","description":"

Returns this timer expressed as a string

"},{"title":"Timer#unset","link":"unset","description":"

Unset the timer

"},{"title":"Timer#valueOf","link":"valueOf","description":"

Get how long since elapsed, returns 0 if not set (returns negative if currently active)

"},{"title":"Utilities","link":"Utilities","description":"

LittleJS Utility Classes and Functions

\n"},{"title":"Utilities.PI","link":"PI","description":"

A shortcut to get Math.PI

"},{"title":"Utilities.abs","link":"abs","description":"

Returns absoulte value of value passed in

"},{"title":"Utilities.clamp","link":"clamp","description":"

Clamps the value beween max and min

"},{"title":"Utilities.distanceAngle","link":"distanceAngle","description":"

Returns signed wrapped distance between the two angles passed in

"},{"title":"Utilities.distanceWrap","link":"distanceWrap","description":"

Returns signed wrapped distance between the two values passed in

"},{"title":"Utilities.formatTime","link":"formatTime","description":"

Formats seconds to mm:ss style for display purposes

"},{"title":"Utilities.hsl","link":"hsl","description":"

Create a color object with HSLA values

"},{"title":"Utilities.isOverlapping","link":"isOverlapping","description":"

Returns true if two axis aligned bounding boxes are overlapping

"},{"title":"Utilities.isVector2","link":"isVector2","description":"

Check if object is a valid Vector2

"},{"title":"Utilities.lerp","link":"lerp","description":"

Linearly interpolates between values passed in using percent

"},{"title":"Utilities.lerpAngle","link":"lerpAngle","description":"

Linearly interpolates between the angles passed in with wrappping

"},{"title":"Utilities.lerpWrap","link":"lerpWrap","description":"

Linearly interpolates between values passed in with wrappping

"},{"title":"Utilities.max","link":"max","description":"

Returns highest of two values passed in

"},{"title":"Utilities.min","link":"min","description":"

Returns lowest of two values passed in

"},{"title":"Utilities.mod","link":"mod","description":"

Returns first parm modulo the second param, but adjusted so negative numbers work as expected

"},{"title":"Utilities.nearestPowerOfTwo","link":"nearestPowerOfTwo","description":"

Returns the nearest power of two not less then the value

"},{"title":"Utilities.percent","link":"percent","description":"

Returns what percentage the value is between valueA and valueB

"},{"title":"Utilities.rgb","link":"rgb","description":"

Create a color object with RGBA values

"},{"title":"Utilities.sign","link":"sign","description":"

Returns the sign of value passed in (also returns 1 if 0)

"},{"title":"Utilities.smoothStep","link":"smoothStep","description":"

Applies smoothstep function to the percentage value

"},{"title":"Utilities.vec2","link":"vec2","description":"

Create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar

"},{"title":"Utilities.wave","link":"wave","description":"

Returns an oscillating wave between 0 and amplitude with frequency of 1 Hz by default

"},{"title":"Vector2","link":"Vector2","description":"

Create a 2D vector with the x and y passed in, can also be created with vec2()

"},{"title":"Vector2#add","link":"add","description":"

Returns a copy of this vector plus the vector passed in

"},{"title":"Vector2#angle","link":"angle","description":"

Returns the angle of this vector, up is angle 0

"},{"title":"Vector2#area","link":"area","description":"

Returns the area this vector covers as a rectangle

"},{"title":"Vector2#arrayCheck","link":"arrayCheck","description":"

Returns true if this vector is within the bounds of an array size passed in

"},{"title":"Vector2#clampLength","link":"clampLength","description":"

Returns a new vector clamped to length passed in

"},{"title":"Vector2#copy","link":"copy","description":"

Returns a new vector that is a copy of this

"},{"title":"Vector2#cross","link":"cross","description":"

Returns the cross product of this and the vector passed in

"},{"title":"Vector2#direction","link":"direction","description":"

Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)

"},{"title":"Vector2#distance","link":"distance","description":"

Returns the distance from this vector to vector passed in

"},{"title":"Vector2#distanceSquared","link":"distanceSquared","description":"

Returns the distance squared from this vector to vector passed in

"},{"title":"Vector2#divide","link":"divide","description":"

Returns a copy of this vector divided by the vector passed in

"},{"title":"Vector2#dot","link":"dot","description":"

Returns the dot product of this and the vector passed in

"},{"title":"Vector2#floor","link":"floor","description":"

Returns a copy of this vector with each axis floored

"},{"title":"Vector2#invert","link":"invert","description":"

Returns a copy of this vector that has been inverted

"},{"title":"Vector2#length","link":"length","description":"

Returns the length of this vector

"},{"title":"Vector2#lengthSquared","link":"lengthSquared","description":"

Returns the length of this vector squared

"},{"title":"Vector2#lerp","link":"lerp","description":"

Returns a new vector that is p percent between this and the vector passed in

"},{"title":"Vector2#multiply","link":"multiply","description":"

Returns a copy of this vector times the vector passed in

"},{"title":"Vector2#normalize","link":"normalize","description":"

Returns a new vector in same direction as this one with the length passed in

"},{"title":"Vector2#rotate","link":"rotate","description":"

Returns copy of this vector rotated by the angle passed in

"},{"title":"Vector2#scale","link":"scale","description":"

Returns a copy of this vector scaled by the vector passed in

"},{"title":"Vector2#setAngle","link":"setAngle","description":"

Sets this vector with angle and length passed in

"},{"title":"Vector2#subtract","link":"subtract","description":"

Returns a copy of this vector minus the vector passed in

"},{"title":"Vector2#toString","link":"toString","description":"

Returns this vector expressed as a string

"},{"title":"Vector2#x","link":"x"},{"title":"Vector2#y","link":"y"},{"title":"WebGL","link":"WebGL","description":"

LittleJS WebGL Interface

\n"},{"title":"WebGL.glCanvas","link":"glCanvas","description":"

The WebGL canvas which appears above the main canvas and below the overlay canvas

"},{"title":"WebGL.glCompileShader","link":"glCompileShader","description":"

Compile WebGL shader of the given type, will throw errors if in debug mode

"},{"title":"WebGL.glContext","link":"glContext","description":"

2d context for glCanvas

"},{"title":"WebGL.glCopyToContext","link":"glCopyToContext","description":"

Draw any sprites still in the buffer, copy to main canvas and clear

"},{"title":"WebGL.glCreateProgram","link":"glCreateProgram","description":"

Create WebGL program with given shaders

"},{"title":"WebGL.glCreateTexture","link":"glCreateTexture","description":"

Create WebGL texture from an image and set the texture settings

"},{"title":"WebGL.glDraw","link":"glDraw","description":"

Add a sprite to the gl draw list, used by all gl draw functions

"},{"title":"WebGL.glDrawPoints","link":"glDrawPoints","description":"

Add a convex polygon to the gl draw list

"},{"title":"WebGL.glFlush","link":"glFlush","description":"

Draw all sprites and clear out the buffer, called automatically by the system whenever necessary

"},{"title":"WebGL.glInitPostProcess","link":"glInitPostProcess","description":"

Set up a post processing shader

"},{"title":"WebGL.glSetBlendMode","link":"glSetBlendMode","description":"

Set the WebGl blend mode, normally you should call setBlendMode instead

"},{"title":"WebGL.glSetTexture","link":"glSetTexture","description":"

Set the WebGl texture, not normally necessary unless multiple tile sheets are used

\n"},{"title":"WebGL.glTileTexture","link":"glTileTexture","description":"

Main tile sheet texture automatically loaded by engine

"}]} \ No newline at end of file diff --git a/docs/engine.js.html b/docs/engine.js.html index 58582883..0f96f9d6 100644 --- a/docs/engine.js.html +++ b/docs/engine.js.html @@ -1,6 +1,6 @@ Source: engine.js
On this page

engine.js

/** 
+    
On this page

engine.js

/** 
  * LittleJS - The Tiny JavaScript Game Engine That Can!
  * MIT License - Copyright 2021 Frank Force
  * 
@@ -32,7 +32,7 @@
  *  @type {String}
  *  @default
  *  @memberof Engine */
-const engineVersion = '1.6.93';
+const engineVersion = '1.7.12';
 
 /** Frames per second to update objects
  *  @type {Number}
@@ -130,7 +130,7 @@
     };
 
     // frame time tracking
-    let frameTimeLastMS = 0, frameTimeBufferMS = 0, averageFPS;
+    let frameTimeLastMS = 0, frameTimeBufferMS = 0, averageFPS = 0;
 
     // main update loop
     function engineUpdate(frameTimeMS=0)
@@ -321,4 +321,4 @@
         for (const o of objects)
             pos.distanceSquared(o.pos) < sizeSquared && callbackFunction(o);
     }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineAudio.js.html b/docs/engineAudio.js.html index 9295b277..c5555f98 100644 --- a/docs/engineAudio.js.html +++ b/docs/engineAudio.js.html @@ -1,13 +1,13 @@ Source: engineAudio.js
On this page

engineAudio.js

/** 
+    
On this page

engineAudio.js

/** 
  * LittleJS Audio System
- * - <a href=https://killedbyapixel.github.io/ZzFX/>ZzFX Sound Effects</a> - Sound Effect Generator
- * - <a href=https://keithclark.github.io/ZzFXM/>ZzFXM Music</a> - Music System
+ * - <a href=https://killedbyapixel.github.io/ZzFX/>ZzFX Sound Effects</a> - ZzFX Sound Effect Generator
+ * - <a href=https://keithclark.github.io/ZzFXM/>ZzFXM Music</a> - ZzFXM Music System
  * - Caches sounds and music for fast playback
  * - Can attenuate and apply stereo panning to sounds
  * - Ability to play mp3, ogg, and wave files
- * - Speech synthesis wrapper functions
+ * - Speech synthesis functions
  * @namespace Audio
  */
 
@@ -41,12 +41,15 @@
         /** @property {Number} - At what percentage of range should it start tapering off */
         this.taper = taper;
 
-        // get randomness from sound parameters
-        this.randomness = zzfxSound[1] || 0;
-        zzfxSound[1] = 0;
+        /** @property {Number} - How much to randomize frequency each time sound plays */
+        this.randomness = 0;
 
-        // generate sound now for fast playback
-        this.cachedSamples = zzfxG(...zzfxSound);
+        if (zzfxSound)
+        {
+            // generate zzfx sound now for fast playback
+            this.randomness = zzfxSound[1] || (zzfxSound[1] = 0); 
+            this.cachedSamples = zzfxSound && zzfxG(...zzfxSound);
+        }
     }
 
     /** Play the sound
@@ -58,7 +61,7 @@
      */
     play(pos, volume=1, pitch=1, randomnessScale=1)
     {
-        if (!soundEnable) return;
+        if (!soundEnable || !this.cachedSamples) return;
 
         let pan;
         if (pos)
@@ -91,12 +94,36 @@
      *  @return {AudioBufferSourceNode} - The audio, can be used to stop sound later
      */
     playNote(semitoneOffset, pos, volume)
+    { return this.play(pos, volume, 2**(semitoneOffset/12), 0); }
+}
+
+/** 
+ * Sound Wave Object - Stores a wave sound for later use and can be played positionally
+ */
+class SoundWave extends Sound
+{
+    /** Create a sound object and cache the wave file for later use
+     *  @param {String} waveFilename - Filename of wave file to load
+     *  @param {Number} [randomness=.05] - How much to randomize frequency each time sound plays
+     *  @param {Number} [range=soundDefaultRange] - World space max range of sound, will not play if camera is farther away
+     *  @param {Number} [taper=soundDefaultTaper] - At what percentage of range should it start tapering off
+     */
+    constructor(waveFilename, randomness=.05, range, taper)
     {
+        super(0, range, taper);
+        this.randomness = randomness;
+
         if (!soundEnable) return;
+        if (!soundWaveDecoderContext)
+            soundDecoderContext = new AudioContext;
 
-        return this.play(pos, volume, 2**(semitoneOffset/12), 0);
+        fetch(waveFilename)
+        .then(response => response.arrayBuffer())
+        .then(arrayBuffer => soundWaveDecoderContext.decodeAudioData(arrayBuffer))
+        .then(audioBuffer => this.cachedSamples = audioBuffer.getChannelData(0));
     }
 }
+let soundDecoderContext; // audio context used only to decode audio files
 
 /**
  * Music Object - Stores a zzfx music track for later use
@@ -239,16 +266,17 @@
 {
     if (!soundEnable) return;
 
-    // create audio context
+    // create audio context if needed
     if (!audioContext)
         audioContext = new AudioContext;
 
-    // fix stalled audio
-    audioContext.resume();
-
     // prevent sounds from building up if they can't be played
     if (audioContext.state != 'running')
+    {
+        // fix stalled audio
+        audioContext.resume();
         return;
+    }
 
     // create buffer and source
     const buffer = audioContext.createBuffer(sampleChannels.length, sampleChannels[0].length, zzfxR), 
@@ -453,7 +481,7 @@
 
         // stop if end, different instrument or new note
         stop = i == patternChannel.length + isSequenceEnd - 1 && isSequenceEnd ||
-            instrument != (patternChannel[0] || 0) || note;
+            instrument != (patternChannel[0] || 0) || note | 0;
 
         // fill buffer with samples for previous beat, most cpu intensive part
         for (j = 0; j < beatLength && notFirstBeat;
@@ -497,4 +525,4 @@
   }
 
   return [leftChannelBuffer, rightChannelBuffer];
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineDebug.js.html b/docs/engineDebug.js.html index 4a342c0c..abcd3a1e 100644 --- a/docs/engineDebug.js.html +++ b/docs/engineDebug.js.html @@ -1,12 +1,12 @@ Source: engineDebug.js
On this page

engineDebug.js

/** 
+    
On this page

engineDebug.js

/** 
  * LittleJS Debug System
- * - Press ~ to show debug overlay with mouse pick
+ * - Press Esc to show debug overlay with mouse pick
  * - Number keys toggle debug functions
  * - +/- apply time scale
  * - Debug primitive rendering
- * - Save a 2d canvas as an image
+ * - Save a 2d canvas as a png image
  * @namespace Debug
  */
 
@@ -140,11 +140,27 @@
 /** Save a canvas to disk 
  *  @param {HTMLCanvasElement} canvas
  *  @param {String}            [filename]
+ *  @param {String}            [type='image/png']
  *  @memberof Debug */
-function debugSaveCanvas(canvas, filename = engineName + '.png')
+function debugSaveCanvas(canvas, filename=engineName, type='image/png')
+{ debugSaveDataURL(canvas.toDataURL(type), filename); }
+
+/** Save a text file to disk 
+ *  @param {String}     text
+ *  @param {String}     [filename]
+ *  @param {String}     [type='text/plain']
+ *  @memberof Debug */
+function debugSaveText(text, filename=engineName, type='text/plain')
+{ debugSaveDataURL(URL.createObjectURL(new Blob([text], {'type':type})), filename); }
+
+/** Save a data url to disk 
+ *  @param {String}     dataURL
+ *  @param {String}     filename
+ *  @memberof Debug */
+function debugSaveDataURL(dataURL, filename)
 {
-    downloadLink.download = 'screenshot.png';
-    downloadLink.href = canvas.toDataURL('image/png').replace('image/png','image/octet-stream');
+    downloadLink.download = filename;
+    downloadLink.href = dataURL;
     downloadLink.click();
 }
 
@@ -387,4 +403,4 @@
     
         overlayContext.restore();
     }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineDraw.js.html b/docs/engineDraw.js.html index 27a745ef..6d762643 100644 --- a/docs/engineDraw.js.html +++ b/docs/engineDraw.js.html @@ -1,10 +1,11 @@ Source: engineDraw.js
On this page

engineDraw.js

/** 
+    
On this page

engineDraw.js

/** 
  * LittleJS Drawing System
- * - Hybrid with both Canvas2D and WebGL available
+ * - Hybrid system with both Canvas2D and WebGL available
  * - Super fast tile sheet rendering with WebGL
  * - Can apply rotation, mirror, color and additive color
+ * - Font rendering system with built in engine font
  * - Many useful utility functions
  * 
  * LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL.
@@ -14,7 +15,6 @@
  * overlayCanvas - Another 2D canvas that appears on top of the other 2 canvases.
  * 
  * The WebGL rendering system is very fast with some caveats...
- * - The default setup supports only 1 tile sheet, to support more call glCreateTexture and glSetTexture
  * - Switching blend modes (additive) or textures causes another draw call which is expensive in excess
  * - Group additive rendering together using renderOrder to mitigate this issue
  * 
@@ -58,33 +58,29 @@
 let tileImageSize, tileImageFixBleed, drawCount;
 
 /** Convert from screen to world space coordinates
- *  - if calling outside of render, you may need to manually set mainCanvasSize
  *  @param {Vector2} screenPos
  *  @return {Vector2}
  *  @memberof Draw */
 function screenToWorld(screenPos)
 {
-    ASSERT(mainCanvasSize.x && mainCanvasSize.y, 'mainCanvasSize is invalid');
-    return screenPos
-        .add(vec2(.5))
-        .subtract(mainCanvasSize.scale(.5))
-        .multiply(vec2(1/cameraScale,-1/cameraScale))
-        .add(cameraPos);
+    return new Vector2
+    (
+        (screenPos.x - mainCanvasSize.x/2 + .5) /  cameraScale + cameraPos.x,
+        (screenPos.y - mainCanvasSize.y/2 + .5) / -cameraScale + cameraPos.y
+    );
 }
 
 /** Convert from world to screen space coordinates
- *  - if calling outside of render, you may need to manually set mainCanvasSize
  *  @param {Vector2} worldPos
  *  @return {Vector2}
  *  @memberof Draw */
 function worldToScreen(worldPos)
 {
-    ASSERT(mainCanvasSize.x && mainCanvasSize.y, 'mainCanvasSize is invalid');
-    return worldPos
-        .subtract(cameraPos)
-        .multiply(vec2(cameraScale,-cameraScale))
-        .add(mainCanvasSize.scale(.5))
-        .subtract(vec2(.5));
+    return new Vector2
+    (
+        (worldPos.x - cameraPos.x) *  cameraScale + mainCanvasSize.x/2 - .5,
+        (worldPos.y - cameraPos.y) * -cameraScale + mainCanvasSize.y/2 - .5
+    );
 }
 
 /** Draw textured tile centered in world space, with color applied if using WebGL
@@ -97,13 +93,21 @@
  *  @param {Boolean} [mirror=0]                     - If true image is flipped along the Y axis
  *  @param {Color}   [additiveColor=Color(0,0,0,0)] - Additive color to be applied
  *  @param {Boolean} [useWebGL=glEnable]            - Use accelerated WebGL rendering
+ *  @param {Boolean} [screenSpace=0]                - If true the pos and size are in screen space
  *  @memberof Draw */
 function drawTile(pos, size=vec2(1), tileIndex=-1, tileSize=tileSizeDefault, color=new Color,
-    angle=0, mirror, additiveColor=new Color(0,0,0,0), useWebGL=glEnable)
+    angle=0, mirror, additiveColor=new Color(0,0,0,0), useWebGL=glEnable, screenSpace)
 {
     showWatermark && ++drawCount;
+    
     if (glEnable && useWebGL)
     {
+        if (screenSpace)
+        {
+            // convert to world space
+            pos = screenToWorld(pos);
+            size = size.scale(1/cameraScale);
+        }
         if (tileIndex < 0 || !tileImage.width)
         {
             // if negative tile index or image not found, force untextured
@@ -145,7 +149,7 @@
                 context.globalAlpha = color.a; // only alpha is supported
                 context.drawImage(tileImage, sX, sY, sWidth, sHeight, -.5, -.5, 1, 1);
             }
-        });
+        }, undefined, screenSpace);
     }
 }
 
@@ -155,38 +159,30 @@
  *  @param {Color}   [color=Color()]
  *  @param {Number}  [angle=0]
  *  @param {Boolean} [useWebGL=glEnable]
+ *  @param {Boolean} [screenSpace=0]
  *  @memberof Draw */
-function drawRect(pos, size, color, angle, useWebGL)
-{
-    drawTile(pos, size, -1, tileSizeDefault, color, angle, 0, 0, useWebGL);
-}
+function drawRect(pos, size, color, angle, useWebGL, screenSpace)
+{ drawTile(pos, size, -1, tileSizeDefault, color, angle, 0, undefined, useWebGL, screenSpace); }
 
-/** Draw textured tile centered on pos in screen space
- *  @param {Vector2} pos                        - Center of the tile
- *  @param {Vector2} [size=Vector2(1,1)]    - Size of the tile
- *  @param {Number}  [tileIndex=-1]             - Tile index to use, negative is untextured
- *  @param {Vector2} [tileSize=tileSizeDefault] - Tile size in source pixels
+/** Draw colored polygon using passed in points
+ *  @param {Array}   points - Array of Vector2 points
  *  @param {Color}   [color=Color()]
- *  @param {Number}  [angle=0]
- *  @param {Boolean} [mirror=0]
- *  @param {Color}   [additiveColor=Color(0,0,0,0)]
  *  @param {Boolean} [useWebGL=glEnable]
+ *  @param {Boolean} [screenSpace=0]
  *  @memberof Draw */
-function drawTileScreenSpace(pos, size=vec2(1), tileIndex, tileSize, color, angle, mirror, additiveColor, useWebGL)
+function drawPoly(points, color=new Color, useWebGL=glEnable, screenSpace)
 {
-    drawTile(screenToWorld(pos), size.scale(1/cameraScale), tileIndex, tileSize, color, angle, mirror, additiveColor, useWebGL);
-}
-
-/** Draw colored rectangle in screen space
- *  @param {Vector2} pos
- *  @param {Vector2} [size=Vector2(1,1)]
- *  @param {Color}   [color=Color()]
- *  @param {Number}  [angle=0]
- *  @param {Boolean} [useWebGL=glEnable]
- *  @memberof Draw */
-function drawRectScreenSpace(pos, size, color, angle, useWebGL)
-{
-    drawTileScreenSpace(pos, size, -1, tileSizeDefault, color, angle, 0, 0, useWebGL);
+    if (useWebGL)
+        glDrawPoints(screenSpace ? points.map(screenToWorld) : points, color.rgbaInt());
+    else
+    {
+        // draw using canvas
+        mainContext.fillStyle = color;
+        mainContext.beginPath();
+        for (const point of screenSpace ? points : points.map(worldToScreen))
+            mainContext.lineTo(point.x, point.y);
+        mainContext.fill();
+    }
 }
 
 /** Draw colored line between two points
@@ -195,12 +191,13 @@
  *  @param {Number}  [thickness=.1]
  *  @param {Color}   [color=Color()]
  *  @param {Boolean} [useWebGL=glEnable]
+ *  @param {Boolean} [screenSpace=0]
  *  @memberof Draw */
 function drawLine(posA, posB, thickness=.1, color, useWebGL)
 {
     const halfDelta = vec2((posB.x - posA.x)/2, (posB.y - posA.y)/2);
     const size = vec2(thickness, halfDelta.length()*2);
-    drawRect(posA.add(halfDelta), size, color, halfDelta.angle(), useWebGL);
+    drawRect(posA.add(halfDelta), size, color, halfDelta.angle(), useWebGL, screenSpace);
 }
 
 /** Draw directly to a 2d canvas context in world space
@@ -210,12 +207,16 @@
  *  @param {Boolean}  mirror
  *  @param {Function} drawFunction
  *  @param {CanvasRenderingContext2D} [context=mainContext]
+ *  @param {Boolean} [screenSpace=0]
  *  @memberof Draw */
-function drawCanvas2D(pos, size, angle, mirror, drawFunction, context = mainContext)
+function drawCanvas2D(pos, size, angle, mirror, drawFunction, context = mainContext, screenSpace)
 {
-    // create canvas transform from world space to screen space
-    pos = worldToScreen(pos);
-    size = size.scale(cameraScale);
+    if (!screenSpace)
+    {
+        // create canvas transform from world space to screen space
+        pos = worldToScreen(pos);
+        size = size.scale(cameraScale);
+    }
     context.save();
     context.translate(pos.x+.5|0, pos.y+.5|0);
     context.rotate(angle);
@@ -322,6 +323,17 @@
         this.context = context;
     }
 
+    /** Draw text in world space using the image font
+     *  @param {String}  text
+     *  @param {Vector2} pos
+     *  @param {Number}  [scale=.25]
+     *  @param {Boolean} [center]
+     */
+    drawText(text, pos, scale=1, center)
+    {
+        this.drawTextScreen(text, worldToScreen(pos).floor(), scale*cameraScale|0, center);
+    }
+
     /** Draw text in screen space using the image font
      *  @param {String}  text
      *  @param {Vector2} pos
@@ -359,17 +371,6 @@
 
         context.restore();
     }
-
-    /** Draw text in world space using the image font
-     *  @param {String}  text
-     *  @param {Vector2} pos
-     *  @param {Number}  [scale=.25]
-     *  @param {Boolean} [center]
-     */
-    drawText(text, pos, scale=1, center)
-    {
-        this.drawTextScreen(text, worldToScreen(pos).floor(), scale*cameraScale|0, center);
-    }
 }
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -392,4 +393,4 @@
     else if (document.body.requestFullscreen)
             document.body.requestFullscreen();
 }
-
\ No newline at end of file +
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineExport.js.html b/docs/engineExport.js.html index 142eabcc..f81a024f 100644 --- a/docs/engineExport.js.html +++ b/docs/engineExport.js.html @@ -1,8 +1,8 @@ Source: engineExport.js
On this page

engineExport.js

/** 
+    
On this page

engineExport.js

/** 
  * LittleJS Module Export
- * - Export engine as a module with extra functions where necessary
+ * - Export engine as a module with functions where necessary
  */
 
 /** Set position of camera in world space
@@ -339,8 +339,6 @@
 	worldToScreen,
 	drawTile,
 	drawRect,
-	drawTileScreenSpace,
-	drawRectScreenSpace,
 	drawLine,
 	drawCanvas2D,
 	setBlendMode,
@@ -433,4 +431,4 @@
 	engineObjectsUpdate,
 	engineObjectsDestroy,
 	engineObjectsCallback,
-};
\ No newline at end of file +};
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineInput.js.html b/docs/engineInput.js.html index 3ef1d518..a5f7a430 100644 --- a/docs/engineInput.js.html +++ b/docs/engineInput.js.html @@ -1,11 +1,11 @@ Source: engineInput.js
On this page

engineInput.js

/** 
+    
On this page

engineInput.js

/** 
  * LittleJS Input System
- * - Tracks key down, pressed, and released
- * - Also tracks mouse buttons, position, and wheel
- * - Supports multiple gamepads
- * - Virtual gamepad for touch devices with touchGamepadSize
+ * - Tracks keyboard down, pressed, and released
+ * - Tracks mouse buttons, position, and wheel
+ * - Tracks multiple analog gamepads
+ * - Virtual gamepad for touch devices
  * @namespace Input
  */
 
@@ -277,40 +277,32 @@
     let wasTouching, mouseDown = onmousedown, mouseUp = onmouseup;
     onmousedown = onmouseup = ()=> 0;
 
-    // setup touch input
-    ontouchstart = (e)=>
+    // handle all touch events the same way
+    ontouchstart = ontouchmove = ontouchend = (e)=>
     {
-        // fix mobile audio, force it to play a sound on first touch
-        zzfx(0);
+        e.button = 0; // all touches are left click
 
-        // handle all touch events the same way
-        ontouchstart = ontouchmove = ontouchend = (e)=>
-        {
-            e.button = 0; // all touches are left click
-
-            // check if touching and pass to mouse events
-            const touching = e.touches.length;
-            if (touching)
-            {
-                // set event pos and pass it along
-                e.x = e.touches[0].clientX;
-                e.y = e.touches[0].clientY;
-                wasTouching ? onmousemove(e) : mouseDown(e);
-            }
-            else if (wasTouching)
-                mouseUp(e);
-
-            // set was touching
-            wasTouching = touching;
+        // fix stalled audio on mobile
+        if (soundEnable)
+            audioContext ? audioContext.resume() : zzfx(0);
 
-            // must return true so the document will get focus
-            return true;
+        // check if touching and pass to mouse events
+        const touching = e.touches.length;
+        if (touching)
+        {
+            // set event pos and pass it along
+            e.x = e.touches[0].clientX;
+            e.y = e.touches[0].clientY;
+            wasTouching ? onmousemove(e) : mouseDown(e);
         }
+        else if (wasTouching)
+            mouseUp(e);
 
-        // try to create touch game pad
-        touchGamepadEnable && touchGamepadCreate();
+        // set was touching
+        wasTouching = touching;
 
-        return ontouchstart(e);
+        // must return true so the document will get focus
+        return true;
     }
 }
 
@@ -321,13 +313,13 @@
 let touchGamepadTimer = new Timer, touchGamepadButtons, touchGamepadStick;
 
 // create the touch gamepad, called automatically by the engine
-function touchGamepadCreate()
+if (touchGamepadEnable)
 {
     // touch input internal variables
     touchGamepadButtons = [];
     touchGamepadStick = vec2();
 
-    let touchHandler = ontouchstart;
+    const touchHandler = ontouchstart;
     ontouchstart = ontouchmove = ontouchend = (e)=> 
     {
         // clear touch gamepad input
@@ -443,4 +435,4 @@
 
     // set canvas back to normal
     overlayContext.restore();
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineMedals.js.html b/docs/engineMedals.js.html index e8625c22..b4fd560d 100644 --- a/docs/engineMedals.js.html +++ b/docs/engineMedals.js.html @@ -1,6 +1,6 @@ Source: engineMedals.js
On this page

engineMedals.js

/** 
+    
On this page

engineMedals.js

/** 
  * LittleJS Medal System
  * - Tracks and displays medals
  * - Saves medals to local storage
@@ -320,4 +320,4 @@
         // end of Crypto-JS
         ///////////////////////////////////////////////////////////////////////////////
     }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineObject.js.html b/docs/engineObject.js.html index 6625a857..a79a60be 100644 --- a/docs/engineObject.js.html +++ b/docs/engineObject.js.html @@ -1,6 +1,6 @@ Source: engineObject.js
On this page

engineObject.js

/** 
+    
On this page

engineObject.js

/** 
  * LittleJS Object System
  */
 
@@ -8,12 +8,12 @@
 
 /** 
  * LittleJS Object Base Object Class
- * - Base object class used by the engine
+ * - Top level object class used by the engine
  * - Automatically adds self to object list
  * - Will be updated and rendered each frame
  * - Renders as a sprite from a tilesheet by default
  * - Can have color and addtive color applied
- * - 2d Physics and collision system
+ * - 2D Physics and collision system
  * - Sorted by renderOrder
  * - Objects can have children attached
  * - Parents are updated before children, and set child transform
@@ -377,4 +377,4 @@
             return text;
         }
     }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineParticles.js.html b/docs/engineParticles.js.html index 996d0ce9..a26d6195 100644 --- a/docs/engineParticles.js.html +++ b/docs/engineParticles.js.html @@ -1,6 +1,6 @@ Source: engineParticles.js
On this page

engineParticles.js

/** 
+    
On this page

engineParticles.js

/** 
  * LittleJS Particle System
  */
 
@@ -305,4 +305,4 @@
             this.destroyed = 1;
         }
     }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineSettings.js.html b/docs/engineSettings.js.html index 8a267ab8..e97a568e 100644 --- a/docs/engineSettings.js.html +++ b/docs/engineSettings.js.html @@ -1,7 +1,8 @@ Source: engineSettings.js
On this page

engineSettings.js

/**
+    
On this page

engineSettings.js

/**
  * LittleJS Engine Settings
+ * - All settings for the engine are here
  * @namespace Settings
  */
 
@@ -248,4 +249,4 @@
  *  @type {Boolean}
  *  @default 0
  *  @memberof Settings */
-let medalsPreventUnlock;
\ No newline at end of file +let medalsPreventUnlock;
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineTileLayer.js.html b/docs/engineTileLayer.js.html index 339c4dd4..4c0d8c30 100644 --- a/docs/engineTileLayer.js.html +++ b/docs/engineTileLayer.js.html @@ -1,6 +1,6 @@ Source: engineTileLayer.js
On this page

engineTileLayer.js

/** 
+    
On this page

engineTileLayer.js

/** 
  * LittleJS Tile Layer System
  * - Caches arrays of tiles to off screen canvas for fast rendering
  * - Unlimted numbers of layers, allocates canvases as needed
@@ -360,4 +360,4 @@
      *  @param {Number}  [angle=0] */
     drawRect(pos, size, color, angle) 
     { this.drawTile(pos, size, -1, 0, color, angle); }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineUtilities.js.html b/docs/engineUtilities.js.html index 8fe1cf37..3997bb8d 100644 --- a/docs/engineUtilities.js.html +++ b/docs/engineUtilities.js.html @@ -1,11 +1,12 @@ Source: engineUtilities.js
On this page

engineUtilities.js

/**
+    
On this page

engineUtilities.js

/**
  * LittleJS Utility Classes and Functions
  * - General purpose math library
  * - Vector2 - fast, simple, easy 2D vector class
  * - Color - holds a rgba color with some math functions
  * - Timer - tracks time automatically
+ * - RandomGenerator - seeded random number generator
  * @namespace Utilities
  */
 
@@ -173,6 +174,12 @@
  *  @memberof Random */
 function randSign() { return randInt(2) * 2 - 1; }
 
+/** Returns a random Vector2 with the passed in length
+ *  @param {Number} [length=1]
+ *  @return {Vector2}
+ *  @memberof Random */
+function randVector(length=1) { return new Vector2().setAngle(rand(2*PI), length); }
+
 /** Returns a random Vector2 within a circular shape
  *  @param {Number} [radius=1]
  *  @param {Number} [minRadius=0]
@@ -181,12 +188,6 @@
 function randInCircle(radius=1, minRadius=0)
 { return radius > 0 ? randVector(radius * rand(minRadius / radius, 1)**.5) : new Vector2; }
 
-/** Returns a random Vector2 with the passed in length
- *  @param {Number} [length=1]
- *  @return {Vector2}
- *  @memberof Random */
-function randVector(length=1) { return new Vector2().setAngle(rand(2*PI), length); }
-
 /** Returns a random color between the two passed in colors, combine components if linear
  *  @param {Color}   [colorA=Color()]
  *  @param {Color}   [colorB=Color(0,0,0,1)]
@@ -225,7 +226,7 @@
     *  @param {Number} [valueA=1]
     *  @param {Number} [valueB=0]
     *  @return {Number} */
-    rand(valueA=1, valueB=0)
+    float(valueA=1, valueB=0)
     {
         // xorshift algorithm
         this.seed ^= this.seed << 13; 
@@ -238,11 +239,11 @@
     *  @param {Number} valueA
     *  @param {Number} [valueB=0]
     *  @return {Number} */
-    randInt(valueA, valueB=0) { return Math.floor(this.rand(valueA, valueB)); }
+    int(valueA, valueB=0) { return Math.floor(this.rand(valueA, valueB)); }
 
     /** Randomly returns either -1 or 1 deterministically
     *  @return {Number} */
-    randSign() { return this.randInt(2) * 2 - 1; }
+    sign() { return this.randInt(2) * 2 - 1; }
 }
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -657,4 +658,4 @@
     /** Get how long since elapsed, returns 0 if not set (returns negative if currently active)
      * @return {Number} */
     valueOf()               { return this.get(); }
-}
\ No newline at end of file +}
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/engineWebGL.js.html b/docs/engineWebGL.js.html index 1180b6ff..e66abe81 100644 --- a/docs/engineWebGL.js.html +++ b/docs/engineWebGL.js.html @@ -1,6 +1,6 @@ Source: engineWebGL.js
On this page

engineWebGL.js

/** 
+    
On this page

engineWebGL.js

/** 
  * LittleJS WebGL Interface
  * - All webgl used by the engine is wrapped up here
  * - For normal stuff you won't need to see or call anything in this file
@@ -205,8 +205,8 @@
 
     // draw all the sprites in the batch and reset the buffer
     glContext.bufferSubData(gl_ARRAY_BUFFER, 0, 
-        glPositionData.subarray(0, glBatchCount * gl_VERTICES_PER_QUAD * gl_INDICIES_PER_VERT));
-    glContext.drawArrays(gl_TRIANGLES, 0, glBatchCount * gl_VERTICES_PER_QUAD);
+        glPositionData.subarray(0, glBatchCount * gl_INDICIES_PER_VERT));
+    glContext.drawArrays(gl_TRIANGLE_STRIP, 0, glBatchCount);
     glBatchCount = 0;
     glBatchAdditive = glAdditive;
 }
@@ -227,39 +227,75 @@
 }
 
 /** Add a sprite to the gl draw list, used by all gl draw functions
- *  @param x
- *  @param y
- *  @param sizeX
- *  @param sizeY
- *  @param angle
- *  @param uv0X
- *  @param uv0Y
- *  @param uv1X
- *  @param uv1Y
- *  @param rgba
- *  @param [rgbaAdditive=0]
+ *  @param {Number} x
+ *  @param {Number} y
+ *  @param {Number} sizeX
+ *  @param {Number} sizeY
+ *  @param {Number} angle
+ *  @param {Number} uv0X
+ *  @param {Number} uv0Y
+ *  @param {Number} uv1X
+ *  @param {Number} uv1Y
+ *  @param {Number} rgba
+ *  @param {Number} [rgbaAdditive=0]
  *  @memberof WebGL */
 function glDraw(x, y, sizeX, sizeY, angle, uv0X, uv0Y, uv1X, uv1Y, rgba, rgbaAdditive=0)
 {
-    // flush if there is no room for more verts or if different blend mode
-    if (glBatchCount == gl_MAX_BATCH || glBatchAdditive != glAdditive)
+    // flush if there is not enough room or if different blend mode
+    const vertCount = 6;
+    if (glBatchCount >= gl_MAX_BATCH-vertCount || glBatchAdditive != glAdditive)
         glFlush();
 
     // prepare to create the verts from size and angle
     const c = Math.cos(angle)/2, s = Math.sin(angle)/2;
     const cx = c*sizeX, cy = c*sizeY, sx = s*sizeX, sy = s*sizeY;
-        
-    // setup 2 triangles to form a quad
-    for(let i=6, offset = glBatchCount++ * gl_VERTICES_PER_QUAD * gl_INDICIES_PER_VERT; i--;)
+    const positionData = 
+    [
+        x-cx+sy, y+cy+sx, uv0X, uv0Y,
+        x-cx-sy, y-cy+sx, uv0X, uv1Y,
+        x+cx+sy, y+cy-sx, uv1X, uv0Y,
+        x+cx-sy, y-cy-sx, uv1X, uv1Y,
+    ];
+
+    // setup 2 triangle strip quad
+    for(let i = vertCount, offset = glBatchCount * gl_INDICIES_PER_VERT; i--;)
     {
-        const a = i-4&&i>1, b = i-5&&i-2&&i-1;
-        glPositionData[offset++] = x + (a?-cx:cx) + (b?sy:-sy);
-        glPositionData[offset++] = y + (b?cy:-cy) + (a?sx:-sx);
-        glPositionData[offset++] = a ? uv0X : uv1X; 
-        glPositionData[offset++] = b ? uv0Y : uv1Y;
+        let j = clamp(i-1, 0, 3)*4;  // degenerate tri at ends
+        glPositionData[offset++] = positionData[j++];
+        glPositionData[offset++] = positionData[j++];
+        glPositionData[offset++] = positionData[j++];
+        glPositionData[offset++] = positionData[j++];
         glColorData[offset++] = rgba; 
         glColorData[offset++] = rgbaAdditive;
     }
+    glBatchCount += vertCount;
+}
+
+/** Add a convex polygon to the gl draw list
+ *  @param {Array} points - Array of Vector2 points
+ *  @param {Number} rgba - Color of the polygon
+ *  @memberof WebGL */
+function glDrawPoints(points, rgba)
+{
+    // flush if there is not enough room or if different blend mode
+    const vertCount = points.length + 2;
+    if (glBatchCount >= gl_MAX_BATCH-vertCount || glBatchAdditive != glAdditive)
+        glFlush();
+  
+    // setup triangle strip from list of points
+    for(let i = vertCount, offset = glBatchCount * gl_INDICIES_PER_VERT; i--;)
+    {
+        const j = clamp(i-1, 0, vertCount-3);  // degenerate tri at ends
+        const h = j>>1;
+        const point = points[j%2? h : vertCount-3-h];
+        glPositionData[offset++] = point.x;
+        glPositionData[offset++] = point.y;
+        glPositionData[offset++] = 0; // uvx
+        glPositionData[offset++] = 0; // uvy
+        glColorData[offset++] = 0;    // nothing to tint
+        glColorData[offset++] = rgba; // apply rgba via additive
+    }
+    glBatchCount += vertCount;
 }
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -353,14 +389,14 @@
     glContext.uniform1i(uniformLocation('iChannel0'), 0);
     glContext.uniform1f(uniformLocation('iTime'), time);
     glContext.uniform3f(uniformLocation('iResolution'), mainCanvas.width, mainCanvas.height, 1);
-    glContext.drawArrays(gl_TRIANGLES, 0, 3);
+    glContext.drawArrays(gl_TRIANGLE_STRIP, 0, 3);
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 // store gl constants as integers so their name doesn't use space in minifed
 const 
 gl_ONE = 1,
-gl_TRIANGLES = 4,
+gl_TRIANGLE_STRIP = 5,
 gl_SRC_ALPHA = 770,
 gl_ONE_MINUS_SRC_ALPHA = 771,
 gl_BLEND = 3042,
@@ -391,6 +427,6 @@
 // constants for batch rendering
 gl_VERTICES_PER_QUAD = 6,
 gl_INDICIES_PER_VERT = 6,
-gl_MAX_BATCH = 1<<16,
+gl_MAX_BATCH = 1e5,
 gl_VERTEX_BYTE_STRIDE = (4 * 2) * 2 + (4) * 2, // vec2 * 2 + (char * 4) * 2
-gl_VERTEX_BUFFER_SIZE = gl_MAX_BATCH * gl_VERTICES_PER_QUAD * gl_VERTEX_BYTE_STRIDE;
\ No newline at end of file +gl_VERTEX_BUFFER_SIZE = gl_MAX_BATCH * gl_VERTEX_BYTE_STRIDE;
LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 43d9b227..7cfe957f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,6 +1,6 @@ Home
On this page

LittleJS Logo LittleJS - The Tiny JavaScript Game Engine That Can

NPM PackageBuild SizeNPM DownloadsDeepScanDiscord

All aboard!

LittleJS is a lightweight open source HTML5 game engine designed for modern web development. It's small footprint is packed with a comprehensive feature set, including hybrid rendering, physics, particles, sound effects, music, input handling, and debug tools. The code is very clean and well documented with a several examples to get you started. Choo-Choo! 🚂

LittleJS Screenshot

Demos

Starter Project - Clean example with only a few things to get you started

Puzzle Game - Match 3 puzzle game with HD rendering and high score tracking

Platformer - Platformer/shooter with procedural generation and destruction

Breakout - Breakout game with post processing effect

Stress Test - Max sprite/object test and music system demo

Particle System Designer - Particle system editor and visualizer

About LittleJS

LittleJS is a small but powerful game engine with many features and no depenencies.

Graphics

  • Super fast sprite and tile map rendering engine with WebGL
  • Update and render 10,000+ objects at 60fps, often many times more
  • Apply Shadertoy compatible shaders for post processinge effects

Audio

  • Positional sound effects with ZzFX sound effect generator
  • Music with ZzFXM, mp3, or wav audio

Input

  • Input processing system for keyboard, mouse, gamepad, and touch
  • On screen touch gamepad for mobile devices

Physics

  • 2D physics engine with collision handling for axis aligned boxes
  • Very fast collision handling and raycasting for tile maps

Flexability

And more...

  • Node.js build system
  • Debug primitives rendering system
  • Particle effects system and design tool
  • Bitmap font rendering and includes a built in engine font
  • Medal system tracks and displays achievements with Newgrounds integration

How to use LittleJS

To use LittleJS download the latest package from GitHub or call npm install littlejsengine. This package contains the engine and several small examples.

You can use the empty example template as a starting point. This file contains just the minimal setup to start the engine. You can also download and include littlejs.js or littlejs.min.js.

If your game loads any files like images you will need to run a local web server. Some editors can do this automatically like Visual Studio Code with the Live Server plugin. You can also use http-server via npm.

The Breakout Tutorial is provided to demonstrate how to make a simple game from scratch. The tutorial is also available on YouTube.

Builds

To easily include LittleJS in your game, you can use one of the 3 pre-built js files. These are also built automatically by the build scripts.

LittleJS can also be imported as a module. There are two module flavors that are automatically built.

To rebuild the engine you must first run npm install to setup the necessary npm dependencies. Then call npm run build to build the engine.

The starter example project also includes a node js file build.js that compresses everything into a tiny zip file using Google Closure, UglifyJS, and ECT Zip.

Engine Source Code

This engine is made with simplicity in mind using clean easy to read code. There are only a few files used by the entire engine.

Optional Components, these components are built to synergize with the rest of the engine but are not necessary.

LittleJS Setup

To start LittleJS, you must create 5 functions and pass them to engineInit. A canvas will automatically be created and added to the document.

function gameInit()
+    
On this page

LittleJS Logo LittleJS - The Tiny JavaScript Game Engine That Can

NPM PackageBuild SizeNPM DownloadsDeepScanDiscord

🚂 All aboard!

LittleJS is a lightweight open source HTML5 game engine designed for modern web development. It's small footprint is packed with a comprehensive feature set, including hybrid rendering, physics, particles, sound effects, music, input handling, and debug tools. The code is very clean and well documented with a several examples to get you started. Choo-Choo! 🚂

LittleJS Screenshot

About LittleJS

LittleJS is a small but powerful game engine with many features and no depenencies.

✨ Graphics

  • Super fast sprite and tile map rendering engine with WebGL
  • Update and render 10,000+ objects at 60fps, often many times more
  • Particle effect system and design tool
  • Apply Shadertoy compatible shaders for post processinge effects

🔊 Audio

  • Positional sound effects with wav or ZzFX sound effect generator
  • Music with mp3, ogg, wave, or ZzFXM

🎮 Input

  • Input processing system for keyboard, mouse, gamepad, and touch
  • On screen touch gamepad for mobile devices

💥 Physics

  • 2D physics engine with collision handling for axis aligned boxes
  • Very fast collision handling and raycasting for tile maps

🚀 Flexability

  • Designed to work with all modern web bowsers and mobile devices
  • Compatible with TypeScript and Modules with example projects for both
  • For size coding competitions like js13kGames, a special example project builds to a 7KB zip file
  • Builds to a Windows executable with Electron for distribution on PC platforms like Steam
  • Open Source with the MIT license so it can be used for anything you want forever

🛠️ And more...

  • Node.js build system
  • 2D vector math library
  • Debug primitive rendering system
  • Particle effects system and design tool
  • Bitmap font rendering and includes a built in engine font
  • Medal system tracks and displays achievements with Newgrounds integration

Demos

Starter Project - Clean example with only a few things to get you started

Puzzle Game - Match 3 puzzle game with HD rendering and high score tracking

Platformer - Platformer/shooter with procedural generation and destruction

Breakout - Breakout game with post processing effect

Stress Test - Max sprite/object test and music system demo

Particle System Designer - Particle system editor and visualizer

How to use LittleJS

To use LittleJS download the latest package from GitHub or call npm install littlejsengine. This package contains the engine and several small examples.

You can use the empty example template as a starting point. This file contains just the minimal setup to start the engine. You can also download and include littlejs.js or littlejs.min.js.

If your game loads any files like images you will need to run a local web server. Some editors can do this automatically like Visual Studio Code with the Live Server plugin. You can also use http-server via npm.

The Breakout Tutorial is provided to demonstrate how to make a simple game from scratch. The tutorial is also available on YouTube.

Builds

To easily include LittleJS in your game, you can use one of the 3 pre-built js files. These are also built automatically by the build scripts.

LittleJS can also be imported as a module. There are two module flavors that are automatically built.

To rebuild the engine you must first run npm install to setup the necessary npm dependencies. Then call npm run build to build the engine.

The starter example project also includes a node js file build.js that compresses everything into a tiny zip file using Google Closure, UglifyJS, and ECT Zip.

Engine Source Code

This engine is made with simplicity in mind using clean easy to read code. There are only a few core files used by the entire engine.

Optional Components, these components are built to synergize with the rest of the engine but are not required.

LittleJS Setup

To start LittleJS, you must create 5 functions and pass them to engineInit. A canvas will automatically be created and added to the document.

function gameInit()
 {
     // called once after the engine starts up
     // setup the game
@@ -51,4 +51,4 @@
         super.render();
     }
 }
-

Debugging

Debug builds of LittleJS have a special menu that can be opened by pressing the Esc key.

  • Esc: Debug Overlay
  • 1: Debug Physics
  • 2: Debug Particles
  • 3: Debug Gamepads
  • 4: Debug Raycasts
  • 5: Save Screenshot

Games Made With LittleJS

Here are a few of the amazing games people are making with LittleJS.

LittleJS Logo

\ No newline at end of file +

Debugging

Debug builds of LittleJS have a special menu that can be opened by pressing the Esc key.

  • Esc: Debug Overlay
  • 1: Debug Physics
  • 2: Debug Particles
  • 3: Debug Gamepads
  • 4: Debug Raycasts
  • 5: Save Screenshot

Games Made With LittleJS

Here are a few of the amazing games people are making with LittleJS.

LittleJS Logo

LittleJS - The Tiny JavaScript Game Engine That Can!
\ No newline at end of file