CarDrive

交通工具模拟
See Demo
Code:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package  
{
    import flash.display.*;
    import flash.events.*;
    import flash.ui.Keyboard;
    import flash.geom.Vector3D;
   
    import org.papervision3d.cameras.CameraType;
    import org.papervision3d.materials.*;
    import org.papervision3d.materials.utils.MaterialsList;
    import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
    import org.papervision3d.objects.parsers.*;
    import org.papervision3d.objects.DisplayObject3D;
    import org.papervision3d.lights.PointLight3D;
    import org.papervision3d.events.FileLoadEvent;
    import org.papervision3d.objects.parsers.Collada;
    import org.papervision3d.view.BasicView;
    import org.papervision3d.view.stats.StatsView;
    import org.papervision3d.view.layer.ViewportLayer;
    import org.papervision3d.view.layer.util.ViewportLayerSortMode;

    import jiglib.math.*;
    import jiglib.physics.*;
    import jiglib.vehicles.JCar;
    import jiglib.vehicles.JWheel;
    import jiglib.plugin.papervision3d.*;

    [SWF(width="800", height="600", backgroundColor="#ffffff", frameRate="60")]
    public class CarDrive extends BasicView
    {
        private var mylight:PointLight3D;
       
        private var carBody:JCar;
        private var carSkin:Collada;
        private var steerFR :DisplayObject3D;
        private var steerFL :DisplayObject3D;
        private var wheelFR :DisplayObject3D;
        private var wheelFL :DisplayObject3D;
        private var wheelBR :DisplayObject3D;
        private var wheelBL :DisplayObject3D;
        private var vplObjects:ViewportLayer;
       
        private var physics:Papervision3DPhysics;
       
        public function CarDrive()
        {
            super(800, 600, true, true, CameraType.TARGET);
            stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler );
            stage.addEventListener( KeyboardEvent.KEY_UP, keyUpHandler );
           
            init3D();
        }
       
        private function init3D():void
        {
            physics = new Papervision3DPhysics(scene, 6);
            viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;
             
            mylight = new PointLight3D(true, true);
            mylight.y = 300;
            mylight.z = -400;
             
            var shadeMateria:FlatShadeMaterial = new FlatShadeMaterial(mylight, 0x77ee77);
            var ground:RigidBody = physics.createGround(shadeMateria, 500, 0);
            viewport.getChildLayer(physics.getMesh(ground)).layerIndex = 0;
           
           
            //init car skin
            shadeMateria = new FlatShadeMaterial(mylight,0xeeeeff);
            var materiaList:MaterialsList = new MaterialsList();
            materiaList.addMaterial(shadeMateria,"all");
            carSkin = new Collada("res/car.DAE", materiaList, 0.01);
            carSkin.addEventListener(FileLoadEvent.LOAD_COMPLETE,onCarLoaded);
             
            camera.y = mylight.y;
            camera.z = mylight.z;
             
            var stats:StatsView = new StatsView(renderer);
            addChild(stats);
        }
       
        private function onCarLoaded(e:FileLoadEvent):void
        {
            scene.addChild(carSkin);
             
            //init car physics
            carBody = new JCar(new Pv3dMesh(carSkin));
            carBody.setCar(40,5,500);
            carBody.chassis.moveTo(new Vector3D( 0, 100, 0));
            carBody.chassis.rotationY = -90;
            carBody.chassis.mass = 9;
            carBody.chassis.sideLengths = new Vector3D(40, 20, 90);
            physics.addBody(carBody.chassis);
             
            carBody.setupWheel("WheelFL", new Vector3D( -20, -10, 25), 1.2, 1.2, 3, 8, 0.4, 0.6, 2);
            carBody.setupWheel("WheelFR", new Vector3D(20, -10, 25), 1.2, 1.2, 3, 8, 0.4, 0.6, 2);
            carBody.setupWheel("WheelBL", new Vector3D( -20, -10, -25), 1.2, 1.2, 3, 8, 0.4, 0.6, 2);
            carBody.setupWheel("WheelBR", new Vector3D(20, -10, -25), 1.2, 1.2, 3, 8, 0.4, 0.6, 2);
             
            var shadeMateria:FlatShadeMaterial = new FlatShadeMaterial(mylight, 0x777777);
            steerFL = carSkin.getChildByName( "WheelFL", true );
            steerFR = carSkin.getChildByName( "WheelFR", true );
            wheelFL = carSkin.getChildByName( "WheelFL_PIVOT", true );
            wheelFL.material = shadeMateria;
            wheelFR = carSkin.getChildByName( "WheelFR_PIVOT", true );
            wheelFR.material = shadeMateria;
            wheelBL = carSkin.getChildByName( "WheelBL", true );
            wheelBL.material = shadeMateria;
            wheelBR = carSkin.getChildByName( "WheelBR", true );
            wheelBR.material = shadeMateria;
             
            var vplCar:ViewportLayer = viewport.getChildLayer(carSkin.getChildByName("Chassis",true));
            vplCar.addDisplayObject3D(wheelFR);
            vplCar.addDisplayObject3D(wheelFL);
            vplCar.addDisplayObject3D(wheelBR);
            vplCar.addDisplayObject3D(wheelBL);
            vplCar.layerIndex = 2;
           
            shadeMateria = new FlatShadeMaterial(mylight, 0x77ee77);
            var materiaList :MaterialsList = new MaterialsList();
            materiaList.addMaterial(shadeMateria, "all");
            var ramp1:RigidBody = physics.createCube(materiaList, 400, 200, 10);
            ramp1.movable = false;
            ramp1.moveTo(new Vector3D(0, 33, 250));
            ramp1.rotationX = -20;
            vplCar.addDisplayObject3D(physics.getMesh(ramp1));
           
            var ramp2:RigidBody = physics.createCube(materiaList, 400, 200, 10);
            ramp2.movable = false;
            ramp2.moveTo(new Vector3D(0, 33, 440));
            ramp2.rotationX = 20;
            vplCar.addDisplayObject3D(physics.getMesh(ramp2));
           
            shadeMateria = new FlatShadeMaterial(mylight, 0xeeee00);
            materiaList = new MaterialsList();
            materiaList.addMaterial(shadeMateria, "all");
            var boxBody:Array = new Array();
            for (var i:int = 0; i < 2; i++)
            {
                boxBody[i] = physics.createCube(materiaList, 40, 40, 40);
                boxBody[i].moveTo(new Vector3D(-100, 30 + (50 * i + 50), 0));
                vplCar.addDisplayObject3D(boxBody[i].skin.mesh);
            }
           
            startRendering();
        }
       
        private function keyDownHandler(event :KeyboardEvent):void
        {
            switch(event.keyCode)
            {
                case Keyboard.UP:
                    carBody.setAccelerate(1);
                    break;
                case Keyboard.DOWN:
                    carBody.setAccelerate(-1);
                    break;
                case Keyboard.LEFT:
                    carBody.setSteer(["WheelFL", "WheelFR"], -1);
                    break;
                case Keyboard.RIGHT:
                    carBody.setSteer(["WheelFL", "WheelFR"], 1);
                    break;
                case Keyboard.SPACE:
                    carBody.setHBrake(1);
                    break;
            }
        }


        private function keyUpHandler(event:KeyboardEvent):void
        {
            switch(event.keyCode)
            {
                case Keyboard.UP:
                    carBody.setAccelerate(0);
                    break;
                   
                case Keyboard.DOWN:
                    carBody.setAccelerate(0);
                    break;
                   
                case Keyboard.LEFT:
                    carBody.setSteer(["WheelFL", "WheelFR"], 0);
                    break;
                   
                case Keyboard.RIGHT:
                    carBody.setSteer(["WheelFL", "WheelFR"], 0);
                    break;
                case Keyboard.SPACE:
                   carBody.setHBrake(0);
            }
        }
         
        private function updateWheelSkin():void
        {
            steerFL.rotationY = carBody.wheels["WheelFL"].getSteerAngle();
            steerFR.rotationY = carBody.wheels["WheelFR"].getSteerAngle();
           
            wheelFL.pitch(carBody.wheels["WheelFL"].getRollAngle());
            wheelFR.pitch(carBody.wheels["WheelFR"].getRollAngle());
            wheelBL.roll(carBody.wheels["WheelBL"].getRollAngle());
            wheelBR.roll(carBody.wheels["WheelBR"].getRollAngle());
           
            steerFL.y = carBody.wheels["WheelFL"].getActualPos().y;
            steerFR.y = carBody.wheels["WheelFR"].getActualPos().y;
            wheelBL.y = carBody.wheels["WheelBL"].getActualPos().y;
            wheelBR.y = carBody.wheels["WheelBR"].getActualPos().y;
        }
         
        protected override function onRenderTick(event:Event = null):void {
            //physics.step();
            physics.engine.integrate(0.12);
            updateWheelSkin();
            super.onRenderTick(event);
        }
    }
}

HingeJoint

铰链关节
See Demo
Code:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package
{
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Vector3D;

import jiglib.geometry.*;
import jiglib.math.*;
import jiglib.cof.JConfig;
import jiglib.physics.*;
import jiglib.physics.constraint.*;
import jiglib.plugin.papervision3d.*;

import org.papervision3d.cameras.CameraType;
import org.papervision3d.core.math.Number3D;
import org.papervision3d.core.math.Plane3D;
import org.papervision3d.core.utils.Mouse3D;
import org.papervision3d.events.*;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.materials.shadematerials.*;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.core.geom.renderables.Vertex3D;
import org.papervision3d.objects.primitives.*;
import org.papervision3d.view.BasicView;
import org.papervision3d.view.layer.ViewportLayer;
import org.papervision3d.view.layer.util.ViewportLayerSortMode;
import org.papervision3d.view.stats.StatsView;

[SWF(width="800", height="600", backgroundColor="#ffffff", frameRate="60")]
public class HingeJointTest extends BasicView
{
private var mylight:PointLight3D;
private var mouse3D:Mouse3D;
private var shadeMateria:FlatShadeMaterial;
private var vplObjects:ViewportLayer;

private var ground:RigidBody;
private var chainBody:Vector.;
private var chain:Vector.;

private var onDraging:Boolean = false;

private var currDragBody:RigidBody;
private var dragConstraint:JConstraintWorldPoint;
private var startMousePos:Vector3D;
private var planeToDragOn:Plane3D;

private var physics:Papervision3DPhysics;

public function HingeJointTest()
{
super(800, 600, true, true, CameraType.TARGET);

stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);

Mouse3D.enabled = true;
mouse3D = viewport.interactiveSceneManager.mouse3D;
viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;

mylight = new PointLight3D(true, true);
mylight.y = 300;
mylight.z = -400;

camera.y = mylight.y;
camera.z = mylight.z;

var stats:StatsView = new StatsView(renderer);
addChild(stats);

startRendering();

initObject();
}

private function initObject():void
{
JConfig.numContactIterations = 12;
physics = new Papervision3DPhysics(scene, 8);

shadeMateria = new FlatShadeMaterial(mylight, 0x77ee77);
var materiaList :MaterialsList = new MaterialsList();
materiaList.addMaterial(shadeMateria, "all");

ground = physics.createCube(materiaList, 500, 500, 10);
ground.movable = false;
viewport.getChildLayer(physics.getMesh(ground)).layerIndex = 1;

vplObjects = new ViewportLayer(viewport,null);
vplObjects.layerIndex = 2;
vplObjects.sortMode = ViewportLayerSortMode.Z_SORT;
viewport.containerSprite.addLayer(vplObjects);

shadeMateria = new FlatShadeMaterial(mylight, 0xeeee00);
shadeMateria.interactive = true;
materiaList = new MaterialsList();
materiaList.addMaterial(shadeMateria, "all");

chain = new Vector.();
chainBody = new Vector.();
for (var i:int = 0; i &lt; 10; i++) { chainBody[i] = physics.createCube(materiaList, 40, 20, 40); chainBody[i].maxLinVelocities = 200; chainBody[i].maxRotVelocities = 10; physics.getMesh(chainBody[i]).addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, handleMousePress); chainBody[i].moveTo(new Vector3D( 0, 130 + (45 * i + 45), 0)); if (i &gt; 0) {
//disable some collisions between adjacent pairs
chainBody[i].disableCollisions(chainBody[i - 1]);
}
vplObjects.addDisplayObject3D(physics.getMesh(chainBody[i]));
}

var pos1:Vector3D;
var pos2:Vector3D;
for (i = 1; i &lt; chainBody.length; i++ ){
//set up the hinge joints.
chain[i-1] = new HingeJoint(chainBody[i - 1], chainBody[i], Vector3D.X_AXIS, new Vector3D(0, 15, 0), 10, 50, 50, 0.1, 0.5);
}
}

private function findSkinBody(skin:DisplayObject3D):int
{
for (var i:String in PhysicsSystem.getInstance().bodys)
{
if (skin == physics.getMesh(PhysicsSystem.getInstance().bodys[i]))
{
return int(i);
}
}
return -1;
}

private function handleMousePress(event:InteractiveScene3DEvent):void
{
onDraging = true;
startMousePos = new Vector3D(mouse3D.x, mouse3D.y, mouse3D.z);
currDragBody = PhysicsSystem.getInstance().bodys[findSkinBody(event.displayObject3D)];
planeToDragOn = new Plane3D(new Number3D(0, 0, -1), new Number3D(0, 0, -startMousePos.z));

var bodyPoint:Vector3D = startMousePos.subtract(currDragBody.currentState.position);
dragConstraint = new JConstraintWorldPoint(currDragBody, bodyPoint, startMousePos);
}

private function handleMouseMove(event:MouseEvent):void
{
if (onDraging)
{
var ray:Number3D = camera.unproject(viewport.containerSprite.mouseX, viewport.containerSprite.mouseY);
ray = Number3D.add(ray, new Number3D(camera.x, camera.y, camera.z));

var cameraVertex3D:Vertex3D = new Vertex3D(camera.x, camera.y, camera.z);
var rayVertex3D:Vertex3D = new Vertex3D(ray.x, ray.y, ray.z);
var intersectPoint:Vertex3D = planeToDragOn.getIntersectionLine(cameraVertex3D, rayVertex3D);

dragConstraint.worldPosition = new Vector3D(intersectPoint.x, intersectPoint.y, intersectPoint.z);
}
}

private function handleMouseRelease(event:MouseEvent):void
{
if (onDraging)
{
onDraging = false;
dragConstraint.disableConstraint();
currDragBody.setActive();
}
}

private function resetBody():void
{
if (chainBody[0].currentState.position.y &lt; -1000)
{
for (var i:String in chainBody)
{
chainBody[i].moveTo(new Vector3D( 0, 800 + (45 * int(i) + 45), 0));
}
}
}

protected override function onRenderTick(event:Event = null):void {

//physics.step();//dynamic timeStep
physics.engine.integrate(0.2);//static timeStep
resetBody();
super.onRenderTick(event);
}
}
}

Constraints

使用约束类连接刚体
See Demo
Code:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package
{
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Vector3D;

import jiglib.geometry.*;
import jiglib.math.*;
import jiglib.cof.JConfig;
import jiglib.physics.*;
import jiglib.physics.constraint.*;
import jiglib.plugin.papervision3d.*;

import org.papervision3d.cameras.CameraType;
import org.papervision3d.core.math.Number3D;
import org.papervision3d.core.math.Plane3D;
import org.papervision3d.core.utils.Mouse3D;
import org.papervision3d.events.*;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.materials.shadematerials.*;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.core.geom.renderables.Vertex3D;
import org.papervision3d.objects.primitives.*;
import org.papervision3d.view.BasicView;
import org.papervision3d.view.layer.ViewportLayer;
import org.papervision3d.view.layer.util.ViewportLayerSortMode;
import org.papervision3d.view.stats.StatsView;

[SWF(width="800", height="600", backgroundColor="#ffffff", frameRate="60")]
public class Constraints extends BasicView
{
private var mylight:PointLight3D;
private var mouse3D:Mouse3D;
private var shadeMateria:FlatShadeMaterial;
private var vplObjects:ViewportLayer;

private var ground:RigidBody;
private var chainBody1:Vector.;
private var chain1:Vector.;

private var onDraging:Boolean = false;

private var currDragBody:RigidBody;
private var dragConstraint:JConstraintWorldPoint;
private var startMousePos:Vector3D;
private var planeToDragOn:Plane3D;

private var physics:Papervision3DPhysics;

public function Constraints()
{
super(800, 600, true, true, CameraType.TARGET);

stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);

Mouse3D.enabled = true;
mouse3D = viewport.interactiveSceneManager.mouse3D;
viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;

mylight = new PointLight3D(true, true);
mylight.y = 300;
mylight.z = -400;

camera.y = mylight.y;
camera.z = mylight.z;

var stats:StatsView = new StatsView(renderer);
addChild(stats);

startRendering();

initObject();
}

private function initObject():void
{
JConfig.numContactIterations = 15;
physics = new Papervision3DPhysics(scene, 8);

shadeMateria = new FlatShadeMaterial(mylight, 0x77ee77);
var materiaList :MaterialsList = new MaterialsList();
materiaList.addMaterial(shadeMateria, "all");

ground = physics.createCube(materiaList, 500, 500, 10);
ground.y = -50;
ground.movable = false;
viewport.getChildLayer(physics.getMesh(ground)).layerIndex = 1;

vplObjects = new ViewportLayer(viewport,null);
vplObjects.layerIndex = 2;
vplObjects.sortMode = ViewportLayerSortMode.Z_SORT;
viewport.containerSprite.addLayer(vplObjects);

shadeMateria = new FlatShadeMaterial(mylight, 0xeeee00);
shadeMateria.interactive = true;

chain1 = new Vector.();
chainBody1 = new Vector.();
for (var i:int = 0; i &lt; 12; i++)
{
chainBody1[i] = physics.createSphere(shadeMateria, 15,6,3);
chainBody1[i].maxLinVelocities = 100;
chainBody1[i].maxRotVelocities = 10;
physics.getMesh(chainBody1[i]).addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, handleMousePress);
chainBody1[i].moveTo(new Vector3D( 0, 100 + (20 * i + 20), 0));
vplObjects.addDisplayObject3D(physics.getMesh(chainBody1[i]));
}

var pos1:Vector3D;
var pos2:Vector3D;
for (i = 1; i &lt; chainBody1.length; i++ ){
pos1 = JNumber3D.getScaleVector(Vector3D.Y_AXIS, chainBody1[i - 1].boundingSphere);
pos2 = JNumber3D.getScaleVector(Vector3D.Y_AXIS, -chainBody1[i].boundingSphere);
chain1[i - 1] = new JConstraintPoint(chainBody1[i - 1], pos1, chainBody1[i], pos2, 1, 0.01);
}
}

private function findSkinBody(skin:DisplayObject3D):int
{
for (var i:String in PhysicsSystem.getInstance().bodys)
{
if (skin == physics.getMesh(PhysicsSystem.getInstance().bodys[i]))
{
return int(i);
}
}
return -1;
}

private function handleMousePress(event:InteractiveScene3DEvent):void
{
onDraging = true;
startMousePos = new Vector3D(mouse3D.x, mouse3D.y, mouse3D.z);
currDragBody = PhysicsSystem.getInstance().bodys[findSkinBody(event.displayObject3D)];
planeToDragOn = new Plane3D(new Number3D(0, 0, -1), new Number3D(0, 0, -startMousePos.z));

var bodyPoint:Vector3D = startMousePos.subtract(currDragBody.currentState.position);
dragConstraint = new JConstraintWorldPoint(currDragBody, bodyPoint, startMousePos);
}

private function handleMouseMove(event:MouseEvent):void
{
if (onDraging)
{
var ray:Number3D = camera.unproject(viewport.containerSprite.mouseX, viewport.containerSprite.mouseY);
ray = Number3D.add(ray, new Number3D(camera.x, camera.y, camera.z));

var cameraVertex3D:Vertex3D = new Vertex3D(camera.x, camera.y, camera.z);
var rayVertex3D:Vertex3D = new Vertex3D(ray.x, ray.y, ray.z);
var intersectPoint:Vertex3D = planeToDragOn.getIntersectionLine(cameraVertex3D, rayVertex3D);

dragConstraint.worldPosition = new Vector3D(intersectPoint.x, intersectPoint.y, intersectPoint.z);
}
}

private function handleMouseRelease(event:MouseEvent):void
{
if (onDraging)
{
onDraging = false;
dragConstraint.disableConstraint();
currDragBody.setActive();
}
}

private function resetBody():void
{
if (chainBody1[0].currentState.position.y &lt; -1000)
{
for (var i:String in chainBody1)
{
chainBody1[i].moveTo(new Vector3D( 0, 800 + (20 * int(i) + 20), 0));
}
}
}

protected override function onRenderTick(event:Event = null):void {

//physics.step();//dynamic timeStep
physics.engine.integrate(0.2);//static timeStep
resetBody();
super.onRenderTick(event);
}
}
}

Flash3D Physics

使用papervision3d+jiglibflash创建刚体以及基本的鼠标键盘控制
 See Demo
Code:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package
{
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
import jiglib.geometry.*;
import jiglib.math.*;
import jiglib.cof.JConfig;
import jiglib.physics.*;
import jiglib.physics.constraint.*;
import jiglib.plugin.papervision3d.*;

import org.papervision3d.cameras.CameraType;
import org.papervision3d.core.math.Number3D;
import org.papervision3d.core.math.Plane3D;
import org.papervision3d.core.utils.Mouse3D;
import org.papervision3d.events.*;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.materials.shadematerials.*;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.core.geom.renderables.Vertex3D;
import org.papervision3d.objects.primitives.*;
import org.papervision3d.view.BasicView;
import org.papervision3d.view.layer.ViewportLayer;
import org.papervision3d.view.layer.util.ViewportLayerSortMode;
import org.papervision3d.view.stats.StatsView;

[SWF(width="800", height="600", backgroundColor="#ffffff", frameRate="60")]
public class Flash3DPhysics extends BasicView
{
private var mylight:PointLight3D;
private var mouse3D:Mouse3D;
private var shadeMateria:FlatShadeMaterial;

private var ground:RigidBody;
private var ballBody:Vector.;
private var boxBody:Vector.;
private var capsuleBody:Vector.;

private var onDraging:Boolean = false;

private var currDragBody:RigidBody;
private var dragConstraint:JConstraintWorldPoint;
private var startMousePos:Vector3D;
private var planeToDragOn:Plane3D;

private var keyRight :Boolean = false;
private var keyLeft :Boolean = false;
private var keyForward :Boolean = false;
private var keyReverse :Boolean = false;
private var keyUp:Boolean = false;

private var physics:Papervision3DPhysics;

public function Flash3DPhysics()
{
super(800, 600, true, true, CameraType.TARGET);

stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener( KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseRelease);
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);

init3D();
}

private function init3D():void
{
JConfig.deactivationTime = 0.5;
JConfig.numContactIterations = 15;

physics = new Papervision3DPhysics(scene, 8);

Mouse3D.enabled = true;
mouse3D = viewport.interactiveSceneManager.mouse3D;
viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;

mylight = new PointLight3D(true, true);
mylight.y = 300;
mylight.z = -400;

shadeMateria = new FlatShadeMaterial(mylight, 0x77ee77);
var materiaList :MaterialsList = new MaterialsList();
materiaList.addMaterial(shadeMateria, "all");

ground = physics.createCube(materiaList, 500, 500, 10);
ground.movable = false;
ground.friction = 0.2;
ground.restitution = 0.8;
viewport.getChildLayer(physics.getMesh(ground)).layerIndex = 1;

var vplObjects:ViewportLayer = new ViewportLayer(viewport,null);
vplObjects.layerIndex = 2;
vplObjects.sortMode = ViewportLayerSortMode.Z_SORT;
viewport.containerSprite.addLayer(vplObjects);

ballBody = new Vector.();
var color:uint;
for (var i:int = 0; i &lt; 5; i++)
{
color = (i == 0)?0xff8888:0xeeee00;
shadeMateria = new FlatShadeMaterial(mylight, color);
shadeMateria.interactive = true;
ballBody[i] = physics.createSphere(shadeMateria, 22);
physics.getMesh(ballBody[i]).addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, handleMousePress);
ballBody[i].mass = 3;
ballBody[i].moveTo(new Vector3D( -100, 30 + (50 * i + 50), -100));
vplObjects.addDisplayObject3D(physics.getMesh(ballBody[i]));
}

shadeMateria = new FlatShadeMaterial(mylight,0xeeee00);
shadeMateria.interactive = true;
materiaList = new MaterialsList();
materiaList.addMaterial(shadeMateria,"all");
boxBody=new Vector.();
for (i = 0; i &lt; 5; i++)
{
boxBody[i] = physics.createCube(materiaList, 50, 40, 30);
physics.getMesh(boxBody[i]).addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, handleMousePress);
boxBody[i].moveTo(new Vector3D(0, 50 + (40 * i + 40), 0));
vplObjects.addDisplayObject3D(physics.getMesh(boxBody[i]));
}

var capsuleSkin:Cylinder;
capsuleBody = new Vector.();
for (i = 0; i &lt; 5; i++)
{
capsuleSkin = new Cylinder(shadeMateria, 20, 50);
capsuleSkin.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, handleMousePress);
scene.addChild(capsuleSkin);
vplObjects.addDisplayObject3D(capsuleSkin);

capsuleBody[i] = new JCapsule(new Pv3dMesh(capsuleSkin), 20, 30);
capsuleBody[i].moveTo(new Vector3D(100, 10 + (80 * i + 80), -100));
PhysicsSystem.getInstance().addBody(capsuleBody[i]);
}

camera.y = mylight.y;
camera.z = mylight.z;

var stats:StatsView = new StatsView(renderer);
addChild(stats);

startRendering();
}

private function findSkinBody(skin:DisplayObject3D):int
{
for (var i:String in PhysicsSystem.getInstance().bodys)
{
if (skin == physics.getMesh(PhysicsSystem.getInstance().bodys[i]))
{
return int(i);
}
}
return -1;
}

private function handleMousePress(event:InteractiveScene3DEvent):void
{
onDraging = true;
startMousePos = new Vector3D(mouse3D.x, mouse3D.y, mouse3D.z);
currDragBody = PhysicsSystem.getInstance().bodys[findSkinBody(event.displayObject3D)];
planeToDragOn = new Plane3D(new Number3D(0, 0, -1), new Number3D(0, 0, -startMousePos.z));

var bodyPoint:Vector3D = startMousePos.subtract(currDragBody.currentState.position);
dragConstraint = new JConstraintWorldPoint(currDragBody, bodyPoint, startMousePos);
PhysicsSystem.getInstance().addConstraint(dragConstraint);
}

private function handleMouseMove(event:MouseEvent):void
{
if (onDraging)
{
var ray:Number3D = camera.unproject(viewport.containerSprite.mouseX, viewport.containerSprite.mouseY);
ray = Number3D.add(ray, new Number3D(camera.x, camera.y, camera.z));

var cameraVertex3D:Vertex3D = new Vertex3D(camera.x, camera.y, camera.z);
var rayVertex3D:Vertex3D = new Vertex3D(ray.x, ray.y, ray.z);
var intersectPoint:Vertex3D = planeToDragOn.getIntersectionLine(cameraVertex3D, rayVertex3D);

dragConstraint.worldPosition = new Vector3D(intersectPoint.x, intersectPoint.y, intersectPoint.z);
}
}

private function handleMouseRelease(event:MouseEvent):void
{
if (onDraging)
{
onDraging = false;
PhysicsSystem.getInstance().removeConstraint(dragConstraint);
currDragBody.setActive();
}
}

private function keyDownHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.UP:
keyForward = true;
keyReverse = false;
break;

case Keyboard.DOWN:
keyReverse = true;
keyForward = false;
break;

case Keyboard.LEFT:
keyLeft = true;
keyRight = false;
break;

case Keyboard.RIGHT:
keyRight = true;
keyLeft = false;
break;
case Keyboard.SPACE:
keyUp = true;
break;
}
}

private function keyUpHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.UP:
keyForward = false;
break;

case Keyboard.DOWN:
keyReverse = false;
break;

case Keyboard.LEFT:
keyLeft = false;
break;

case Keyboard.RIGHT:
keyRight = false;
break;
case Keyboard.SPACE:
keyUp=false;
}
}

private function resetBox():void
{
for (var i:int = 0; i &lt; ballBody.length;i++ )
{
if (ballBody[i].currentState.position.y &lt; -200)
{
ballBody[i].moveTo(new Vector3D( 0, 1000 + (60 * i + 60), 0));
}
}

for (i = 0; i &lt; boxBody.length;i++ )
{
if (boxBody[i].currentState.position.y &lt; -200)
{
boxBody[i].moveTo(new Vector3D(0, 1000 + (60 * i + 60), 0));
}
}

for (i = 0; i &lt; capsuleBody.length;i++ )
{
if (capsuleBody[i].currentState.position.y &lt; -200)
{
capsuleBody[i].moveTo(new Vector3D(0, 1000 + (60 * i + 60), 0));
}
}
}

private function testFreezeObject():void {
var _body:RigidBody;
for (var i:int = 0; i &lt; ballBody.length; i++ )
{
_body = ballBody[i];
if (_body.isActive)
{
shadeMateria = (i == 0)? new FlatShadeMaterial(mylight, 0xff8888):new FlatShadeMaterial(mylight, 0xeeee00);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
else
{
shadeMateria = new FlatShadeMaterial(mylight, 0xff7777);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
}

for each (_body in boxBody)
{
if (_body.isActive)
{
shadeMateria = new FlatShadeMaterial(mylight, 0xeeee00);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
else
{
shadeMateria = new FlatShadeMaterial(mylight, 0xff7777);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
}
for each (_body in capsuleBody)
{
if (_body.isActive)
{
shadeMateria = new FlatShadeMaterial(mylight, 0xeeee00);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
else
{
shadeMateria = new FlatShadeMaterial(mylight, 0xff7777);
shadeMateria.interactive = true;
physics.getMesh(_body).material = shadeMateria;
}
}
}

protected override function onRenderTick(event:Event = null):void {

if(keyLeft)
{
ballBody[0].addWorldForce(new Vector3D(-60,0,0),ballBody[0].currentState.position);
}
if(keyRight)
{
ballBody[0].addWorldForce(new Vector3D(60,0,0),ballBody[0].currentState.position);
}
if(keyForward)
{
ballBody[0].addWorldForce(new Vector3D(0,0,60),ballBody[0].currentState.position);
}
if(keyReverse)
{
ballBody[0].addWorldForce(new Vector3D(0,0,-60),ballBody[0].currentState.position);
}
if(keyUp)
{
ballBody[0].addWorldForce(new Vector3D(0, 60, 0), ballBody[0].currentState.position);
}

//physics.step();//dynamic timeStep
PhysicsSystem.getInstance().integrate(0.2);//static timeStep
resetBox();
//testFreezeObject();
super.onRenderTick(event);
}
}
}