Untitled

mail@pastecode.io avatar
unknown
csharp
a month ago
2.8 kB
2
Indexable
Never
using UnityEngine;
using DG.Tweening;

public class MetalDetector : MonoBehaviour
{
    public Transform downPosition;
    public Transform upPosition;
    public float moveDuration = 1f;
    public float leftRightMoveDistance = 1f;
    public float leftRightMoveDuration = 1f;

    private bool isMoving = false;
    private bool isAnimatingUpDown = false;
    private bool isAnimatingLeftRight = false;
    private Tween currentUpDownTween;
    private Tween currentLeftRightTween;

    void Start()
    {
        // Initialize positions
        transform.position = upPosition.position;
    }

    public void StartDetection()
    {
        if (!isMoving)
        {
            // Stop any ongoing up-down animation
            currentUpDownTween?.Kill();

            // Animate down
            currentUpDownTween = transform.DOMove(downPosition.position, moveDuration).SetEase(Ease.OutQuad)
                .OnComplete(() =>
                {
                    isAnimatingUpDown = false;
                    StartLeftRightMovement();
                });
            isAnimatingUpDown = true;
        }
    }

    public void StopDetection()
    {
        if (isAnimatingUpDown)
        {
            // Stop the up-down animation and go back to the initial position
            currentUpDownTween.Kill();
            currentUpDownTween = transform.DOMove(upPosition.position, moveDuration).SetEase(Ease.OutQuad)
                .OnComplete(() =>
                {
                    isAnimatingUpDown = false;
                    isMoving = false;
                });
            isAnimatingUpDown = false;

            // Stop left-right movement if ongoing
            if (isAnimatingLeftRight)
            {
                currentLeftRightTween.Kill();
                isAnimatingLeftRight = false;
            }
        }
        else if (isAnimatingLeftRight)
        {
            // Stop left-right movement
            currentLeftRightTween.Kill();
            currentUpDownTween = transform.DOMove(upPosition.position, moveDuration).SetEase(Ease.OutQuad)
                .OnComplete(() =>
                {
                    isAnimatingUpDown = false;
                    isMoving = false;
                });
            isAnimatingUpDown = false;
            isAnimatingLeftRight = false;
        }
    }

    private void StartLeftRightMovement()
    {
        if (!isMoving)
        {
            // Animate left-right
            currentLeftRightTween = transform.DOMoveX(transform.position.x + leftRightMoveDistance, leftRightMoveDuration)
                .SetEase(Ease.Linear).SetLoops(-1, LoopType.Yoyo);
            isAnimatingLeftRight = true;
            isMoving = true;
        }
    }
}
Leave a Comment