/
CartPole BlogSpot
120 lines (99 loc) · 3.17 KB
/
CartPole BlogSpot
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
<html>
<head></head>
<body>
<div id="world">Matter.js Physics Engine TEST<p><br /></p></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.js"></script>
</body>
<script>
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Events = Matter.Events,
Composites = Matter.Composites,
Common = Matter.Common,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.getElementById('world'),
engine: engine,
options: {
width: 600,
height: 500,
showAngleIndicator: false,
wireframes: false
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// add bodies
var offset = 10,
options = {
isStatic: true,
friction: 1
};
world.bodies = [];
// these static walls will not be rendered in this sprites example, see options
World.add(world, [
Bodies.rectangle(400, -offset, 800.5 + 2 * offset, 50.5, options),
Bodies.rectangle(400, 600 + offset, 800.5 + 2 * offset, 50.5, options),
Bodies.rectangle(800 + offset, 300, 50.5, 600.5 + 2 * offset, options),
Bodies.rectangle(-offset, 300, 50.5, 600.5 + 2 * offset, options)
]);
var bubble1 = Bodies.circle(300, 275, 50, {
density: 10,
frictionAir: 0.0,
restitution: 0.8,
friction: 1,
render: {
sprite: {
texture: 'https://brm.io/matter-js/demo/img/ball.png'
}
}
});
var rod1 = Bodies.rectangle(300,100,100,250, {
density: 10,
frictionAir: 0.0,
restitution: 0.8,
friction: 1,
});
World.add(world, [bubble1, rod1]);
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 }
});
// an example of using mouse events on a mouse
Events.on(mouseConstraint, 'startdrag', function(event) {
var mousePosition = event.mouse.position;
console.log('mousedown at ' + mousePosition.x + ' ' + mousePosition.y);
});
Matter.Events.on(engine, 'beforeUpdate', function(event) {
console.log(bubble1.position, rod1.angle);
console.log(bubble1.position.x, rod1.position.x);
Body.translate(bubble1,{x:rod1.position.x-bubble1.position.x, y:0});
});
</script>
</html>