Inicio > JigLibFlash > Tutorial JigLibFlash – How to create basic physics 3d scene.

Tutorial JigLibFlash – How to create basic physics 3d scene.

viernes, 24 de abril de 2009 miguelMoraleda Dejar un comentario Ir a comentarios

Jiglibflash is a open source 3D physics engine with a MIT license (ported from c++ Jiglib). Official Web

Para empezar voy a detallar un poco los conceptos para los que no estan muy interiorisados con el tema. JigLibFlash es un motor de fisica 3D. Esto NO! quiere decir que sea un motor de 3D. JigLib es solo la parte que simula la fisica dentro de una scena3D. Es por esto que primero que todo deben tener un motor de 3D, tal como Papervision3D, Away3D, Sandy, etc. Para este ejemplo voy a utilizar Papersivion3D que es el motor que vengo usando hace ya un tiempo.

Lo primero es configurar la parte 3D, en papervision3D se necesita un viewport, una camara, un render engine y una scena. Para hacer esto facil vamos a extender de la clase BasicView que ya implementa todo este sistema para poder renderear en 3d. La idea de esto es no tener que explicar muchas cosas que son netamente de pv3d y ver directamente lo que a JigLib refiere.
Bueno nuestra clase deberia verse asi. La funcion startRendering() hace que comienze a renderear pv3d, esto hace que la funcion onRenderTick sea llamada en cada frame.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package
{
	import flash.events.Event;
	import org.papervision3d.view.BasicView;
 
	public class Main extends BasicView
	{
		public function Main()
		{
			super(0, 0, true);
 
			startRendering();
		}
 
		override protected function onRenderTick(event:Event = null):void
		{
			super.onRenderTick(event);
		}
 
	}
 
}

Con esa base ya podemos comenzar a integrar lo necesario para simular la fisica. JibLibFlash trae unas classes plugin para interactuar con cada motor 3d especifico. Dentro de la libreria van a encontrar una clase que se llama Papervision3DPhysics, esta clase encapsula todo lo necesario para que JigLib funcione, ademas de brindarnos algunas funciones para crear objetos de manera sencilla.
Continuando con el ejemplo, vamos agregar una instancia de esta clase.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package
{
	import flash.events.Event;
	import jiglib.plugin.papervision3d.Papervision3DPhysics;
	import org.papervision3d.view.BasicView;
 
	public class Main extends BasicView
	{
		private var _physics:Papervision3DPhysics;
 
		public function Main()
		{
			super(0, 0, true);
 
			initPhysics();
			startRendering();
		}
 
		private function initPhysics():void
		{
			_physics = new Papervision3DPhysics(scene, 7);
		}
 
		override protected function onRenderTick(event:Event = null):void
		{
			_physics.step();
			super.onRenderTick(event);
		}
	}
}

De aca solo dos lineas a destacar (no se para que copio tanto codigo), la creacion de la instancia recibe en el constructor la scena(Scene3d de pv3d) y la velocidad, la velocidad es una constante para toda la libreria. Y la otra linea es fundamental _physics.step(); que debe hacerse en cada frame para ir actualizando todo, es por esto que esta dentro de la funcion onRenderTick y antes del super para que primero actualize todos los valores relacionados a la fisica y luego renderee los objetos.

Con esas pocas lineas tenemos lo necesario para el ejemplo. Ahora solo resta agregar objetos a la scena, para esto la clase Papervision3DPhysics tiene algunas funciones para hacer esto de manera sencilla.

Crear Suelo

1
2
3
4
5
private function createGround():void
{
	var mat:WireframeMaterial = new WireframeMaterial(0xCCCCCC);
	var ground:RigidBody = _physics.createGround(mat, 1000, 0);
}

Crear Cubos

1
2
3
4
5
6
7
8
9
10
private function createBox():void
{
	var materials:MaterialsList = new MaterialsList();
	materials.addMaterial(new WireframeMaterial(0xFF4444), "all");
	var box:RigidBody;
	for (var i:int = 1; i < 5; i++) {
		box = _physics.createCube(materials, 100, 100, 100, 3, 3, 3);
		box.y = 300 * i;
	}
}

Crear Esferas

1
2
3
4
5
6
7
8
9
private function createSphere():void
{
	var ball:RigidBody;
	for (var i:int = 1; i < 4; i++) {
		ball = _physics.createSphere(new WireframeMaterial(0xFF44FF), 50);
		ball.z = -200;
		ball.y = 300 * i;
	}
}

Estas son las 3 posibilidades que nos ofrece la clase Papervision3DPhysics. Tambien es posible crear los objetos de manera mas abstracta pero no voy a tocar ese tema por ahora. Asi concluyo con este tutorial, espero que a alguien le sea de ayuda.

VER EJEMPLO
DESCARGAR ARCHIVOS DEL TUTORIAL

Categories: JigLibFlash Tags:
  1. Rodolfo Lopez Navarrate
    miércoles, 26 de agosto de 2009 a las 12:20 | #1

    Hola muchas grcias ya estuve jugando un buen rato con esto para unproyecto de la empresa donde trabajo con este gran ejemplo , me podrias pasar tu mail o blog , saludos , va bye , y muchas gracias de nuevo

  2. domingo, 6 de diciembre de 2009 a las 05:27 | #2

    Excellent tyvm just what I needed! Spot on.

  3. miércoles, 27 de enero de 2010 a las 14:01 | #3

    Great job man!!! Thanks

  4. harv
    miércoles, 3 de febrero de 2010 a las 09:06 | #4

    i cant open the fla file….

    any ideas?

    also my main.as is showing errors like this:

    1084: Syntax error: expecting identifier before lessthan.

  5. miércoles, 3 de febrero de 2010 a las 09:23 | #5

    Hi harv,

    The fla file is saved for Flash CS4, probably you are using a older version. I just downloaded the example and compile it without errors. I’m sure the code have not error. Try to download the example again and try :)

  6. harv
    miércoles, 3 de febrero de 2010 a las 09:43 | #6

    thanks for the reply Miguil,
    yeah i was using cs3… so does this mean its impossible?
    also in general trying to use jiglibflash i keep getting errors saying that vector and vector3d are not compile time constants… is this due to flash cs3 too?@miguelMoraleda

  7. miércoles, 3 de febrero de 2010 a las 09:58 | #7

    Hi harv,

    Could be possible if I send you the fla file saved for CS3, BUUUTT, you can create a new FLA file.. my file only contains the document class definition. The if you create a new one and the Main in the document class is enough to the example works.. About the vector class, you get this error becouse this classes only exist for FP10.. you need to use the JigLibFlash for FP9, this version don’t use the vector classes. :)

  8. harv
    miércoles, 3 de febrero de 2010 a las 10:06 | #8

    @miguelMoraleda
    Thanks so much. thats great. i’ll let you know how it turns out!

  9. ncuz
    martes, 13 de abril de 2010 a las 10:33 | #9

    Hai miguel, it`s a good.. I love it
    can you help me? I can`t find the JiglibFlash library.. =(

  10. martes, 13 de abril de 2010 a las 10:38 | #10

    ncuz: You have to use svn to get the library. Check out this links to the google code project.

    You can find the sourcecode at http://code.google.com/p/jiglibflash/.
    The SVN is located at: http://code.google.com/p/jiglibflash/source/checkout.

*

Spam Protection by WP-SpamFree

Get Adobe Flash playerPlugin by wpburn.com wordpress themes