Merge branch 'develop' into feature/movefix

This commit is contained in:
NguyenVanDat
2025-12-03 18:14:59 +07:00
+41 -9
View File
@@ -6,9 +6,9 @@ using UnityEngine.EventSystems;
public class Joystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
public float Horizontal { get { return SnapToDiscrete(input.x); } }
public float Vertical { get { return SnapToDiscrete(input.y); } }
public Vector2 Direction { get { return new Vector2(Horizontal, Vertical); } }
public float Horizontal { get { return input.x; } }
public float Vertical { get { return input.y; } }
public Vector2 Direction { get { return input; } }
public float HandleRange
{
@@ -78,8 +78,8 @@ public class Joystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPoint
HandleInput(input.magnitude, input.normalized, radius, cam);
handle.anchoredPosition = input * radius * handleRange;
// Send event when value changes to -1 or 1
Vector2 currentSnapped = new Vector2(Horizontal, Vertical);
// Send event when value changes significantly (for 360-degree smooth movement)
Vector2 currentSnapped = new Vector2(SnapToDiscrete(input.x), SnapToDiscrete(input.y));
if ((currentSnapped.x == -1 || currentSnapped.x == 1 || currentSnapped.y == -1 || currentSnapped.y == 1) &&
currentSnapped != previousSnappedInput)
{
@@ -95,8 +95,9 @@ public class Joystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPoint
{
if (magnitude > deadZone)
{
if (magnitude > 1)
input = normalised;
// Normalize to ensure speed is always 1 (full speed) or 0 (no movement)
// This keeps 360-degree direction but binary speed
input = normalised;
}
else
input = Vector2.zero;
@@ -110,10 +111,41 @@ public class Joystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPoint
input = new Vector2(0f, input.y);
}
private Vector2 SnapTo8Directions(Vector2 input)
{
// Snap to 8 directions: N, NE, E, SE, S, SW, W, NW
// Returns values of -1, 0, or 1 for each axis
if (input.magnitude < 0.4f)
return Vector2.zero;
// Calculate angle in degrees (0 = up/North, 90 = right/East)
float angle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg;
// Normalize angle to 0-360
if (angle < 0) angle += 360f;
// Snap to 8 directions (every 45 degrees)
// 0° = N, 45° = NE, 90° = E, 135° = SE, 180° = S, 225° = SW, 270° = W, 315° = NW
float snappedAngle = Mathf.Round(angle / 45f) * 45f;
// Convert back to direction vector
float rad = snappedAngle * Mathf.Deg2Rad;
Vector2 snapped = new Vector2(Mathf.Sin(rad), Mathf.Cos(rad));
// Ensure values are exactly -1, 0, or 1
snapped.x = Mathf.Round(snapped.x);
snapped.y = Mathf.Round(snapped.y);
return snapped;
}
private float SnapToDiscrete(float value)
{
// Snap to -1, 1, or 0
if (value == 0)
// Snap to -1, 1, or 0 for 8-directional movement
// Use a small threshold to ensure diagonal movement works
const float threshold = 0.1f;
if (Mathf.Abs(value) < threshold)
return 0;
return value > 0 ? 1 : -1;
}