// How to move images around the screen using TweenJS
// Add support to EaselJS to control the speed the image moves across the canvas.
// Pixels per second the object will move along the x and y axis
DisplayObject.prototype.setPPS = function(x, y) {
this.vX = Math.round(x / Ticker.getFPS());
this.vY = Math.round(y / Ticker.getFPS());
this.ppmsX = x / 1000;
this.ppmsY = y / 1000;
};
// Calculate the time in milliseconds required to move from the current
// position to the specified point using the assigned velocity (pixels/second)
DisplayObject.prototype.travelTime = function(x, y) {
var distX = Math.abs(x - this.x);
var distY = Math.abs(y - this.y);
var duration = Math.max(distX / this.ppmsX, distY / this.ppmsY);
return duration;
};
// Create EaselJS Stage with canvas
var stage = new Stage($('canvas')[0]);
// Create the sprite sheet
var spritesheet = new SpriteSheet({
images: ['https://s3.amazonaws.com/dxparker/blog/zolo/walking.png'],
frames: {width: 200, height: 200},
animations: {
stand_right: 0,
walk_right: [0, 3, /*loop*/ true], // 4 frame walking sequence
stand_left: 4,
walk_left: [4, 7, true]
}
});
// Create the bitmap animation from the spritesheet
// Add properties for width, height, and direction (these are not in Easel)
// and specify the travel velocity in pixels per second.
var player = new BitmapAnimation(spritesheet);
player.width = 200;
player.height = 200;
player.direction = 'right';
player.setPPS(175, 125);
player.gotoAndStop('stand_' + player.direction);
// Add click listener to trigger animation
stage.onMouseDown = function(event) {
// Where is the player going?
var destination = {
x: event.stageX - (player.width / 2),
y: event.stageY - (player.height / 2)
};
// How long should it take?
var duration = player.travelTime(destination.x, destination.y);
// Which way should the player face?
player.direction =
event.stageX < player.x + (player.width / 2) ? 'left' : 'right';
// Start the animation, this doesn't change the bitmaps location
// on the screen, it just cycles through the images in place
player.gotoAndPlay('walk_' + player.direction);
// Move the player across the screen
Tween.get(player, {override: true})
.to(destination, duration)
// Manage what happens when the player reaches the destination
.call(function() { player.gotoAndStop('stand_' + player.direction); });
};
// Display container on screen
stage.addChild(player);
// Set the stage refresh rate
Ticker.setFPS(12);
// IMPORTANT: Remember to register the stage with the Ticker
// or you'll be staring at an empty canvas
Ticker.addListener(stage);
<!--
easeljs, tweenjs, and jquery scripts have been included
using the framework and resources options of jsfiddle
-->
<canvas width="550" height="250"></canvas>
<p>Click on the canvas to move the player around the screen.</p>
canvas {
background-color: #ccd;
margin-bottom: 10px;
}
body {
font: normal normal 14px Arial, Tahoma, Helvetica, FreeSans, sans-serif;
}
External resources loaded into this fiddle: