Skip to content

Instantly share code, notes, and snippets.

@eonarheim
Last active August 29, 2015 14:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eonarheim/2a13acf699500eaefa61 to your computer and use it in GitHub Desktop.
Save eonarheim/2a13acf699500eaefa61 to your computer and use it in GitHub Desktop.
Elastic camera code
var cameraVel = new ex.Vector(0, 0);
engine.on('update', function(){
// Calculate the center of mass between the players on screen
// this is sort of a naive way to do co-op camera but works for now
var playerAvg = players.reduce(function(last, current, i){
return new ex.Vector(last.x + current.x, last.y + current.y);
}, ex.Vector.Zero.clone()).scale(1/players.length);
// Grab the current focus of the camper
var focus = engine.currentScene.camera.getFocus().toVector();
// Grab the "destination" position, in the spring equation the displacement location
var position = new ex.Vector(playerAvg.x, playerAvg.y);
// Calculate the strech vector, using the spring equation
// F = kX
// https://en.wikipedia.org/wiki/Hooke's_law
// Apply to the current camera velocity
var stretch = position.minus(focus).scale(Config.CameraElasticity);
cameraVel = cameraVel.plus(stretch);
// Calculate the friction (-1 to apply a force in the opposition of motion)
// Apply to the current camera velocity
var friction = cameraVel.scale(-1).scale(Config.CameraFriction);
cameraVel = cameraVel.plus(friction);
// Update position by velocity deltas
focus = focus.plus(cameraVel);
// Set new position on camera
engine.currentScene.camera.setFocus(focus.x, focus.y);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment