【问题标题】:Vector3.SmoothDamp() isn't moving the gameObject completelyVector3.SmoothDamp() 没有完全移动游戏对象
【发布时间】:2022-01-15 23:06:33
【问题描述】:

当我将游戏对象拖到屏幕边框之外时,它会回到场景中心,但在游戏对象的中间越过边缘进入屏幕后它会立即停止移动。

此屏幕截图显示游戏对象在向场景中心移动时立即停止。

我的错误在哪里?如何让卡片完全移动到场景中心?

[SerializeField] private Canvas canvas;
Vector3 offset = Vector3.zero;

[SerializeField] private GameObject cardChoice;
private CanvasGroup cardChoiceCG;

private int resolutionX = Screen.width;
private int resolutionY = Screen.height;

[SerializeField] private float distanceToFadeIn;

[SerializeField] private float smoothTime = 0.25f;
private Vector3 velocity = Vector3.zero;


private void Start() {

    cardChoiceCG = cardChoice.GetComponent<CanvasGroup>();
}


private void Update() {

    Vector3 screenPosition = canvas.worldCamera.WorldToScreenPoint(this.transform.position);

    if (screenPosition.x > resolutionX || screenPosition.x < 0f || 
        screenPosition.y > resolutionY || screenPosition.y < 0f) {

        transform.position = Vector3.SmoothDamp(transform.position, canvas.transform.TransformPoint(Vector3.zero), ref velocity, smoothTime);
    }

    cardChoiceCG.alpha = Math.Abs((1f / distanceToFadeIn) * (screenPosition.x - (resolutionX / 2)));
}

public void OnPointerDown(PointerEventData eventData) {

    RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, eventData.position, canvas.worldCamera, out Vector2 pos);
    offset = transform.position - canvas.transform.TransformPoint(pos);
}


public void OnDrag(PointerEventData eventData) {

    RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, eventData.position, canvas.worldCamera, out Vector2 movePos);
    transform.position = canvas.transform.TransformPoint(movePos) + offset;
}

}

【问题讨论】:

  • 你可以在画布中添加一个空的游戏对象并将其用作 SmoothDump 函数中的目标,也许问题是画布本身。

标签: c# unity3d


【解决方案1】:

解决了! transform.position = Vector3.SmoothDamp(transform.position, canvas.transform.TransformPoint(Vector3.zero), ref velocity, smoothTime); 在 if 语句中,所以它只在卡片的中心不在屏幕上时才有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多