Files
ScienceLab.FrictionForce/Assets/Scripts/ScaleController.cs
2026-05-29 18:30:19 +03:00

105 lines
3.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScaleController : MonoBehaviour
{
[SerializeField] private Transform _pointer;
[SerializeField] private float _maxAngle = 1920f;
[SerializeField] private float _maxWeight = 15f;
[SerializeField] private float _rotationSpeed = 2f;
[SerializeField] private ObjectInfoDisplay _display;
private float _currentWeight = 0f;
private float _targetAngle = 0f;
private float _initialLocalZ;
private void Start()
{
if (_pointer != null)
_initialLocalZ = _pointer.localEulerAngles.z;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Target"))
{
Rigidbody rb = other.GetComponent<Rigidbody>();
if (rb != null)
{
_currentWeight += rb.mass;
_targetAngle = (_currentWeight / _maxWeight) * _maxAngle;
ObjectName objName = other.GetComponent<ObjectName>();
string displayName = objName != null ? objName.ukrainianName : other.gameObject.name;
if (_display != null)
_display.ShowInfo(displayName, rb.mass);
GameData.AddWeighed(displayName, rb.mass);
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Target"))
{
Rigidbody rb = other.GetComponent<Rigidbody>();
if (rb != null)
{
_currentWeight -= rb.mass;
_currentWeight = Mathf.Max(0f, _currentWeight);
_targetAngle = (_currentWeight / _maxWeight) * _maxAngle;
}
}
}
private void Update()
{
if (_currentWeight > 0 && !IsAnythingInTrigger())
{
_currentWeight = 0f;
_targetAngle = 0f;
}
if (_pointer != null)
{
float targetZ = _initialLocalZ + _targetAngle;
float currentZ = _pointer.localEulerAngles.z;
float diff = targetZ - currentZ;
if (Mathf.Abs(diff) <= 180f)
diff = Mathf.DeltaAngle(currentZ, targetZ);
float step = diff * Time.deltaTime * _rotationSpeed;
_pointer.RotateAround(GetPointerCenter(), _pointer.forward, step);
}
}
private bool IsAnythingInTrigger()
{
Collider triggerCollider = GetComponent<Collider>();
if (triggerCollider == null) return false;
Collider[] hits = Physics.OverlapBox(
triggerCollider.bounds.center,
triggerCollider.bounds.extents
);
foreach (Collider hit in hits)
{
if (hit.CompareTag("Target")) return true;
}
return false;
}
private Vector3 GetPointerCenter()
{
MeshFilter mf = _pointer.GetComponent<MeshFilter>();
if (mf != null)
return _pointer.TransformPoint(mf.mesh.bounds.center);
return _pointer.position;
}
}