跳转至正文

动态场景中的力反馈教程

基于基础力反馈教程,本指南将介绍如何在 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);
}
}
}