using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Text; public class AngleCalculator : MonoBehaviour { public GameObject axis2; public GameObject needle; public TMP_Text axis2AngleText; public TMP_Text sentAngleText; public GameObject point2; public GameObject arrowDown; public GameObject arrowUp; public string pcIPAddress = "169.254.47.171"; public int pcPort = 8888; private bool showIndicators = false; private float lastSendTime = 0f; public float sendInterval = 0.2f; // slower send rate private float previousAngle = -999f; // to prevent resending same value private UdpClient udpClient; void Start() { HideIndicators(); udpClient = new UdpClient(); Debug.Log("AngleCalculator initialized and UDP client ready."); } void Update() { if (!showIndicators) return; float angleWithAxis2 = CalculateAngleWithAxis2(); if (axis2AngleText != null) { axis2AngleText.text = $"{angleWithAxis2:F1}°"; axis2AngleText.gameObject.SetActive(true); } if (arrowUp && arrowDown) { if (angleWithAxis2 < 0) { arrowUp.SetActive(true); arrowDown.SetActive(false); } else { arrowUp.SetActive(false); arrowDown.SetActive(true); } } if (Time.time - lastSendTime >= sendInterval) { float clampedAngle = Mathf.Clamp(angleWithAxis2, 0f, 33f); if (Mathf.Abs(clampedAngle - previousAngle) > 0.05f) { SendAngleToPC(clampedAngle); previousAngle = clampedAngle; if (sentAngleText != null) sentAngleText.text = $"Sent to PC: {clampedAngle:F1}°"; Debug.Log($"Sent to PC: {clampedAngle:F1}°"); } lastSendTime = Time.time; } } private void SendAngleToPC(float angle) { if (udpClient == null) return; string message = angle.ToString("F1"); try { byte[] data = Encoding.UTF8.GetBytes(message); udpClient.Send(data, data.Length, pcIPAddress, pcPort); } catch (System.Exception e) { Debug.LogError("UDP Send Error: " + e.Message); } } void OnApplicationQuit() { if (udpClient != null) { udpClient.Close(); udpClient = null; } } public void ToggleIndicators() { showIndicators = !showIndicators; if (!showIndicators) HideIndicators(); } private void HideIndicators() { if (arrowUp) arrowUp.SetActive(false); if (arrowDown) arrowDown.SetActive(false); if (axis2AngleText) axis2AngleText.gameObject.SetActive(false); if (sentAngleText) sentAngleText.text = ""; } private float CalculateAngleWithAxis2() { if (needle == null || axis2 == null || point2 == null) return 0f; Vector3 needleUp = needle.transform.up; Vector3 axis2Up = axis2.transform.up; float angle = Vector3.Angle(needleUp, axis2Up); if (point2.transform.position.y < axis2.transform.position.y) { angle = -angle; } return angle; } }