In this tutorial, we are going to make a 2D camera (moves along x and y axises).
- First make your backround (Better if it's larger than stage) and give it an instance name "Background"
- According to the press of arrow keys camera gonna move.
Let's get started...
<code>
import
flash.geom.Rectangle;
import
flash.events.Event;
import
flash.events.KeyboardEvent;
var
myCam:Rectangle = new
Rectangle(0,0,stage.stageWidth,stage.stageHeight);
/* creating a rectangle
which act as a camera to a movieClip which is our Background
parameters
for new rectangle
Rectangle x position = 0
Rectangle y position = 0
Rectangle width = stage width
Rectangle height = stage
height
*/
//creating a function in
order to move the camera (i.e. our rectangle) using arrow keys
function
moveCamera(e:KeyboardEvent):void{
if(e.keyCode==Keyboard.UP){
myCam.y-=2;
}
if(e.keyCode==Keyboard.DOWN){
myCam.y+=2;
}
if(e.keyCode==Keyboard.LEFT){
myCam.x-=2;
}
if(e.keyCode==Keyboard.RIGHT){
myCam.x+=2;
}
}
//calling the camera move
function to the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN,moveCamera);
function
updateView(e:Event):void{
Background.scrollRect = myCam;
}
/*
assigning viewing area of the Background to the
rectangle(our cam)
so, we can see the area
bounded to the rectangle more like a mask
but you can't use .mask
instead of scrollRect :D
note that myCam position,
scale parameters generates in, as myCam
is
inside Background
*/
stage.addEventListener(Event.ENTER_FRAME,
updateView);
/* calling the updateView function on stage. stage gets updated
according to the frame
rate and the function
updateView
*/
</code>
- Note : scrollRect animations are not well smooth.
- Light Blue colour texts represent variables and functions
- Green texts represent comments