Skip to content

Instantly share code, notes, and snippets.

@peterhoang
Created July 16, 2013 13:18
Show Gist options
  • Save peterhoang/6008605 to your computer and use it in GitHub Desktop.
Save peterhoang/6008605 to your computer and use it in GitHub Desktop.
package utils
{
import net.flashpunk.FP;
import entities.Player;
public class Camera
{
private var cameraSpeed:Number;
/**
* Camera following information.
*/
public const FOLLOW_TRAIL:Number = 50;
public const FOLLOW_RATE:Number = .9;
public function Camera(cameraSpeed:int = 200)
{
this.cameraSpeed = cameraSpeed;
}
public function adjustToPlayer(mapWidth:int, mapHeight:int, player:Player):void
{
if (player == null) return;
// Find the coordinates to that would center the player
var newCameraX:int = (player.x + player.width / 2) - FP.width / 2;
var newCameraY:int = (player.y + player.height / 2) - FP.height / 2;
// check if they go beyond map boundaries
if (newCameraX < 0) newCameraX = 0;
else if (newCameraX + FP.width > mapWidth) newCameraX = mapWidth - FP.width;
if (newCameraY < 0) newCameraY = 0
else if (newCameraY + FP.height > mapHeight) newCameraY = mapHeight - FP.height;
// set the camera coordinates
FP.camera.x = newCameraX;
FP.camera.y = newCameraY;
}
public function followPlayer(mapWidth:int, mapHeight:int, player:Player):void
{
var targetX:Number = player.x - FP.width / 2;
var targetY:Number = player.y - FP.height / 2;
// make camera follow the player
FP.point.x = FP.camera.x - targetX;
FP.point.y = FP.camera.y - targetY;
var dist:Number = FP.point.length;
if (dist > FOLLOW_TRAIL) dist = FOLLOW_TRAIL;
FP.point.normalize(dist * FOLLOW_RATE);
FP.camera.x = int(targetX + FP.point.x);
FP.camera.y = int(targetY + FP.point.y);
// keep camera in room bounds
FP.camera.x = FP.clamp(FP.camera.x, 0, mapWidth - FP.width);
FP.camera.y = FP.clamp(FP.camera.y, 0, mapHeight - FP.height);
//FP.camera.x -= (FP.camera.x - (player.x - FP.halfWidth)) * FP.elapsed * cameraSpeed;
//FP.camera.y -= (FP.camera.y - ((player.y + 50) - FP.halfHeight)) * FP.elapsed * cameraSpeed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment