-
-
Save zachwlewis/6009817 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
var cameraDelta:Point = new Point(); | |
cameraDelta.x = FP.camera.x - targetX; | |
cameraDelta.y = FP.camera.y - targetY; | |
var dist:Number = cameraDelta.length; | |
dist = Math.min(dist, FOLLOW_TRAIL); | |
cameraDelta.normalize(dist * FOLLOW_RATE); | |
FP.camera.x = int(targetX + cameraDelta.x); | |
FP.camera.y = int(targetY + cameraDelta.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