gamvas.Actor

Description

The actor class is the most important class in gamvas.  You use it for the player, ai opponents, physics objects, maybe even static objects in your gameworld.  It forms a object that can hold animations, physical properties, states, logic and can react to events like keyboard or mouse input or collisions.  Actors hold a default animation and a default state, so if you only need one of them, you can use these, see example below.

Constructur

new gamvas.Actor(name, x, y);

Parameters

namea unique name in the game world or false to let the name autogenerate
x/ythe position of the actors center in the world (optional)

See

gamvas.ActorState gamvas.Class gamvas.Image

Example

// extend gamvas.Actor to create a new instancable actor
myActor = gamvas.Actor.extend({
    // the create function is the constructor
    create: function(name, x, y) {
        // call our super class constructor to initialize the actor
        this._super(name, x, y);
        // get our current state to get access to the resource handler
        var st = gamvas.state.getCurrentState();
        // load our animation with 64x64 pixels per frames, 10 frames
        // playing with 20 frames per second
        this.setFile(st.resource.getImage('anim.png'), 64, 64, 10, 20);
        // get default actor state
        var defState = this.myActor.getCurrentState();
        // install brain, move 10 pixels per second to the right
        defState.update = function(t) {
            this.actor.move(10*t, 0);
        };
    }
});
Summary
gamvas.ActorThe actor class is the most important class in gamvas.
Variables
nameThe name of the actor
positionA gamvas.Vector2D object with the position information
centerA gamvas.Vector2D object with the center offset of the actor
currentAnimationThe name of the current animation
rotationThe rotation of the actor
scaleFactorThe scale factor of the object
densityThe physical property of density.
frictionThe physical property of friction Defines the friction of objects.
resitutionThe physical property of resitution (bounce).
typeAllows you to set types to your physics objects to identify them.
layerInteger value used for z-sorting on automatic draw through gamvas.State.addActor
usePhysicsDelivers true/false if this object has physics enabled.
bodyThe Box2D b2Body, if physics is enabled
fixtureThe Box2D b2Fixture, if physics is enabled
Functions
initDescription
addStateAdds a actor state
addAnimationAdds a animation
createBodyCreate a Box2D b2Body object for the actor.
bodyRectmake the actor a physics object with a rectangular body shape
bodyCirclemake the actor a physics object with a circle as body shape
bodyPolygonmake the actor a physics object with a non rectangular polygon shape If you just need a rectangle, there is a shortcut: <gamvas.actor.bodyRect>
resetForcesResets all physical forces on the actor
setBulletDefines if a actor is a physics ‘bullet’.
setSensorDefines if a actor is a physics sensor or not
setAwakeAllows you to wake (or sleep) a actor in the physics simulation
setFixedRotationObject does not rotate, when under physics controll
setNameSet the actor name
setRotationSet certain rotation of the actor in radians
rotateRotate the actor
setPositionSet the position of a actor
moveMove the actor
setScaleSet a certain scale factor
scaleScale a object
setLinearDampingSets the linear damping of the physics object.
setAngularDampingSets the angular damping of the physics object.
setCenterSet the center for an actor.
getCurrentAnimationGet the current gamvas.Animation object that is playing
getCurrentStateGet the current gamvas.ActorState the actor is in
setFileSets a image file for the current animation
preDrawGets called after screen clear and before camera handling.
drawGets called when the actor is drawn.
postDrawGets called after camera handling.
isActiveCheck if the actor is active
setActiveEnable or disable the actor for automatic drawing (if in states actors list)
setStateSwitch the actor to a certain gamvas.ActorState
setAnimationSwitch the actor to a certain gamvas.Animation
setFPSSets the frames per seconds of the current animation
setFrameListSets the list of frames of the current animation
setGroupIndexSet the Box2D filter group index
setCategoryBitsSets the Box2D category bits
setMaskBitsSets the Box2D mask bits
addRevoluteJointAdd a Box2D revolute joint between this actor and another
addPrismaticJointAdd a Box2D prismatic joint between this actor and another

Variables

name

this.name

The name of the actor

position

this.position

A gamvas.Vector2D object with the position information

See

<gamvas.actor.setPosition> <gamvas.actor.move>

center

this.center

A gamvas.Vector2D object with the center offset of the actor

See

<gamvas.actor.setCenter>

currentAnimation

this.currentAnimation

The name of the current animation

rotation

this.rotation

The rotation of the actor

See

<gamvas.actor.setRotation> <gamvas.actor.rotate>

scaleFactor

this.scaleFactor

The scale factor of the object

Note

Scaling actors does not work with physics.  Well... scaling does, but the physics collision box will not be scaled.

density

this.density

The physical property of density.  In case of impact, objects with higher density will push objects with lower density away more.

Default

1.0

friction

this.friction

The physical property of friction Defines the friction of objects.  A ice ground would have a very low friction, maybe 0.1 or less, while a rubber ground would have a high value, close to 1.0.  So if you would push a ball over these grounds, on the low friction ice ground, the ball might slip over where as on the high friction rubber ground it would immediately start to roll.

Default

0.5

resitution

The physical property of resitution (bounce).  Defines how bouncy a object is.  A value of 1.0 means, that if falling to the ground, the object would jump exactly as high up as it fell down, wile smaller values will give a more natural bouncyness where with every bounce, it would bounce less, until it stops bouncing.

Default

0.3

type

this.type

Allows you to set types to your physics objects to identify them.  You could for example use “player”, “wall”, “opponent”, “tree” to identify what type of object you are colliding and react accordingly.

Default

empty string

layer

this.layer

Integer value used for z-sorting on automatic draw through gamvas.State.addActor

Note

Versions prior 0.8.3 used the layer value in the wrong direction, if you have used gamvas before this version, see gamvas.config.reverseLayerOrder

Default

0

usePhysics

this.usePhysics

Delivers true/false if this object has physics enabled.  This is meant to be read only, it will be set automatically when creating a physics body.

See

gamvas.Actor.createBody gamvas.Actor.bodyRect gamvas.Actor.bodyCircle gamvas.Actor.bodyPolygon

body

this.body

The Box2D b2Body, if physics is enabled

fixture

this.fixture

The Box2D b2Fixture, if physics is enabled

Functions

init

init: function()

Description

Overwrite with code to get executed on actor initialisation

addState

addState: function(state,
activate)

Description

Adds a actor state

Parameters

statea gamvas.ActorState object
activateif true, immediately switch to the new state (optional)

Example

myRunningState = gamvas.ActorState.extend({
    update: function(t) {
         this.actor.move(100*t, 0);
    },
    onKeyUp: function(keyCode) {
        if ( (keyCode == gamvas.key.RIGHT) || (keyCode = gamvas.key.LEFT) ) {
            this.actor.setState('walking');
        }
    }
});
myActor = gamvas.Actor.extend({
    create: function(name, x, y) {
        this._super(name, x, y);
        this.addState(new myRunningState('running'));
    }
});

addAnimation

addAnimation: function(anim)

Description

Adds a animation

Parameters

anima gamvas.Animation object

Example

myActor = gamvas.Actor.extend({
    create: function(name, x, y) {
        this._super(name, x, ,y);
        this.addAnimation(
            new gamvas.Animation('running', this.resource.getImage('playerRun.png'), 64, 64, 12, 20)
        );
    }
});

createBody

createBody: function(type,
shape)

Description

Create a Box2D b2Body object for the actor.  This is the most flexible way to create a body, but you have to do the Box2D stuff quite low level

Note

This is the low level function to add physics to your object.  Unless you are required to for some reason, you would normally not use this function directly, but use gamvas.Actor.bodyRect, gamvas.Actor.bodyCircle or gamvas.Actor.bodyPolygon

Parameters

typethe Box2D body type (dynamic/static/...)
shapethe Box2D shape for collision detection

Types

gamvas.physics.DYNAMICA body that moves, collides, etc (gamvas.physics.DYNAMIC)
gamvas.physics.STATICA body that does not move, like ground, walls, etc (gamvas.physics.STATIC)
gamvas.physics.KINEMATICA body that does move, but under player or AI controll (gamvas.physics.KINEMATIC)

See

gamvas.Actor.bodyRect gamvas.Actor.bodyPolygon gamvas.Actor.bodyCircle

Example

myPlayer = gamvas.Actor.extend({
    create: function(name, x ,y) {
        this._super(name, x, y);
        // create a polygon shape
        var shape = new Box2D.Collision.Shapes.b2PolygonShape;
        // create a box shape with 200 by 100 pixels
        // NOTE: For demonstration only, use gamvas.Actor.bodyRect for this scenario
        shape.SetAsBox(gamvas.physics.toWorld(200), gamvas.physics.toWorld(100));
        // now finally create the body, adds the actor to physics simulation automatically
        this.createBody(gamvas.physics.DYNAMIC, shape);
    }
});

bodyRect

bodyRect: function(x,
y,
width,
height,
type)

Description

make the actor a physics object with a rectangular body shape

Parameters

x/ythe position of the body in the physics world
width/heightthe half dimension of the rectangle, in pixels
typethe Box2D body type (See gamvas.Actor.createBody) (optional)

See

gamvas.Actor.createBody gamvas.Actor.bodyPolygon gamvas.Actor.bodyCircle

bodyCircle

bodyCircle: function(x,
y,
radius,
type)

Description

make the actor a physics object with a circle as body shape

Parameters

x/ythe position of the body in the physics world
radiusthe radius of the circle in pixels
typethe Box2D body type (See gamvas.Actor.createBody) (optional)

See

gamvas.Actor.createBody gamvas.Actor.bodyRect gamvas.Actor.bodyPolygon

bodyPolygon

bodyPolygon: function(x,
y,
polys,
cx,
cy,
type)

Description

make the actor a physics object with a non rectangular polygon shape If you just need a rectangle, there is a shortcut: <gamvas.actor.bodyRect>

Note

Although Box2D documentation requires a counter clock wise (CCW) polygon, gamvas does require you to secify a clock wise polygon, as in the gamvas worl, the y axis represents screen pixels and therefor runs down, whereas Box2D world represents a real life world, where positive values on the y axis run up.

Important

Box2D does not collide concave polygons (as in curving inward, like a skateboard ramp), make sure your polygons are convex (as in curving outward, like a hexagon).

Parameters

x/ythe position of the body in the physics world
polysa array holding arrays of the pixel coordinates of the vertices
cx/cythe center of the polygon object (optional)
typethe Box2D body type (See gamvas.Actor.createBody) (optional)

See

gamvas.Actor.createBody gamvas.Actor.bodyRect gamvas.Actor.bodyCircle

Example

Create a triangle object with a image of the size 64 by 64 pixels with the center in the middle, at screen position 200, 50

this.bodyPolygon(200, 50, [ [32, 0], [64, 64], [0, 64] ], 32, 32);

resetForces

resetForces: function(x,
y,
r)

Description

Resets all physical forces on the actor

When called without parameter, it just stops rotation and movement.  With the optional parameters, you can fully reset the actor to its starting position/rotation

Parameters

x/yThe position to set the actor to (optional)
rThe rotation to set the actor to (in radians)

setBullet

setBullet: function(b)

Description

Defines if a actor is a physics ‘bullet’.

A bullet gets increased precision (but slower) collision calculation.  Immagine a bullet flying towards a thin piece of metal.  In real world, that bullet would hit the metal, no matter what, because the real world is not running in frames per second.  The physics simulation on the other hand does, therefor, if the bullet moves very fast, the bullet actually skips through the air, because it traveled a certain amount since the last frame redraw.  This can lead to very fast moving objects falling through walles that they would collide when they would move slower, because they skiped a distance larger then this colliding objects width.

By setting a actor to a bullet, you can ensure that it always collides, even if it skips that part because of the frame based simulation.

Note

This is a expensive operation, only use it on important objects (like e.b. the players spaceship) and only if necessary because your objects falls through stuff that it should collide with

Parameters

btrue/false

Default

false

setSensor

setSensor: function(b)

Defines if a actor is a physics sensor or not

Sensors do recognize collisions, but are not influenced by the collision forces, so will continue moving as there would not be a collision, but there is one.

You would use sensors to trigger events, like open a door if the player stands right before it.

Parameters

btrue/false

Default

false

setAwake

setAwake: function(b)

Description

Allows you to wake (or sleep) a actor in the physics simulation

Sleeping actors are not considered in the simulation, until something hits them.  Then they are automatically switched awake.

Parameters

btrue/false

setFixedRotation

setFixedRotation: function(b)

Description

Object does not rotate, when under physics controll

Parameters

btrue/false

Default

false

setName

setName: function(name)

Description

Set the actor name

Parameters

namethe actors name, must be unique in the game world

setRotation

setRotation: function(r)

Description

Set certain rotation of the actor in radians

Parameters

rthe rotation in radians

See

gamvas.Actor.rotate http://en.wikipedia.org/wiki/Radians

rotate

rotate: function(r)

Description

Rotate the actor

Parameters

rthe amount to rotate the actor in radians

See

gamvas.Actor.setRotation http://en.wikipedia.org/wiki/Radians

setPosition

setPosition: function(x,
y)

Description

Set the position of a actor

Parameters

x/ythe position of the actor in pixels

See

gamvas.Actor.move

move

move: function(x,
y)

Description

Move the actor

Parameters

x/ythe pixels to move the actor

See

gamvas.Actor.setPosition

setScale

setScale: function(s)

Description

Set a certain scale factor

Note

Do not use scale for objects under physics controll it will work for the image, but not for the collision object

Parameters

sthe scale value (1 = no scale, < 1 = smaller, > 1 = bigger)

See

gamvas.Actor.scale

scale

scale: function(s)

Description

Scale a object

Note

Do not use scale for objects under physics controll it will work for the image, but not for the collision object

Parameters

sthe scale factor (< 0 = shrink, > 0 = enlarge)

See

gamvas.Actor.setScale

setLinearDamping

setLinearDamping: function(d)

Description

Sets the linear damping of the physics object.

This means, the higher the value, the more will the object be slowed down while simply ‘rolling along’

setAngularDamping

setAngularDamping: function(d)

Description

Sets the angular damping of the physics object.

A angular damping slows down the rotation of a object over time while no other forces are having impact on it

setCenter

setCenter: function(x,
y)

Description

Set the center for an actor.  If you have a round object for example with a size of 64 by 64 pixels and you want to rotate it around the center, you would use myObject.setCenter(32, 32);

Parameters

x/ythe center, as seen of the upper left corner of the object

getCurrentAnimation

getCurrentAnimation: function()

Description

Get the current gamvas.Animation object that is playing

Returns

gamvas.Animation

getCurrentState

getCurrentState: function()

Description

Get the current gamvas.ActorState the actor is in

Returns

gamvas.ActorState

setFile

setFile: function(file,
frameWidth,
frameHeight,
numberOfFrames,
fps)

Description

Sets a image file for the current animation

Parameters

filea JavaScript Image object holding the animation in tiles
frameWidththe width of a single frame tile of the animation
frameHeightthe height of a single frame tile of the animation
numberOfFramesthe number of frames in the animation
fpsthe speed of the animation in frames per second

Example

myActor = gamvas.Actor.extend({
    create: function(name, x, y) {
        this._super(name, x,, y);
        var st = gamvas.state.getCurrentState();
        this.setFile(st.resource.getImage('anim.png'), 64, 64, 10, 20);
    }
});

preDraw

preDraw: function(t)

Description

Gets called after screen clear and before camera handling.

Parameters

tthe time since last redraw

See

gamvas.ActorState.update

draw

draw: function(t)

Description

Gets called when the actor is drawn.  Usually you would not overwrite this function with your logic, use the gamvas.ActorState.update function of either the default state or a custom gamvas.ActorState

Parameters

tthe time since last redraw

See

gamvas.ActorState.update

postDraw

postDraw: function(t)

Description

Gets called after camera handling.

Parameters

tthe time since last redraw

See

gamvas.ActorState.update

isActive

isActive: function()

Description

Check if the actor is active

See

gamvas.Actor.setActive

setActive

setActive: function(yesno)

Description

Enable or disable the actor for automatic drawing (if in states actors list)

See

gamvas.State.addActor

setState

setState: function(stateName)

Description

Switch the actor to a certain gamvas.ActorState

Parameters

stateNamethe name of the gamvas.ActorState

See

gamvas.ActorState

setAnimation

setAnimation: function(a)

Description

Switch the actor to a certain gamvas.Animation

Parameters

athe name of the gamvas.Animation

See

gamvas.Animation

setFPS

setFPS: function(fps)

Sets the frames per seconds of the current animation

See

gamvas.Animation.setFPS for more information

setFrameList

setFrameList: function(fl)

Sets the list of frames of the current animation

See

gamvas.Animation.setFrameList for more information

setGroupIndex

setGroupIndex: function(g)

Description

Set the Box2D filter group index

All members of a negative group never collide, or of a positive group always collide

Parameters

gThe group index, negative or positive values disable or enable collision

Example

Set 4 objects group index, so ncol1 and ncol2 never collide with each other but all other objects collide with everything

this.ncol1.setGroupIndex(-1);
this.ncol2.setGroupIndex(-1);
this.col1.setGroupIndex(1);
this.col2.setGroupIndex(1);

setCategoryBits

setCategoryBits: function(b)

Description

Sets the Box2D category bits

You can have up to 16 categories for your physics objects like for example player, monster, coins and together with <gamvas.actor.setMaskBits> you can specify which category can collide with which

Parameters

ba bitfield which category the current object belongs

See

<gamvas.actor.setMaskBits>

setMaskBits

setMaskBits: function(b)

Description

Sets the Box2D mask bits

You can have up to 16 categories for your physics objects.  With the mask bits you specify with which category to collide with, whereas 1 means collide, and 0 means ignore collision.

Parameters

ba bitfield which categories to collide with

See

<gamvas.actor.setCategoryBits>

addRevoluteJoint

addRevoluteJoint: function(t,
tp,
params)

Description

Add a Box2D revolute joint between this actor and another

Revolute joints are hinge like joints, you can limit their angle and use them as motors.

Parameters

tthe target actor
tpthe target position, either as b2Vec2D or gamvas.Vector2D (optional)
paramsa list of joint parameters, see below (optional)

Joint Parameters

For detailed description see Box2D manual on http://box2d.org/manual.html

lowerAngleangle in radians
upperAngleangle in radians
enableLimittrue/false
maxMotorTorquemaximum torque value
motorSpeedcurrent motor speed
enableMotortrue/false

addPrismaticJoint

addPrismaticJoint: function(t,
tp,
tv,
params)

Description

Add a Box2D prismatic joint between this actor and another

Prismatic joints are joints movable along a axis, similar to springs

Parameters

tthe target actor
tpthe target position, either as b2Vec2D or gamvas.Vector2D (optional)
tvthe target vector, aka the direction of the joint, either as b2Vec2D or gamvas.Vector2D (optional)
paramsa list of joint parameters, see below (optional)

Joint Parameters

For detailed description see Box2D manual on http://box2d.org/manual.html

upperTranslationthe upper translation limit
lowerTranslationthe lower translation limit
enableLimittrue/false
maxMotorForcethe maximum motor force
motorSpeedthe current motor speed
enableMotortrue/false

Note

upperTranslation and lowerTranslation should allow the value zero between them, because the joint will start with zero.  For example: upperTranslation = -0.2 lowerTranslation = 0.3

this.name
The name of the actor
this.position
A gamvas.Vector2D object with the position information
A 2D vector class
this.center
A gamvas.Vector2D object with the center offset of the actor
this.currentAnimation
The name of the current animation
this.rotation
The rotation of the actor
this.scaleFactor
The scale factor of the object
this.density
The physical property of density.
this.friction
The physical property of friction Defines the friction of objects.
this.type
Allows you to set types to your physics objects to identify them.
this.layer
Integer value used for z-sorting on automatic draw through gamvas.State.addActor
addActor: function(act)
Add a gamvas.Actor to the state.
this.usePhysics
Delivers true/false if this object has physics enabled.
this.body
The Box2D b2Body, if physics is enabled
this.fixture
The Box2D b2Fixture, if physics is enabled
init: function()
Description
addState: function(state,
activate)
Adds a actor state
addAnimation: function(anim)
Adds a animation
createBody: function(type,
shape)
Create a Box2D b2Body object for the actor.
bodyRect: function(x,
y,
width,
height,
type)
make the actor a physics object with a rectangular body shape
bodyCircle: function(x,
y,
radius,
type)
make the actor a physics object with a circle as body shape
bodyPolygon: function(x,
y,
polys,
cx,
cy,
type)
make the actor a physics object with a non rectangular polygon shape If you just need a rectangle, there is a shortcut: gamvas.actor.bodyRect
resetForces: function(x,
y,
r)
Resets all physical forces on the actor
setBullet: function(b)
Defines if a actor is a physics ‘bullet’.
setSensor: function(b)
Defines if a actor is a physics sensor or not
setAwake: function(b)
Allows you to wake (or sleep) a actor in the physics simulation
setFixedRotation: function(b)
Object does not rotate, when under physics controll
setName: function(name)
Set the actor name
setRotation: function(r)
Set certain rotation of the actor in radians
rotate: function(r)
Rotate the actor
setPosition: function(x,
y)
Set the position of a actor
move: function(x,
y)
Move the actor
setScale: function(s)
Set a certain scale factor
scale: function(s)
Scale a object
setLinearDamping: function(d)
Sets the linear damping of the physics object.
setAngularDamping: function(d)
Sets the angular damping of the physics object.
setCenter: function(x,
y)
Set the center for an actor.
getCurrentAnimation: function()
Get the current gamvas.Animation object that is playing
Class for animated sprites
getCurrentState: function()
Get the current gamvas.ActorState the actor is in
A class for actor states
setFile: function(file,
frameWidth,
frameHeight,
numberOfFrames,
fps)
Sets a image file for the current animation
preDraw: function(t)
Gets called after screen clear and before camera handling.
draw: function(t)
Gets called when the actor is drawn.
postDraw: function(t)
Gets called after camera handling.
isActive: function()
Check if the actor is active
setActive: function(yesno)
Enable or disable the actor for automatic drawing (if in states actors list)
setState: function(stateName)
Switch the actor to a certain gamvas.ActorState
setAnimation: function(a)
Switch the actor to a certain gamvas.Animation
setFPS: function(fps)
Sets the frames per seconds of the current animation
setFrameList: function(fl)
Sets the list of frames of the current animation
setGroupIndex: function(g)
Set the Box2D filter group index
setCategoryBits: function(b)
Sets the Box2D category bits
setMaskBits: function(b)
Sets the Box2D mask bits
addRevoluteJoint: function(t,
tp,
params)
Add a Box2D revolute joint between this actor and another
addPrismaticJoint: function(t,
tp,
tv,
params)
Add a Box2D prismatic joint between this actor and another
The basic class for inheritance
A plain image with methods to move, rotate and zoom.
reverseLayerOrder: false
Reverse layer sorting
define for a dynamic body
define for a static body
define for a kinematic body
update: function(t)
Update the ai.
setFPS: function(fps)
Set the speed of the animation in frames per second
setFrameList: function(fl)
Allows to set a list of frames that are considdered to be the animation
Close