Comunidad de diseño web y desarrollo en internet online

HitTest en AS3

Citar            
MensajeEscrito el 08 Abr 2011 03:26 pm
He estado buscando informacion sobre este tema en AS3, encontré este tuto http://www.esedeerre.com/ejemplo/4/141/actionscript-30-colisiones-a-nivel-de-pixel donde hay una clase ya lista para su uso y detecta la colision no en cuadrado sino según la forma del MC, ya lo probé y me funciona, pero quisiera no usar una clase creada sino comprender como funciona el HitTest en AS3, alguien que tenga experiencia en colisiones en AS3 que me pueda ayudar?

Por el_chejin

Claber

725 de clabLevel

4 tutoriales

Genero:Masculino  

En mi nave Espacial

firefox
Citar            
MensajeEscrito el 08 Abr 2011 04:26 pm
estoy utilizando esta clase en un laberinto que cree, ya me funciona el movimiento del laberinto por medio de KEY_DOWN y una serie de variables de los mc con trigonometría, pero al aplicar la clase de colisión ya no me reconoce el teclado y me da este error: Scene 1, Layer 'Actions', Frame 1, Line 40 1046: Type was not found or was not a compile-time constant: KeyboardEvent.

pongo el codigo usado:

en mi fla tengo este codigo (utilicé los snippets para detectar cuando se presionan las teclas de flechas)

Código ActionScript :

//constante estática para hallar radianes en 1º
var g_r:Number = Math.PI/180;

// declaro la posición del pivote de cuadro, punto donde va a girar el laberinto
cuadro.x = 275;
cuadro.y = 200;

var giro:Number = 0; // angulo del giro del laberinto01_mc
var distancia:Number = 1; // cantidad de pixels que se moverá el leberinto no importando hacia que angulo
//var caida_x:Number = 0; // cuanto se movera en x para continuar el movimiento vertical
//var caida_y:Number = 0; // cuanto se movera en y para continuar el movimiento vertical

var caida_x:Number = distancia*Math.sin(giro * g_r);
var caida_y:Number = distancia*Math.cos(giro * g_r);

/*añadimos un listener para crear una funcion que se active cada frame
lo que en as2 era onEnterFrame*/
addEventListener(Event.ENTER_FRAME,mov_y);
function mov_y(event:Event):void 
{
   var caida_x:Number = distancia*Math.sin(giro * g_r);
   var caida_y:Number = distancia*Math.cos(giro * g_r);
   //ponemos aca todo lo que qurramos que haga cada vez que entre el frame
   cuadro.laberinto.y = cuadro.laberinto.y+caida_y;
   cuadro.laberinto.x = cuadro.laberinto.x+caida_x;
   giro = cuadro.rotation;
   trace("onEnterFrame rotacion: "+giro+" movimiento X: "+caida_x+" movimiento Y: "+caida_y);
}

/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.

Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/

stage.addEventListener(KeyboardEvent.KEY_DOWN,fl_PressKeyToMove);

function fl_PressKeyToMove(event:KeyboardEvent):void
{
   switch (event.keyCode)
   {
      /*case Keyboard.UP:
      {
         
         break;
      }
      case Keyboard.DOWN:
      {
         
         break;
      }*/
      case Keyboard.LEFT:
      {
         cuadro.rotation += 2;
         brujula_mc.rotation = cuadro.rotation;
         break;
      }
      case Keyboard.RIGHT:
      {
         cuadro.rotation -= 2;
         brujula_mc.rotation = cuadro.rotation;
         break;
      }
   }
}


y en la clase de colision va este codigo:

Código ActionScript :

package{
   
   import flash.geom.*;
   import HitTest;
   import flash.display.MovieClip;
   import flash.display.Shape;
   import flash.events.Event;
   import flash.text.TextField;
   


   
   public class Colisiones extends MovieClip{
      
      var dibujo = new Shape();
      
   
      
      public function Colisiones():void{
         addChild(dibujo);
         addEventListener(Event.ENTER_FRAME,probar);
      }
      
      public function probar(e:Event):void{
         
         //Obtiene un Rectángulo con el área de choque entre Item1_mc e Item2_mc
         var rect:Rectangle = HitTest.complexIntersectionRectangle(flecha_mc,cuadro.laberinto);
         
         //Dibuja el rectángulo obtenido
         dibujo.graphics.clear();
         dibujo.graphics.beginFill(0xff00ff,.6);
         dibujo.graphics.drawRect(rect.x,rect.y,rect.width,rect.height);
         
         
      }

   }
}


y por ultimo la clase HitTest:

Código ActionScript :

package 
{
        
        import flash.display.BitmapData;
        import flash.display.BlendMode;
        import flash.display.DisplayObject;
        import flash.display.Sprite;
        
        import flash.geom.ColorTransform;
        import flash.geom.Matrix;
        import flash.geom.Point;
        import flash.geom.Rectangle;
        
        public class HitTest
        {
 
                public static function complexHitTestObject( target1:DisplayObject, target2:DisplayObject,  accurracy:Number = 1 ):Boolean
                {
                        return complexIntersectionRectangle( target1, target2, accurracy ).width != 0;
                }
                
                public static function intersectionRectangle( target1:DisplayObject, target2:DisplayObject ):Rectangle
                {
                        // If either of the items don't have a reference to stage, then they are not in a display list
                        // or if a simple hitTestObject is false, they cannot be intersecting.
                        if( !target1.root || !target2.root || !target1.hitTestObject( target2 ) ) return new Rectangle();
                        
                        // Get the bounds of each DisplayObject.
                        var bounds1:Rectangle = target1.getBounds( target1.root );
                        var bounds2:Rectangle = target2.getBounds( target2.root );
                        
                        // Determine test area boundaries.
                        var intersection:Rectangle = new Rectangle();
                        intersection.x   = Math.max( bounds1.x, bounds2.x );
                        intersection.y    = Math.max( bounds1.y, bounds2.y );
                        intersection.width      = Math.min( ( bounds1.x + bounds1.width ) - intersection.x, ( bounds2.x + bounds2.width ) - intersection.x );
                        intersection.height = Math.min( ( bounds1.y + bounds1.height ) - intersection.y, ( bounds2.y + bounds2.height ) - intersection.y );
                
                        return intersection;
                }
                
                public static function complexIntersectionRectangle( target1:DisplayObject, target2:DisplayObject, accurracy:Number = 1 ):Rectangle
                {                     
                        if( accurracy <= 0 ) throw new Error( "ArgumentError: Error #5001: Invalid value for accurracy", 5001 );
                        
                        // If a simple hitTestObject is false, they cannot be intersecting.
                        if( !target1.hitTestObject( target2 ) ) return new Rectangle();
                        
                        var hitRectangle:Rectangle = intersectionRectangle( target1, target2 );
                        // If their boundaries are no interesecting, they cannot be intersecting.
                        if( hitRectangle.width * accurracy <1 || hitRectangle.height * accurracy <1 ) return new Rectangle();
                        
                        var bitmapData:BitmapData = new BitmapData( hitRectangle.width * accurracy, hitRectangle.height * accurracy, false, 0x000000 ); 
 
                        // Draw the first target.
                        bitmapData.draw( target1, HitTest.getDrawMatrix( target1, hitRectangle, accurracy ), new ColorTransform( 1, 1, 1, 1, 255, -255, -255, 255 ) );
                        // Overlay the second target.
                        bitmapData.draw( target2, HitTest.getDrawMatrix( target2, hitRectangle, accurracy ), new ColorTransform( 1, 1, 1, 1, 255, 255, 255, 255 ), BlendMode.DIFFERENCE );
                        
                        // Find the intersection.
                        var intersection:Rectangle = bitmapData.getColorBoundsRect( 0xFFFFFFFF,0xFF00FFFF );
                        
                        bitmapData.dispose();
                        
                        // Alter width and positions to compensate for accurracy
                        if( accurracy != 1 )
                        {
                                intersection.x /= accurracy;
                                intersection.y /= accurracy;
                                intersection.width /= accurracy;
                                intersection.height /= accurracy;
                        }
                        
                        intersection.x += hitRectangle.x;
                        intersection.y += hitRectangle.y;
                        
                        return intersection;
                }
                
                
                protected static function getDrawMatrix( target:DisplayObject, hitRectangle:Rectangle, accurracy:Number ):Matrix
                {
                        var localToGlobal:Point;;
                        var matrix:Matrix;
                        
                        var rootConcatenatedMatrix:Matrix = target.root.transform.concatenatedMatrix;
                        
                        localToGlobal = target.localToGlobal( new Point( ) );
                        matrix = target.transform.concatenatedMatrix;
                        matrix.tx = localToGlobal.x - hitRectangle.x;
                        matrix.ty = localToGlobal.y - hitRectangle.y;
                        
                        matrix.a = matrix.a / rootConcatenatedMatrix.a;
                        matrix.d = matrix.d / rootConcatenatedMatrix.d;
                        if( accurracy != 1 ) matrix.scale( accurracy, accurracy );
 
                        return matrix;
                }
 
        }
 
}


total que si le aplico la clase a mi laberinto ya no detecta las teclas, si borro el codigo de KEY_DOWN me funciona HitTest perfectamente, y si por el contrario no aplico la clase Colisiones me funciona el movimiento de las teclas sin ningún problema, alguien puede ayudarme?

Por el_chejin

Claber

725 de clabLevel

4 tutoriales

Genero:Masculino  

En mi nave Espacial

firefox

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.