-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPhysics.js
More file actions
74 lines (64 loc) · 1.94 KB
/
Physics.js
File metadata and controls
74 lines (64 loc) · 1.94 KB
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
import Matter from "matter-js";
import { useState, useEffect } from 'react';
import { Accelerometer } from 'expo-sensors';
// 创建引擎
const engine = Matter.Engine.create({ enableSleeping: false });
const world = engine.world;
// 引擎对象
export const physicsEntity = {
engine: engine,
world: world
};
// 更新引擎
export const Physics = (entities, { time }) => {
let engine = entities["physics"].engine;
Matter.Engine.update(engine, time.delta);
return entities;
};
// 点击创建球
let ballIndex = 0;
const ballColors = [ "#f93", "#f39", "#9f3", "#3f9", "#93f", "#39f"];
export const CreateBalls = (renderer)=> (entities, { touches, screen }) => {
const ballSize = Math.trunc(Math.max(screen.width, screen.height) * 0.075);
touches.filter(t => t.type === "press").forEach(t => {
entities[++ballIndex] = {
body: createBall(t.event.pageX, t.event.pageY, ballSize / 2),
size: [ballSize, ballSize],
color: ballColors[ballIndex % ballColors.length],
renderer: renderer
};
});
return entities;
};
//创建墙
export const createWall = (x, y, w, h) => {
const wall = Matter.Bodies.rectangle(x, y, w, h, { isStatic: true })
Matter.World.add(world, wall);
return wall;
};
//创建球
export const createBall = (x, y, r) => {
const ball = Matter.Bodies.circle(x, y, r, { frictionAir: 0.021 });
Matter.World.add(world, [ball]);
return ball;
}
export const useAccelerometer = () => {
const [subscription, setSubscription] = useState(null);
const subscribeAccelerometer = () => {
setSubscription(
Accelerometer.addListener(accelerometerData => {
const { x, y, z } = accelerometerData;
world.gravity.x = -x;
world.gravity.y = y;
})
);
};
const unsubscribeAccelerometer = () => {
subscription && subscription.remove();
setSubscription(null);
};
useEffect(() => {
subscribeAccelerometer();
return () => unsubscribeAccelerometer();
}, []);
}