본문으로 건너뛰기

간단한 위치 제어 튜토리얼

이 튜토리얼에서는입문 가이드에서 소개한 개념을 바탕으로, 동적 게임 오브젝트를 사용하여 Unity 씬 내에서 ‘ Inverse3 ’ 기기의 커서 위치를 제어하는 방법을 설명합니다.

서문​

Inverse3 이 장치는,힘 제어(힘 제어)와위치 제어(위치 제어)의 두 가지 제어 모드를 지원합니다. 전자는 커서 위치를 기준으로 힘을 조절하는 반면, 후자는 커서 위치를 직접 조작합니다. 이 튜토리얼에서는,동적 장면에서의 힘 피드백 튜토리얼 해당 장면 설정을 활용하여,FixedUpdate 메서드 내에서 CursorSetPosition 을 사용하여 디바이스의 커서가 게임 오브젝트의 움직임을 따라가도록 합니다.

장면 설정​

동적 장면에서의 힘 피드백 튜토리얼 에서 설명한 장면 구성부터 시작하겠습니다. 이 장면에는,햅틱 리그 그리고,MovableObject 컴포넌트에 의해 제어되는 움직이는 공 게임 오브젝트가 포함되어 있습니다.

SpherePositionControl 컴포넌트 구현​

움직이는 공 게임 오브젝트상의 SphereForceFeedback 컴포넌트를 새로운 C# 스크립트로 SpherePositionControl.cs 로 대체합니다. SpherePositionControl 클래스 내에서 다음 속성을 정의합니다:

public Inverse3 inverse3;
public float minSyncDistance = 0.05f;
private bool _isCursorSynchronized;
  • inverse3: 인스펙터에서 설정하는,Inverse3 장치 컴포넌트에 대한 참조입니다.
  • minSyncDistance: 커서 동기화를 시작하기 위한 최소 거리 임계값입니다.
  • _isCursorSynchronized: 커서의 움직임이 Moving Ball과 동기화되어 있는지 여부를 나타내는 플래그입니다.

동기 로직​

'Moving Ball '과의 근접도를 기준으로 커서 동기화를 시작하고 중지하는 메서드를 구현합니다:

private void StartSynchronizeCursor()
{
var cursorPosition = inverse3.Cursor.transform.position;
GetComponent<MovableObject>().SetTargetPosition(cursorPosition, teleport: true);
_isCursorSynchronized = true;
}

private void StopSynchronizeCursor()
{
_isCursorSynchronized = !inverse3.Release();
}

여기서는 MovableObject.SetTargetPosition(position, teleport:true) 를 사용합니다. 이를 통해,무빙볼 가 커서 위치로 순간이동됩니다.

Update 메서드와 FixedUpdate 메서드​

Update 메서드에서는 커서와 움직이는 공 다음 거리를 기준으로 커서 동기화를 전환합니다:

private void Update()
{
var distance = Vector3.Distance(inverse3.CursorPosition, transform.position);
if (!_isCursorSynchronized && distance <= minSyncDistance)
{
StartSynchronizeCursor();
}
else if (_isCursorSynchronized && distance > minSyncDistance)
{
StopSynchronizeCursor();
}
}

동기화가 활성화된 경우,FixedUpdate 내에서 커서의 위치를 움직이는 공 다음 위치와 일치하도록 업데이트합니다:

private void FixedUpdate()
{
if (_isCursorSynchronized)
{
inverse3.SetCursorPosition(transform.position);
}
}

위치 제어가 그래픽 렌더링 성능에 영향을 받지 않고 안정적인 프레임 속도로 작동하도록 하려면 FixedUpdate 메서드를 사용하십시오.

초기화​

Awake() 내부에서, 주로 사용하는 손과 관계없이 Inverse3 기기에서 접근할 수 있는 위치에 움직이는 공 다음이 시작되도록 설정해 주세요:

private void Awake()
{
inverse3.Ready.AddListener(device =>
{
GetComponent<MovableObject>().SetTargetPosition(((Inverse3)device).WorkspaceCenterLocalPosition, teleport: true);
});
}

게임 플레이 체험​

Inverse3 장치를 단단히 고정하고 충분한 공간을 확보해 주십시오. 플레이 모드를 활성화한 후 커서를 ‘Moving Ball’에 가까이 가져가면, ‘Inverse3 ’이 ‘Moving Ball’의 움직임을 따라갑니다. 키보드로 ‘Moving Ball’을 이동시켜 보면, 커서가 그 위치를 추적하는 것을 확인할 수 있습니다.

간단한 위치 제어

소스 파일​

이 튜토리얼의 전체 씬 및 관련 파일은 Unity Package Manager 내의 튜토리얼 샘플에 있습니다. 여기에는 MovableObject 스크립트가 포함되어 있습니다. 이 스크립트는 여러 예제에서 키보드 입력을 통해 게임 오브젝트의 이동을 제어하는 데 사용됩니다.

SpherePositionControl.cs​

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

using Haply.Inverse.DeviceControllers;
using Haply.Samples.Tutorials.Utils;
using UnityEngine;

namespace Haply.Samples.Tutorials._5_SimplePositionControl
{
/// <summary>
/// Controls the Inverse3 cursor position based on the current position of this GameObject.
/// When the GameObject is within a specified distance from the cursor, it initiates synchronized control,
/// allowing the cursor to follow the GameObject's movements.
/// </summary>
[RequireComponent(typeof(MovableObject))]
public class SpherePositionControl : MonoBehaviour
{
public Inverse3Controller inverse3;

[Tooltip("Minimum distance required to initiate synchronized control between this GameObject and the Inverse3 cursor.")]
[Range(0, 1)]
public float minSyncDistance = 0.05f;

private bool _isCursorSynchronized;

private void Awake()
{
// Ensure inverse3 is set, finding it in the scene if necessary.
inverse3 ??= FindFirstObjectByType<Inverse3Controller>();

// When inverse3 is ready, so the handedness is defined
inverse3.Ready.AddListener((device, args) =>
{
// Teleport the sphere to its workspace center to ensure it can be reached,
// regardless of whether the device is left or right-handed. This ensures the GameObject starts in a
// position that is accessible by the Inverse3 device.
GetComponent<MovableObject>().SetTargetPosition(device.WorkspaceCenterLocalPosition, teleport:true);
});
}

private void OnDisable()
{
// Ensure movement synchronization is disabled when the component is disabled.
StopSynchronizeCursor();
inverse3.Release();
}

private void Update()
{
if (!inverse3.IsReady)
{
return;
}
// Calculate the distance between the Inverse3 position and this object's position.
var distance = Vector3.Distance(inverse3.CursorPosition, transform.position);

// Enable synchronized movement if within the minimum sync distance and not already synced.
if (!_isCursorSynchronized && distance <= minSyncDistance)
{
StartSynchronizeCursor();
}
// Disable synchronized movement if outside the minimum sync distance and currently synced.
else if (_isCursorSynchronized && distance > minSyncDistance)
{
StopSynchronizeCursor();
}
}

private void FixedUpdate()
{
if (_isCursorSynchronized)
{
// If in sync, set the Inverse3 cursor position to this object's position.
inverse3.SetCursorPosition(transform.position);
}
else
{
inverse3.ProbeCursorPosition(true);
}
}

private void StartSynchronizeCursor()
{
// Get the current cursor position.
var cursorPosition = inverse3.Cursor.transform.position;

// Teleport this object to the cursor position to avoid a sudden jump when position control starts.
GetComponent<MovableObject>().SetTargetPosition(cursorPosition, teleport:true);

// Start synchronizing the movement of this object with the cursor.
_isCursorSynchronized = true;
}

private void StopSynchronizeCursor()
{
// Stop synchronizing the movement.
_isCursorSynchronized = !inverse3.Release();
}
}
}