Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Actor

The most important primitive in Excalibur is an Actor. Anything that can move on the screen, collide with another Actor, respond to events, or interact with the current scene, must be an actor. An Actor must be part of a Scene for it to be drawn to the screen.

Basic actors

For quick and dirty games, you can just create an instance of an Actor and manipulate it directly.

Actors (and other entities) must be added to a Scene to be drawn and updated on-screen.

var player = new ex.Actor();

// move the player
player.vel.x = 5;

// add player to the current scene
game.add(player);

game.add is a convenience method for adding an Actor to the current scene. The equivalent verbose call is game.currentScene.add.

Actor Lifecycle

An actor has a basic lifecycle that dictates how it is initialized, updated, and drawn. Once an actor is part of a scene, it will follow this lifecycle.

Actor Lifecycle

Extending actors

For "real-world" games, you'll want to extend the Actor class. This gives you much greater control and encapsulates logic for that actor.

You can override the onInitialize method to perform any startup logic for an actor (such as configuring state). onInitialize gets called once before the first frame an actor is drawn/updated. It is passed an instance of Engine to access global state or perform coordinate math.

TypeScript

class Player extends ex.Actor {

   public level = 1;
   public endurance = 0;
   public fortitude = 0;

   constructor() {
      super();
   }

   public onInitialize(engine: ex.Engine) {
      this.endurance = 20;
      this.fortitude = 16;
   }

   public getMaxHealth() {
      return (0.4 * this.endurance) + (0.9 * this.fortitude) + (this.level * 1.2);
   }
}

Javascript

In Javascript you can use the extend method to override or add methods to an Actor.

var Player = ex.Actor.extend({

   level: 1,
   endurance: 0,
   fortitude: 0,

   onInitialize: function (engine) {
      this.endurance = 20;
      this.fortitude = 16;
   },

   getMaxHealth: function () {
      return (0.4 * this.endurance) + (0.9 * this.fortitude) + (this.level * 1.2);
   }
});

Updating actors

Override the update method to update the state of your actor each frame. Typically things that need to be updated include state, drawing, or position.

Remember to call super.update to ensure the base update logic is performed. You can then write your own logic for what happens after that.

The update method is passed an instance of the Excalibur engine, which can be used to perform coordinate math or access global state. It is also passed delta which is the time in milliseconds since the last frame, which can be used to perform time-based movement or time-based math (such as a timer).

TypeScript

class Player extends Actor {
   public update(engine: ex.Engine, delta: number) {
      super.update(engine, delta); // call base update logic

      // check if player died
      if (this.health <= 0) {
         this.emit("death");
         this.onDeath();
         return;
      }
   }
}

Javascript

var Player = ex.Actor.extend({
   update: function (engine, delta) {
      ex.Actor.prototype.update.call(this, engine, delta); // call base update logic

      // check if player died
      if (this.health <= 0) {
         this.emit("death");
         this.onDeath();
         return;
      }
   }
});

Drawing actors

Override the draw method to perform any custom drawing. For simple games, you don't need to override draw, instead you can use addDrawing and setDrawing to manipulate the sprites/animations that the actor is using.

Working with Textures & Sprites

Think of a texture as the raw image file that will be loaded into Excalibur. In order for it to be drawn it must be converted to a [[Sprite.sprite]].

A common usage is to load a Texture and convert it to a Sprite for an actor. If you are using the Loader to pre-load assets, you can simply assign an actor a Sprite to draw. You can also create a sprite from a Texture to quickly create a Sprite instance.

// assume Resources.TxPlayer is a 80x80 png image

public onInitialize(engine: ex.Engine) {

   // set as the "default" drawing
   this.addDrawing(Resources.TxPlayer);

   // you can also set a Sprite instance to draw
   this.addDrawing(Resources.TxPlayer.asSprite());
}

Working with Animations

A SpriteSheet holds a collection of sprites from a single Texture. Use SpriteSheet.getAnimationForAll to easily generate an Animation.

// assume Resources.TxPlayerIdle is a texture containing several frames of an animation

public onInitialize(engine: ex.Engine) {

   // create a SpriteSheet for the animation
   var playerIdleSheet = new ex.SpriteSheet(Resources.TxPlayerIdle, 5, 1, 80, 80);

   // create an animation
   var playerIdleAnimation = playerIdleSheet.getAnimationForAll(engine, 120);

   // the first drawing is always the current
   this.addDrawing("idle", playerIdleAnimation);
}

Custom drawing

You can always override the default drawing logic for an actor in the draw method, for example, to draw complex shapes or to use the raw Canvas API.

Usually you should call super.draw to perform the base drawing logic, but other times you may want to take over the drawing completely.

public draw(ctx: Canvas2DRenderingContext, delta: number) {

   super.draw(ctx, delta); // perform base drawing logic

   // custom drawing
   ctx.lineTo(...);
}

Actions

You can use the Action API to create chains of actions and script actors into doing your bidding for your game.

Actions can be simple or can be chained together to create complex AI routines. In the future, it will be easier to create timelines or scripts to run depending on the state of your actor, such as an enemy ship that is Guarding a path and then is Alerted when a Player draws near.

Learn more about the Action API.

Collision Detection

By default Actors do not participate in collisions. If you wish to make an actor participate, you need to switch from the default prevent collision to active, fixed, or passive collision type.

public Player extends ex.Actor {
   constructor() {
      super();
      // set preferred CollisionType
      this.collisionType = ex.CollisionType.Active;
   }
}

// or set the collisionType 

var actor = new ex.Actor();
actor.collisionType = ex.CollisionType.Active;

Collision Groups

TODO, needs more information.

Traits

Traits describe actor behavior that occurs every update. If you wish to build a generic behavior without needing to extend every actor you can do it with a trait, a good example of this may be plugging in an external collision detection library like Box2D or PhysicsJS by wrapping it in a trait. Removing traits can also make your actors more efficient.

Default traits provided by Excalibur are pointer capture, [[Traits.CollisionDetection|tile map collision]], [[Traits.Movement|Euler style movement]], and offscreen culling.

Known Issues

Actor bounding boxes do not rotate Issue #68

Hierarchy

Implements

Index

Constructors

constructor

  • new Actor(x?: number, y?: number, width?: number, height?: number, color?: Color): Actor
  • Parameters

    • Optional x: number

      The starting x coordinate of the actor

    • Optional y: number

      The starting y coordinate of the actor

    • Optional width: number

      The starting width of the actor

    • Optional height: number

      The starting height of the actor

    • Optional color: Color

      The starting color of the actor. Leave null to draw a transparent actor. The opacity of the color will be used as the initial opacity.

    Returns Actor

Properties

Private _collisionHandlers

_collisionHandlers: object

Type declaration

  • [key: string]: function[]
      • Parameters

        Returns void

Private _effectsDirty

_effectsDirty: boolean = false

Private _height

_height: number = 0

Private _isInitialized

_isInitialized: boolean = false

Private _isKilled

_isKilled: boolean = false

Private _opacityFx

_opacityFx: Opacity = new Effects.Opacity(this.opacity)

Private _width

_width: number = 0

Private _zIndex

_zIndex: number = 0

actionQueue

actionQueue: ActionQueue

Direct access to the actor's ActionQueue. Useful if you are building custom actions.

actions

actions: ActionContext

Action context of the actor. Useful for scripting actor behavior.

anchor

anchor: Vector

The anchor to apply all actor related transformations like rotation, translation, and rotation. By default the anchor is in the center of the actor. By default it is set to the center of the actor (.5, .5)

An anchor of (.5, .5) will ensure that drawings are centered.

Use anchor.setTo to set the anchor to a different point using values between 0 and 1. For example, anchoring to the top-left would be Actor.anchor.setTo(0, 0) and top-right would be Actor.anchor.setTo(0, 1).

body

body: Body = new Body(this)

The physics body the is associated with this actor. The body is the container for all physical properties, like position, velocity, acceleration, mass, inertia, etc.

children

children: Actor[] = []

The children of this actor

collisionGroups

collisionGroups: string[] = []

collisionType

collisionType: CollisionType = CollisionType.PreventCollision

Gets or sets the current collision type of this actor. By default it is (CollisionType.PreventCollision).

color

color: Color

Sets the color of the actor. A rectangle of this color will be drawn if no IDrawable is specified as the actors drawing.

The default is null which prevents a rectangle from being drawn.

currentDrawing

currentDrawing: IDrawable = null

Access to the current drawing for the actor, this can be an Animation, Sprite, or Polygon. Set drawings with setDrawing.

enableCapturePointer

enableCapturePointer: boolean = false

Whether or not to enable the CapturePointer trait that propagates pointer events to this actor

eventDispatcher

eventDispatcher: EventDispatcher

Direct access to the game object event dispatcher.

frames

frames: object

Type declaration

id

id: number = Actor.maxId++

The unique identifier for the actor

isOffScreen

isOffScreen: boolean = false

Indicates whether the actor is physically in the viewport

logger

logger: Logger = Logger.getInstance()

Convenience reference to the global logger

opacity

opacity: number = 1

The opacity of an actor. Passing in a color in the constructor will use the color's opacity.

parent

parent: Actor = null

The parent of this actor

previousOpacity

previousOpacity: number = 1

scale

scale: Vector = new ex.Vector(1, 1)

The scale vector of the actor

scene

scene: Scene = null

The scene that the actor is in

sx

sx: number = 0

The x scalar velocity of the actor in scale/second

sy

sy: number = 0

The y scalar velocity of the actor in scale/second

traits

traits: IActorTrait[] = []

Modify the current actor update pipeline.

visible

visible: boolean = true

The visibility of an actor

Static maxId

maxId: number = 0

Indicates the next id to be set

Accessors

acc

  • Gets the acceleration vector of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may be useful to simulate a gravitational effect.

    Returns Vector

  • Sets the acceleration vector of teh actor in pixels/second/second

    Parameters

    Returns void

collisionArea

  • Gets the collision area shape to use for collision possible options are [CircleArea|circles], [PolygonArea|polygons], and [EdgeArea|edges].

    Returns ICollisionArea

  • Gets the collision area shape to use for collision possible options are [CircleArea|circles], [PolygonArea|polygons], and [EdgeArea|edges].

    Parameters

    Returns void

friction

  • get friction(): number
  • set friction(theFriction: number): void
  • Gets the coefficient of friction on this actor, this can be thought of as how sticky or slippery an object is.

    Returns number

  • Sets the coefficient of friction of this actor, this can ve thought of as how stick or slippery an object is.

    Parameters

    • theFriction: number

    Returns void

mass

  • get mass(): number
  • set mass(theMass: number): void
  • Get the current mass of the actor, mass can be thought of as the resistance to acceleration.

    Returns number

  • Sets the mass of the actor, mass can be thought of as the resistance to acceleration.

    Parameters

    • theMass: number

    Returns void

moi

  • get moi(): number
  • set moi(theMoi: number): void
  • Gets the current moment of inertia, moi can be thought of as the resistance to rotation.

    Returns number

  • Sets the current moment of inertia, moi can be thought of as the resistance to rotation.

    Parameters

    • theMoi: number

    Returns void

oldPos

  • Gets the position vector of the actor from the last frame

    Returns Vector

  • Sets the position vector of the actor in the last frame

    Parameters

    Returns void

oldVel

  • Gets the velocity vector of the actor from the last frame

    Returns Vector

  • Sets the velocity vector of the actor from the last frame

    Parameters

    Returns void

pos

  • Gets the position vector of the actor in pixels

    Returns Vector

  • Sets the position vector of the actor in pixels

    Parameters

    Returns void

restitution

  • get restitution(): number
  • set restitution(theRestitution: number): void
  • Gets the coefficient of restitution of this actor, represents the amount of energy preserved after collision. Think of this as bounciness.

    Returns number

  • Sets the coefficient of restitution of this actor, represents the amount of energy preserved after collision. Think of this as bounciness.

    Parameters

    • theRestitution: number

    Returns void

rotation

  • get rotation(): number
  • set rotation(theAngle: number): void
  • Gets the rotation of the actor in radians. 1 radian = 180/PI Degrees.

    Returns number

  • Sets the rotation of the actor in radians. 1 radian = 180/PI Degrees.

    Parameters

    • theAngle: number

    Returns void

rx

  • get rx(): number
  • set rx(angularVelocity: number): void
  • Gets the rotational velocity of the actor in radians/second

    Returns number

  • Sets the rotational velocity of the actor in radians/sec

    Parameters

    • angularVelocity: number

    Returns void

torque

  • get torque(): number
  • set torque(theTorque: number): void
  • Gets the current torque applied to the actor. Torque can be thought of as rotational force

    Returns number

  • Sets the current torque applied to the actor. Torque can be thought of as rotational force

    Parameters

    • theTorque: number

    Returns void

vel

  • Gets the velocity vector of the actor in pixels/sec

    Returns Vector

  • Sets the velocity vector of the actor in pixels/sec

    Parameters

    Returns void

x

  • get x(): number
  • set x(theX: number): void
  • Gets the x position of the actor relative to it's parent (if any)

    Returns number

  • Sets the x position of the actor relative to it's parent (if any)

    Parameters

    • theX: number

    Returns void

y

  • get y(): number
  • set y(theY: number): void
  • Gets the y position of the actor relative to it's parent (if any)

    Returns number

  • Sets the y position of the actor relative to it's parent (if any)

    Parameters

    • theY: number

    Returns void

z

  • get z(): number
  • set z(newZ: number): void
  • Returns number

  • Parameters

    • newZ: number

    Returns void

Methods

Private _checkForPointerOptIn

  • _checkForPointerOptIn(eventName: string): void
  • Parameters

    • eventName: string

    Returns void

Private _getCalculatedAnchor

  • _getCalculatedAnchor(): Vector
  • Returns Vector

Protected _reapplyEffects

  • Parameters

    Returns void

add

  • add(actor: Actor): void
  • Adds a child actor to this actor. All movement of the child actor will be relative to the parent actor. Meaning if the parent moves the child will move with it.

    Parameters

    • actor: Actor

      The child actor to add

    Returns void

addCollisionGroup

  • addCollisionGroup(name: string): void
  • Adds an actor to a collision group. Actors with no named collision groups are considered to be in every collision group.

    Once in a collision group(s) actors will only collide with other actors in that group.

    Parameters

    • name: string

      The name of the collision group

    Returns void

addDrawing

  • addDrawing(texture: Texture): any
  • addDrawing(sprite: Sprite): any
  • addDrawing(key: any, drawing: IDrawable): any
  • Adds a whole texture as the "default" drawing. Set a drawing using setDrawing.

    Parameters

    Returns any

  • Adds a whole sprite as the "default" drawing. Set a drawing using setDrawing.

    Parameters

    Returns any

  • Adds a drawing to the list of available drawings for an actor. Set a drawing using setDrawing.

    Parameters

    Returns any

collides

  • Test whether the actor has collided with another actor, returns the intersection vector on collision. Returns null when there is no collision;

    Parameters

    • actor: Actor

      The other actor to test

    Returns Vector

collidesWithSide

  • Test whether the actor has collided with another actor, returns the side of the current actor that collided.

    Parameters

    • actor: Actor

      The other actor to test

    Returns Side

contains

  • contains(x: number, y: number, recurse?: boolean): boolean
  • Tests whether the x/y specified are contained in the actor

    Parameters

    • x: number

      X coordinate to test (in world coordinates)

    • y: number

      Y coordinate to test (in world coordinates)

    • Default value recurse: boolean = false

      checks whether the x/y are contained in any child actors (if they exist).

    Returns boolean

debugDraw

  • debugDraw(ctx: CanvasRenderingContext2D): void
  • Called by the Engine, draws the actors debugging to the screen

    Parameters

    • ctx: CanvasRenderingContext2D

      The rendering context

    Returns void

draw

  • draw(ctx: CanvasRenderingContext2D, delta: number): void
  • Called by the Engine, draws the actor to the screen

    Parameters

    • ctx: CanvasRenderingContext2D

      The rendering context

    • delta: number

      The time since the last draw in milliseconds

    Returns void

emit

  • emit(eventName: string, eventObject?: GameEvent): void
  • Emits a new event

    Parameters

    • eventName: string

      Name of the event to emit

    • Optional eventObject: GameEvent

      Data associated with this event

    Returns void

getBottom

  • getBottom(): number
  • Gets the bottom edge of the actor

    Returns number

getBounds

  • Returns the actor's BoundingBox calculated for this instant in world space.

    Returns BoundingBox

getCenter

  • Get the center point of an actor

    Returns Vector

getCollisionHandlers

  • getCollisionHandlers(): object
  • Returns object

    • [key: string]: function[]
        • Parameters

          Returns void

getGlobalScale

  • Gets the global scale of the Actor

    Returns Vector

getHeight

  • getHeight(): number
  • Gets the calculated height of an actor, factoring in scale

    Returns number

getLeft

  • getLeft(): number
  • Gets the left edge of the actor

    Returns number

getRelativeBounds

  • Returns the actor's BoundingBox relative to the actors position.

    Returns BoundingBox

getRight

  • getRight(): number
  • Gets the right edge of the actor

    Returns number

getSideFromIntersect

  • Returns the side of the collision based on the intersection

    Parameters

    • intersect: Vector

      The displacement vector returned by a collision

    Returns Side

getTop

  • getTop(): number
  • Gets the top edge of the actor

    Returns number

getWidth

  • getWidth(): number
  • Gets the calculated width of an actor, factoring in scale

    Returns number

getWorldPos

  • Gets an actor's world position taking into account parent relationships, scaling, rotation, and translation

    Returns Vector

    Position in world coordinates

getWorldRotation

  • getWorldRotation(): number
  • Gets this actor's rotation taking into account any parent relationships

    Returns number

    Rotation angle in radians

getZIndex

  • getZIndex(): number
  • Gets the z-index of an actor. The z-index determines the relative order an actor is drawn in. Actors with a higher z-index are drawn on top of actors with a lower z-index

    Returns number

integrate

  • integrate(delta: number): void
  • Perform euler integration at the specified time step

    Parameters

    • delta: number

    Returns void

isKilled

  • isKilled(): boolean
  • Indicates wether the actor has been killed.

    Returns boolean

kill

  • kill(): void
  • If the current actor is a member of the scene, this will remove it from the scene graph. It will no longer be drawn or updated.

    Returns void

off

  • off(eventName: string, handler?: function): void
  • Alias for removeEventListener. If only the eventName is specified it will remove all handlers registered for that specific event. If the eventName and the handler instance are specified only that handler will be removed.

    Parameters

    • eventName: string

      Name of the event to listen for

    • Optional handler: function

      Event handler for the thrown event

    Returns void

on

  • on(eventName: kill, handler: function): any
  • on(eventName: initialize, handler: function): any
  • on(eventName: preupdate, handler: function): any
  • on(eventName: postupdate, handler: function): any
  • on(eventName: predraw, handler: function): any
  • on(eventName: postdraw, handler: function): any
  • on(eventName: predebugdraw, handler: function): any
  • on(eventName: postdebugdraw, handler: function): any
  • on(eventName: pointerup, handler: function): any
  • on(eventName: pointerdown, handler: function): any
  • on(eventName: pointermove, handler: function): any
  • on(eventName: pointercancel, handler: function): any
  • on(eventName: string, handler: function): any
  • Parameters

    • eventName: kill
    • handler: function

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    • eventName: pointerup
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointerdown
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointermove
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointercancel
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: string
    • handler: function

    Returns any

onCollidesWith

  • onCollidesWith(group: string, func: function): void
  • Register a handler to fire when this actor collides with another in a specified group

    Parameters

    • group: string

      The group name to listen for

    • func: function

      The callback to fire on collision with another actor from the group. The callback is passed the other actor.

        • Parameters

          Returns void

    Returns void

onInitialize

  • onInitialize(engine: Engine): void
  • This is called before the first update of the actor. This method is meant to be overridden. This is where initialization of child actors should take place.

    Parameters

    Returns void

remove

  • remove(actor: Actor): void
  • Removes a child actor from this actor.

    Parameters

    • actor: Actor

      The child actor to remove

    Returns void

removeCollidesWith

  • removeCollidesWith(group: string): void
  • Removes all collision handlers for this group on this actor

    Parameters

    • group: string

      Group to remove all handlers for on this actor.

    Returns void

removeCollisionGroup

  • removeCollisionGroup(name: string): void
  • Removes an actor from a collision group.

    Parameters

    • name: string

      The name of the collision group

    Returns void

setDrawing

  • setDrawing(key: string): any
  • setDrawing(key: number): any
  • Sets the current drawing of the actor to the drawing corresponding to the key.

    Parameters

    • key: string

      The key of the drawing

    Returns any

  • Sets the current drawing of the actor to the drawing corresponding to an enum key (e.g. Animations.Left)

    Parameters

    • key: number

      The enum key of the drawing

    Returns any

setHeight

  • setHeight(height: any): void
  • Sets the height of an actor, factoring in the current scale

    Parameters

    • height: any

    Returns void

setWidth

  • setWidth(width: any): void
  • Sets the width of an actor, factoring in the current scale

    Parameters

    • width: any

    Returns void

setZIndex

  • setZIndex(newIndex: number): void
  • Sets the z-index of an actor and updates it in the drawing list for the scene. The z-index determines the relative order an actor is drawn in. Actors with a higher z-index are drawn on top of actors with a lower z-index

    Parameters

    • newIndex: number

      new z-index to assign

    Returns void

unkill

  • unkill(): void
  • If the current actor is killed, it will now not be killed.

    Returns void

update

  • update(engine: Engine, delta: number): void
  • Called by the Engine, updates the state of the actor

    Parameters

    • engine: Engine

      The reference to the current game engine

    • delta: number

      The time elapsed since the last update in milliseconds

    Returns void

within

  • within(actor: Actor, distance: number): boolean
  • Returns true if the two actors are less than or equal to the distance specified from each other

    Parameters

    • actor: Actor

      Actor to test

    • distance: number

      Distance in pixels to test

    Returns boolean

Static extend

  • extend(methods: any): any
  • You may wish to extend native Excalibur functionality in vanilla Javascript. Any method on a class inheriting Class may be extended to support additional functionality. In the example below we create a new type called MyActor.

    var MyActor = Actor.extend({
    
       constructor: function() {
          this.newprop = 'something';
          Actor.apply(this, arguments);
       },
    
       update: function(engine, delta) {
          // Implement custom update
          // Call super constructor update
          Actor.prototype.update.call(this, engine, delta);
    
          console.log("Something cool!");
       }
    });
    
    var myActor = new MyActor(100, 100, 100, 100, Color.Azure);
    

    In TypeScript, you only need to use the extends syntax, you do not need to use this method of extension.

    Parameters

    • methods: any

      A JSON object contain any methods/properties you want to extend

    Returns any

Object literals

capturePointer

capturePointer: object

Configuration for CapturePointer trait

captureMoveEvents

captureMoveEvents: boolean = false