Skip to content

Instantly share code, notes, and snippets.

@enue
Last active May 9, 2018 20:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save enue/8c666b951920e7733e66eb5244a94e6e to your computer and use it in GitHub Desktop.
アナログスティックの入力を8方向にスナップする
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnapAngleSample : MonoBehaviour
{
private void Update()
{
var v = Input.GetAxis("Vertical");
var h = Input.GetAxis("Horizontal");
if (v * v + h * h > 0f)
{
// 8方向なので360/8=45。たとえば4方向にスナップしたいなら360/4で90を渡せばよい。
var snapped = SnapAngle(new Vector2(v, h), 45f * Mathf.Deg2Rad);
Debug.Log(snapped);
}
}
Vector2 SnapAngle(Vector2 vector, float angleSize)
{
var angle = Mathf.Atan2(vector.y, vector.x);
var index = Mathf.RoundToInt(angle / angleSize);
var snappedAngle = index * angleSize;
var magnitude = vector.magnitude;
return new Vector2(
Mathf.Cos(snappedAngle) * magnitude,
Mathf.Sin(snappedAngle) * magnitude);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment