Movimentando objeto pelo teclado
31/07/2009 at 13:24 Thiago Araújo Publicar um comentário
Crie um novo arquivo do flash e dentro dele faça um movieclip qualquer. Exemplo:

Coloque a linkage do movieclip de “Objeto” e o nome da classe principal do fla de “Movimento”.

Após salvar o arquivo, crie mais duas classes “Objeto” e “Controle”:
package
{
import flash.display.MovieClip;
public class Objeto extends MovieClip
{
public var vx:Number;
public var vy:Number;
public var ax:Number;
public var ay:Number;
public function Objeto()
{
this.ax = 0;
this.ay = 0;
this.vx = 0;
this.vy = 0;
}
}
}
A classe objeto serve de interface entre o controlador de teclado (a classe Controle) e o objeto do palco “bolaMc”.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Controle extends Sprite
{
private var target:Objeto;
public function Controle(_target:Objeto)
{
this.target = _target;
}
public function initialize():void
{
this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
}
private function onEnterFrame(evt:Event):void
{
this.target.vx += this.target.ax;
this.target.vy += this.target.ay;
this.target.x += this.target.vx;
this.target.y += this.target.vy;
}
public function onKeydown(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
this.target.ax = - 0.1;
}else if(e.keyCode == Keyboard.RIGHT)
{
this.target.ax = 0.1;
}else if(e.keyCode == Keyboard.UP){
this.target.ay = -0.1
}else if(e.keyCode == Keyboard.DOWN){
this.target.ay = 0.1;
}
}
public function onKeyup(e:KeyboardEvent):void{
this.target.ax = 0;
this.target.ay = 0;
}
}
}
Agora vamos implementar a classe “Movimento”:
package
{
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
public class Movimento extends Sprite
{
private var teclado:Controle;
private var objBola:Objeto;
public function Movimento()
{
init();
}
private function init():void
{
this.objBola = new Objeto();
this.teclado = new Controle(this.objBola);
stage.addEventListener(KeyboardEvent.KEY_DOWN,this.teclado.onKeydown);
stage.addEventListener(KeyboardEvent.KEY_UP,this.teclado.onKeyup);
this.addChild(this.objBola);
this.objBola.x = stage.stageWidth / 2;
this.objBola.y = stage.stageHeight / 2;
this.teclado.initialize();
}
}
}
Pronto! Como foram feitas as classes e a organização foi só para o teste e exemplo. Uma boa organização pode abrir espaço para colocar gravidade e efeitos físicos.
Faça o download dos arquivos utilizados.
Entry filed under: AS3. Tags: .
Trackback este artigo | Subscribe to the comments via RSS Feed