跳至主要内容

动态场景中的力反馈教程

在《基础力反馈》教程的基础上,本指南介绍了如何在 Unity 中模拟动态交互,使用户能够感受到来自运动物体的力反馈。 该场景突显了触觉反馈对高频更新的需求,其更新频率远高于 Unity 中视觉渲染的典型更新频率。

简介​

要获得引人入胜的触觉体验,特别是在动态场景中,以高于 1kHz 的频率进行计算至关重要。 这与通常以约 60Hz 运行的游戏更新循环形成了鲜明对比。 挑战在于如何在主游戏循环之外并行管理这些高频更新,并确保线程安全的数据交换,以保持力反馈的一致性和准确性。

扩展基础力反馈设置​

从 基础力反馈 教程中的场景设置开始。为了添加动态效果,我们将修改 SphereForceFeedback 脚本,使其能够响应球体的运动,并模拟与动态移动物体之间的交互。

主要修改​

  • 动态物体运动:添加逻辑,根据用户输入或预定义的运动模式更新 Sphere 的位置和速度。
  • 线程安全的数据交换:使用 ReaderWriterLockSlim 管理主线程与触觉线程之间对共享数据的并发访问。
  • 力调整计算:修改 SphereForceFeedback.ForceCalculation 一种方法,使其能够考虑球体的速度,从而根据位置和运动提供逼真的反馈。

动态交互​

要模拟运动中的球体,您可以在 Update 可以在代码中手动更新其位置,也可以使用独立的组件,根据键盘输入或其他交互来控制其运动。 在本示例中,我们将 球体 将游戏对象重命名为 移动球,并添加 教程 示例中提供的 MovingObject 组件。

为运动做准备 ForceCalculation​

力反馈计算现在需要考虑“移动球体”的速度,并根据交互的位置和速度来调整力。 这样可以提供更细腻、更逼真的触觉感受,体现交互的动态特性。

  • 添加一个 Vector3 类型的 otherVelocity 方法参数
  • 将 force -= cursorVelocity * damping 替换为 force -= (cursorVelocity - otherVelocity) * damping
private Vector3 ForceCalculation(Vector3 cursorPosition, Vector3 cursorVelocity, float cursorRadius,
Vector3 otherPosition, Vector3 otherVelocity, float otherRadius)
{
var force = Vector3.zero;

var distanceVector = cursorPosition - otherPosition;
var distance = distanceVector.magnitude;
var penetration = otherRadius + cursorRadius - distance;

if (penetration > 0)
{
// Normalize the distance vector to get the direction of the force
var normal = distanceVector.normalized;

// Calculate the force based on penetration
force = normal * penetration * stiffness;

// Calculate the relative velocity
var relativeVelocity = cursorVelocity - otherVelocity;

// Apply damping based on the relative velocity
force -= relativeVelocity * damping;
}

return force;
}

线程安全的数据交换​

在物体能够移动并进行实时交互的动态场景中,确保触觉反馈的计算基于最新数据,同时避免并发访问导致数据损坏,这一点至关重要。 这正是线程安全数据交换变得不可或缺的原因。

线程安全数据交换的核心概念​

  • 线程安全机制:使用 ReaderWriterLockSlim 管理并发数据访问。它允许多个读取操作或单个写入操作同时进行,从而确保数据完整性。
  • 数据读取与写入:
    • 读取:触觉线程在读锁的保护下读取物体的位置和速度,以确保不会干扰数据更新。
    • 写入:主线程对对象数据的更新是在写锁的保护下进行的,以防止同时发生的读写操作导致数据状态不一致。

在 Unity 中实现​

  • 场景数据结构体:为了便于执行线程安全操作,我们定义了一个结构体,用于保存与场景相关的所有必要数据。 该结构体包含“移动球”和光标的位置与速度,以及它们各自的半径。 这一数据结构是我们实现线程安全数据交换的基础。

    private struct SceneData
    {
    public Vector3 ballPosition;
    public Vector3 ballVelocity;
    public float ballRadius;
    public float cursorRadius;
    }

    private SceneData _cachedSceneData;
  • 锁的初始化:初始化一个 ReaderWriterLockSlim 实例,用于管理对场景数据的访问。 该锁允许多个线程同时读取数据,或由单个线程独占加锁进行写入,从而在并发操作期间确保数据完整性。

    private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  • 使用写锁写入缓存:SaveSceneData 该方法在写锁内更新场景数据。 这可确保当一个线程更新数据时,其他线程无法进行读取或写入,从而防止数据竞争并保证一致性。

    private void SaveSceneData()
    {
    _cacheLock.EnterWriteLock();
    try
    {
    var t = transform;
    _cachedSceneData.ballPosition = t.position;
    _cachedSceneData.ballRadius = t.lossyScale.x / 2f;

    _cachedSceneData.cursorRadius = inverse3.Cursor.Radius;

    _cachedSceneData.ballVelocity = _movableObject.Velocity;
    }
    finally
    {
    _cacheLock.ExitWriteLock();
    }
    }
  • 使用读锁读取缓存:GetSceneData 该方法在读锁保护下获取场景数据。 这使得多个线程能够安全地并发读取数据,同时不会干扰写入操作,从而确保触觉反馈的计算基于最新的场景数据。

    private SceneData GetSceneData()
    {
    _cacheLock.EnterReadLock();
    try
    {
    return _cachedSceneData;
    }
    finally
    {
    _cacheLock.ExitReadLock();
    }
    }
  • 主线程数据更新:FixedUpdate 该方法用于在主线程中定期更新场景数据。 这确保了触觉反馈计算能够获取最新数据,从而反映场景的动态变化。

    private void FixedUpdate()
    {
    SaveSceneData();
    }
  • 使用更新后的数据进行力计算:在 OnDeviceStateChanged 在回调过程中,力计算使用通过线程安全方法获取的最新场景数据进行。这确保了力反馈的准确性,并能及时响应场景中的动态交互。

    var sceneData = GetSceneData();

    var force = ForceCalculation(device.CursorLocalPosition, device.CursorLocalVelocity, sceneData.cursorRadius,
    sceneData.ballPosition, sceneData.ballVelocity, sceneData.ballRadius);

游戏体验​

这些脚本增强功能使您能够与场景中主动移动的球体进行交互。 触觉反馈会根据球体的运动轨迹进行动态调整,带来更具沉浸感、触感更丰富的体验。

移动的小球

源文件​

本示例的完整场景及相关文件可从 Unity 包管理器中的“Tutorials”示例导入。

教程 示例包含 MovableObject 脚本,该脚本在多个示例中均有使用,用于通过键盘输入控制关联的游戏对象的移动。

SphereForceFeedback.cs​

/*
* Copyright 2024 Haply Robotics Inc. All rights reserved.
*/

using System.Threading;
using Haply.Inverse.DeviceControllers;
using Haply.Inverse.DeviceData;
using Haply.Samples.Tutorials.Utils;
using UnityEngine;

namespace Haply.Samples.Tutorials._4A_DynamicForceFeedback
{
public class SphereForceFeedback : MonoBehaviour
{
// must assign in inspector
public Inverse3Controller inverse3;

[Range(0, 800)]
// Stiffness of the force feedback.
public float stiffness = 500f;

[Range(0, 3)]
public float damping = 1f;

#region Thread-safe cached data

/// <summary>
/// Represents scene data that can be updated in the Update() call.
/// </summary>
private struct SceneData
{
public Vector3 ballPosition;
public Vector3 ballVelocity;
public float ballRadius;
public float cursorRadius;
}

/// <summary>
/// Cached version of the scene data.
/// </summary>
private SceneData _cachedSceneData;

private MovableObject _movableObject;

/// <summary>
/// Lock to ensure thread safety when reading or writing to the cache.
/// </summary>
private readonly ReaderWriterLockSlim _cacheLock = new();

/// <summary>
/// Safely reads the cached data.
/// </summary>
/// <returns>The cached scene data.</returns>
private SceneData GetSceneData()
{
_cacheLock.EnterReadLock();
try
{
return _cachedSceneData;
}
finally
{
_cacheLock.ExitReadLock();
}
}

/// <summary>
/// Safely updates the cached data.
/// </summary>
private void SaveSceneData()
{
_cacheLock.EnterWriteLock();
try
{
var t = transform;
_cachedSceneData.ballPosition = t.position;
_cachedSceneData.ballRadius = t.lossyScale.x / 2f;

_cachedSceneData.cursorRadius = inverse3.Cursor.Radius;

_cachedSceneData.ballVelocity = _movableObject.Velocity;
}
finally
{
_cacheLock.ExitWriteLock();
}
}

#endregion

/// <summary>
/// Saves the initial scene data cache.
/// </summary>
private void Start()
{
inverse3 ??= FindFirstObjectByType<Inverse3Controller>();
inverse3.Ready.AddListener((device, args) => SaveSceneData());
_movableObject = GetComponent<MovableObject>();
}

/// <summary>
/// Update scene data cache.
/// </summary>
private void FixedUpdate()
{
if (inverse3.IsReady)
{
SaveSceneData();
}
}

/// <summary>
/// Subscribes to the DeviceStateChanged event.
/// </summary>
private void OnEnable()
{
inverse3.DeviceStateChanged += OnDeviceStateChanged;
}

/// <summary>
/// Unsubscribes from the DeviceStateChanged event.
/// </summary>
private void OnDisable()
{
inverse3.DeviceStateChanged -= OnDeviceStateChanged;
inverse3.Release();
}

/// <summary>
/// Calculates the force based on the cursor's position and another sphere position.
/// </summary>
/// <param name="cursorPosition">The position of the cursor.</param>
/// <param name="cursorVelocity">The velocity of the cursor.</param>
/// <param name="cursorRadius">The radius of the cursor.</param>
/// <param name="otherPosition">The position of the other sphere (e.g., ball).</param>
/// <param name="otherVelocity">The velocity of the other sphere (e.g., ball).</param>
/// <param name="otherRadius">The radius of the other sphere.</param>
/// <returns>The calculated force vector.</returns>
private Vector3 ForceCalculation(Vector3 cursorPosition, Vector3 cursorVelocity, float cursorRadius,
Vector3 otherPosition, Vector3 otherVelocity, float otherRadius)
{
var force = Vector3.zero;

var distanceVector = cursorPosition - otherPosition;
var distance = distanceVector.magnitude;
var penetration = otherRadius + cursorRadius - distance;

if (penetration > 0)
{
// Normalize the distance vector to get the direction of the force
var normal = distanceVector.normalized;

// Calculate the force based on penetration
force = normal * penetration * stiffness;

// Calculate the relative velocity
var relativeVelocity = cursorVelocity - otherVelocity;

// Apply damping based on the relative velocity
force -= relativeVelocity * damping;
}

return force;
}

/// <summary>
/// Event handler that calculates and send the force to the device when the cursor's position changes.
/// </summary>
/// <param name="sender">The Inverse3 data object.</param>
/// <param name="args">The event arguments containing the device data.</param>
private void OnDeviceStateChanged(object sender, Inverse3EventArgs args)
{
var inverse3 = args.DeviceController;
var sceneData = GetSceneData();

// Calculate the moving ball force.
var force = ForceCalculation(inverse3.CursorLocalPosition, inverse3.CursorLocalVelocity, sceneData.cursorRadius,
sceneData.ballPosition, sceneData.ballVelocity, sceneData.ballRadius);

// Apply the force to the cursor.
inverse3.SetCursorLocalForce(force);
}
}
}