我在 Unity 中使用 Vuforia 进行 AR 设置。我将下面的脚本放在一个空的游戏对象(它不是我的 imagetarget 的子对象)上,并在检查器中分配了公共值。当找到 Imagetarget 时,GameObjects 就会出现。然后我通过Raycast(AR相机)选择对象。 缩放和移动游戏对象时会出现问题。
我无法将值设置回默认转换。我为 localScale 和 position 做了一个解决方法,我把一些值作为“限制”。但这实际上不是我想要实现的。这个职位的表现真的很奇怪。我唯一想要实现的是击中对象 - 按一个值缩放它并将对象移向 y - 当没有击中时,对象应该简单地重置为其原始值。如果有人能帮我解决这个问题那就太好了。
提前致谢,米拉
我正在使用 Unity3d 2021.3.9f 和 Vuforia 10.14.4 进行测试。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScaleOnHit : MonoBehaviour
{
public Camera arCamera; // Reference to the AR camera in the scene
[SerializeField] private string selectableTag = "Selectable";
public Vector3 targetScale = new Vector3(0.02f, 0.02f, 0.02f);
public Vector3 defaultScale = new Vector3(0.008f, 0.008f, 0.008f);
public float duration = 2.0f;
public float moveY = 0.01f;
public AnimationCurve curve;
private Transform _selection;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (_selection != null)
{
for (float time = 0; time < duration; time += Time.deltaTime)
{
// Calculate the current scale based on the elapsed time and set it
float t = time / duration;
var easing = curve.Evaluate(t);
_selection.localScale = Vector3.Lerp(targetScale, defaultScale, easing);
}
_selection = null;
}
RaycastHit hit;
Ray ray = new Ray(arCamera.transform.position, arCamera.transform.forward); // Create a ray from the AR camera position in the direction it's facing
if (Physics.Raycast(ray, out hit)) // Check if the ray hits an object
{
GameObject store = hit.collider.gameObject;
var selection = hit.transform;
if (selection.CompareTag(selectableTag))
{
if (hit.transform.position.y < -1.0f || hit.transform.position.y > -0.5f)
{
selection.position = new Vector3(
hit.transform.position.x,
hit.transform.position.y + moveY,
hit.transform.position.z);
}
for (float time = 0; time < duration; time += Time.deltaTime)
{
float t = time / duration;
var easing = curve.Evaluate(t);
selection.localScale = Vector3.Lerp(defaultScale, targetScale, easing);
}
_selection = selection;
}
}
}
}