Follow cam prototype
Prototype of a camera following a player
/**
* Copyright mutantleg ( http://wonderfl.net/user/mutantleg )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/ibab
*/
package {
import flash.events.Event;
import flash.display.Sprite;
public class FlashTest extends Sprite {
public var myCam:Cam;
public var act:Actor;
public function FlashTest() {
// write as3 code here..
myCam = new Cam();
addChild(myCam);
myCam.x = 200;
myCam.y = 200;
act = new Actor();
addChild(act);
stage.addEventListener(Event.ENTER_FRAME, onEnter);
}//ctor
public function onEnter(e:Event):void
{
myCam.lookAt(mouseX, mouseY);
myCam.follow(mouseX, mouseY);
act.x = mouseX;
act.y = mouseY;
act.rotation = myCam.rotation;
}//onenter
}//classend
}
import flash.text.TextField;
import flash.display.Sprite;
internal class Actor extends Sprite
{
public function Actor()
{
graphics.clear();
graphics.lineStyle(2,0x0000FF);
graphics.drawCircle(0,0, 16);
graphics.moveTo(0,0);
graphics.lineTo(16,0);
}//ctor
}//classend
internal class Cam extends Sprite
{
public var deb:TextField;
public function Cam()
{
graphics.clear();
graphics.lineStyle(2,0);
graphics.drawCircle(0,0, 16);
graphics.moveTo(0,0);
graphics.lineTo(16,0);
deb = new TextField();
// addChild(deb);
}//ctor
public function lookAt(kx:Number, ky:Number):void
{
var a:Number;
var dx:Number;
var dy:Number;
dx = kx - x;
dy = ky - y;
a = Math.atan2(dy,dx) * 180/3.1415;
this.rotation= a;
//if (isNaN(a)) { deb.text ="NaN"; return;}
deb.text= "Ang: "+a;
}//lookat
public function follow(kx:Number, ky:Number, rest:Number = 100):void
{
var dx:Number;
var dy:Number;
var nx:Number;
var ny:Number;
var mag:Number;
dx = kx - x;
dy = ky - y;
mag = Math.sqrt(dx*dx + dy*dy);
if (mag == 0) { mag = 0.000000001;}
nx = dx / mag;
ny = dy / mag;
x += nx * 0.1 * (mag - rest);
y += ny * 0.1 * (mag - rest);
}//follow
}//classend