Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ fun SimpleGamepadCapture(

LaunchedEffect(gamepadViewModel.gamepadEngaged) {
withContext(Dispatchers.Default) {
var lastPollTime = 0L
while (true) {
try {
ensureActive()
Expand All @@ -160,7 +161,13 @@ fun SimpleGamepadCapture(
val pollLevel = gamepadViewModel.checkGamepadActive()
if (pollLevel == GamepadViewModel.PollLevel.Close) break

gamepadViewModel.pollJoystick()
// 按实际轮询间隔归一化本帧偏移量
// 首轮询间隔记为0,避免重启循环后视角跳动
val now = System.nanoTime()
val deltaMs = if (lastPollTime == 0L) 0.0 else (now - lastPollTime) / 1_000_000.0
lastPollTime = now

gamepadViewModel.pollJoystick(deltaMs)
delay(pollLevel.delayMs.milliseconds)
} catch (_: CancellationException) {
break
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ import kotlin.math.sin

private const val MOUSE_MAX_ACCELERATION = 2.0

/** 采样基准周期(ms) */
private const val BASE_TICK_MS = 16.0
/** 单次偏移量的最大时间倍率 */
private const val MAX_TIME_SCALE = 4.0

/**
* 摇杆横轴、纵轴偏移量状态
*/
Expand All @@ -49,12 +54,15 @@ class Joystick(

fun isUsing(): Boolean = horizontalValue != 0f || verticalValue != 0f

fun onTick(sendEvent: (Event) -> Unit) {
fun onTick(deltaMs: Double, sendEvent: (Event) -> Unit) {
val mouseAngle = angleRadian ?: getAngleRadian()
val acceleration = acceleration ?: calculateAcceleration()

val deltaX = (cos(mouseAngle) * acceleration).toFloat()
val deltaY = (sin(mouseAngle) * acceleration).toFloat()
// 偏移量按实际采样间隔归一化
// 采样率越高,单次偏移越小
val timeScale = (deltaMs / BASE_TICK_MS).coerceIn(0.0, MAX_TIME_SCALE)
val deltaX = (cos(mouseAngle) * acceleration * timeScale).toFloat()
val deltaY = (sin(mouseAngle) * acceleration * timeScale).toFloat()

val offset = Offset(deltaX, -deltaY)
//偏移量为0的情况下,无论发不发送事件都是无意义的
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,10 +385,11 @@ class GamepadViewModel : ViewModel() {

/**
* 轮询调用,持续发送当前拥有的摇杆状态
* @param deltaMs 距离上次轮询经过的毫秒数
*/
fun pollJoystick() {
leftJoystick.onTick(::sendEvent)
rightJoystick.onTick(::sendEvent)
fun pollJoystick(deltaMs: Double) {
leftJoystick.onTick(deltaMs, ::sendEvent)
rightJoystick.onTick(deltaMs, ::sendEvent)
}

private fun sendEvent(event: Event) {
Expand Down Expand Up @@ -439,9 +440,9 @@ class GamepadViewModel : ViewModel() {

enum class PollLevel(val delayMs: Long) {
/**
* 高轮询等级:16ms延迟60fps
* 高轮询等级:4ms延迟250fps
*/
High(16L),
High(4L),

/**
* 不进行轮询
Expand Down