前言
偶然兴趣,想做传感器体感交互内游戏,手机做传感器操控客户端游戏。
当然或许有的兄弟就要说了 “直接移动端获取数据读取传感器操控不更加直接?”。
是的。“我喜欢绕圈子干点硬花样,手机当成一个体感设备采集陀螺仪数据”。
脑内构想
1.手机蓝牙wifi写一些协议直接把手机传感器数据给到服务端,需要详细写一个移动端探索一些通信协议构建时间较长

2.直接通过usb接入一些单片机开发板获取传感器数据,没有设备,也需要写获取陀螺仪数据,传输给到客户端,过程中单片机需要写大部分代码,客户端也要做一些数据串口数据格式化,工程量大


3.直接在客户端里面用webview承载cocos内容,顺便同时创建wss、https h5两个服务,直接手机端访问网页把传感器数据给到客户端,cocos端接入wss实现交互,数度快
演示地址
截图
整理流程

代码仓库
https://github.com/liminmsn/motion_sensing_racing
部分核心代码
Cocos3d
- main.ts
import { _decorator, Component, Node, Label, Vec3, input, Input, EventKeyboard, KeyCode, math } from 'cc';
const { ccclass, property } = _decorator;
interface MotionData {
type: 'motion';
x: number; y: number; z: number;
ra: number; rb: number; rg: number;
t: number;
}
interface OrientationData {
type: 'orientation';
alpha: number; beta: number; gamma: number;
t: number;
}
type SensorData = MotionData | OrientationData;
@ccclass('main')
export class main extends Component {
@property(Node)
cube: Node | null = null;
@property(Label)
debugLabel: Label | null = null;
// ===== 可调参数 =====
@property({ tooltip: '最大速度 (单位/秒)' })
maxSpeed = 5;
@property({ tooltip: '加速度 (单位/秒²)' })
accel = 8;
@property({ tooltip: '转向速度 (度/秒)' })
turnRate = 120;
@property({ tooltip: '倾斜死区 (度),小于它视为不操作' })
deadZoneDeg = 5;
@property({ tooltip: '倾斜多少度算满舵' })
fullTiltDeg = 45;
@property({ tooltip: '超过多少毫秒没收到数据就停车' })
timeoutMs = 500;
@property({ tooltip: '反向油门(前倾变后退)' })
invertThrottle = false;
@property({ tooltip: '反向转向(左右对调)' })
invertSteer = true; // 默认开启,因为手感需要调换
// ===== WebSocket =====
private ws: WebSocket | null = null;
private reconnectTimer: number = 0;
private wsUrl = 'wss://192.168.1.4:8765'; // 换成你电脑的局域网 IP
private latestMotion: MotionData | null = null;
private latestOrientation: OrientationData | null = null;
private lastRecvTime = 0;
// ===== 校准零点 =====
private zeroBeta = 0;
private zeroGamma = 0;
// ===== 车辆状态 =====
private speed = 0;
private heading = 0;
private pos = new Vec3(0, 0, 0);
// 平滑后的控制量
private throttle = 0;
private steer = 0;
start() {
if (this.cube) this.pos.set(this.cube.position);
this.connect();
input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
// 启动 1 秒后自动校准(假设开始时手机水平握正)
setTimeout(() => this.calibrate(), 1000);
}
onDestroy() {
input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
if (this.ws) {
this.ws.onclose = null;
this.ws.close();
this.ws = null;
}
}
// ===== 键盘:C 校准,R 复位 =====
private onKeyDown(e: EventKeyboard) {
if (e.keyCode === KeyCode.KEY_C) this.calibrate();
if (e.keyCode === KeyCode.KEY_R) {
this.speed = 0;
this.heading = 0;
this.pos.set(0, 0, 0);
this.applyTransform();
this.updateDebug('已复位');
}
}
private calibrate() {
const o = this.latestOrientation;
if (!o) {
this.updateDebug('校准失败:还没有方向数据');
return;
}
this.zeroBeta = o.beta;
this.zeroGamma = o.gamma;
this.updateDebug(`已校准 β0=${o.beta.toFixed(1)} γ0=${o.gamma.toFixed(1)}`);
}
// ===== WebSocket =====
private connect() {
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
return;
}
console.log('[WS] connecting', this.wsUrl);
this.ws = new WebSocket(this.wsUrl);
this.ws.onopen = () => {
console.log('[WS] connected');
this.updateDebug('WS 已连接');
};
this.ws.onmessage = (evt) => {
try {
const data: SensorData = JSON.parse(evt.data);
if (data.type === 'motion') {
this.latestMotion = data;
} else if (data.type === 'orientation') {
this.latestOrientation = data;
}
this.lastRecvTime = Date.now();
} catch (e) {
console.warn('[WS] 消息解析失败', evt.data, e);
}
};
this.ws.onerror = (e) => {
console.warn('[WS] error', e);
this.updateDebug('WS 连接出错');
};
this.ws.onclose = () => {
console.log('[WS] closed, 3s 后重连');
this.updateDebug('WS 断开,重连中…');
this.ws = null;
this.reconnectTimer = setTimeout(() => this.connect(), 3000) as unknown as number;
};
}
private updateDebug(text: string) {
if (this.debugLabel) this.debugLabel.string = text;
}
// ===== 每帧驱动车辆 =====
update(dt: number) {
if (dt > 0.1) dt = 0.1; // 防止切后台回来大跳
const fresh = (Date.now() - this.lastRecvTime) < this.timeoutMs;
const o = this.latestOrientation;
let targetThrottle = 0;
let targetSteer = 0;
if (fresh && o) {
const throttleDir = this.invertThrottle ? -1 : 1;
const steerDir = this.invertSteer ? -1 : 1;
// 前后倾斜 → 油门:前倾(beta 减小)为前进
targetThrottle = throttleDir * (this.zeroBeta - o.beta) / this.fullTiltDeg;
// 左右倾斜 → 转向:右倾(gamma 增大)为右转
targetSteer = steerDir * (o.gamma - this.zeroGamma) / this.fullTiltDeg;
// 死区
const dz = this.deadZoneDeg / this.fullTiltDeg;
if (Math.abs(targetThrottle) < dz) targetThrottle = 0;
if (Math.abs(targetSteer) < dz) targetSteer = 0;
targetThrottle = math.clamp(targetThrottle, -1, 1);
targetSteer = math.clamp(targetSteer, -1, 1);
}
// 平滑,避免抖动
this.throttle = math.lerp(this.throttle, targetThrottle, Math.min(1, dt * 8));
this.steer = math.lerp(this.steer, targetSteer, Math.min(1, dt * 8));
// 速度
this.speed += this.throttle * this.accel * dt;
this.speed *= Math.pow(0.3, dt); // 摩擦
this.speed = math.clamp(this.speed, -this.maxSpeed, this.maxSpeed);
// 朝向
this.heading += this.steer * this.turnRate * dt;
// 位移:heading=0 时向 +Z,向 +X 为右转
const rad = this.heading * Math.PI / 180;
this.pos.x += Math.sin(rad) * this.speed * dt;
this.pos.z += Math.cos(rad) * this.speed * dt;
this.applyTransform();
// 状态显示
if (this.debugLabel) {
const wsOK = this.ws?.readyState === WebSocket.OPEN ? 'OK' : 'NO';
this.debugLabel.string =
`WS:${wsOK} T:${this.throttle.toFixed(2)} S:${this.steer.toFixed(2)} ` +
`V:${this.speed.toFixed(2)} H:${this.heading.toFixed(0)}°`;
}
}
private applyTransform() {
if (!this.cube) return;
this.cube.setPosition(this.pos);
this.cube.setRotationFromEuler(0, this.heading, 0);
}
}
Python
- control_server.py
import asyncio
import socket
import ssl
import threading
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import websockets
from src.resources import ROOT
HTTP_PORT = 8000
WS_PORT = 8765
CERT_FILE = ROOT / "server.pem"
KEY_FILE = None
def get_lan_ip() -> str:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
finally:
s.close()
def make_ssl_context() -> ssl.SSLContext:
if not CERT_FILE.exists():
raise FileNotFoundError(f"证书不存在: {CERT_FILE}")
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(str(CERT_FILE))
return ctx
class ControlServer:
def __init__(self):
self.ip = get_lan_ip()
self.clients: set = set() # 所有连接的客户端
print(f"局域网 IP: {self.ip}")
threading.Thread(target=self.run_h5, daemon=True).start()
threading.Thread(target=self.run_ws, daemon=True).start()
# ---------- HTTP ----------
def run_h5(self):
www = str(ROOT / "www")
handler = lambda *a, **kw: SimpleHTTPRequestHandler(*a, directory=www, **kw)
httpd = ThreadingHTTPServer(("0.0.0.0", HTTP_PORT), handler)
httpd.socket = make_ssl_context().wrap_socket(httpd.socket, server_side=True)
print(f"HTTPS: https://{self.ip}:{HTTP_PORT}/")
httpd.serve_forever()
# ---------- WebSocket ----------
def run_ws(self):
async def broadcast(message: str, exclude=None):
"""广播给除 exclude 外所有客户端"""
targets = [c for c in self.clients if c is not exclude]
if not targets:
return
await asyncio.gather(
*(c.send(message) for c in targets),
return_exceptions=True, # 某个客户端断了不影响其他
)
async def handler(ws):
self.clients.add(ws)
peer = ws.remote_address
print(f"[WS] + {peer} (共 {len(self.clients)} 个)")
try:
async for msg in ws:
# 这里不打印原始内容,避免日志刷屏
# print(f"[WS] <- {peer}: {msg}")
await broadcast(msg, exclude=ws)
except websockets.ConnectionClosed:
pass
finally:
self.clients.discard(ws)
print(f"[WS] - {peer} (剩 {len(self.clients)} 个)")
async def main():
async with websockets.serve(
handler, "0.0.0.0", WS_PORT, ssl=make_ssl_context()
):
print(f"WSS: wss://{self.ip}:{WS_PORT}")
await asyncio.Future()
asyncio.run(main())





一个当头显 一个当方向盘 一个当油门一个当刹车
