Skip to content

Instantly share code, notes, and snippets.

@toshikaz55
Last active December 24, 2015 23:59
Show Gist options
  • Save toshikaz55/6884659 to your computer and use it in GitHub Desktop.
Save toshikaz55/6884659 to your computer and use it in GitHub Desktop.
UnityでiOS、Android用にジョイスティックを追加した時にLocomotion で操作するには、Joystickを使う。
using UnityEngine;
using System.Collections;
public class JoystickToEvents : MonoBehaviour
{
public static void Do(Transform root, Transform camera, ref float speed, ref float direction)
{
Vector3 rootDirection = root.forward;
float horizontal;
float vertical;
if ( Application.platform == RuntimePlatform.IPhonePlayer
|| Application.platform == RuntimePlatform.Android ) {
Joystick joystick;
GameObject directionObject = GameObject.Find("Joystick");
joystick = directionObject.GetComponent<Joystick>();
horizontal = joystick.position.x;
vertical = joystick.position.y;
} else {
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
}
Vector3 stickDirection = new Vector3(horizontal, 0, vertical);
// Get camera rotation.
Vector3 CameraDirection = camera.forward;
CameraDirection.y = 0.0f; // kill Y
Quaternion referentialShift = Quaternion.FromToRotation(Vector3.forward, CameraDirection);
// Convert joystick input in Worldspace coordinates
Vector3 moveDirection = referentialShift * stickDirection;
Vector2 speedVec = new Vector2(horizontal, vertical);
speed = Mathf.Clamp(speedVec.magnitude, 0, 1);
if (speed > 0.01f) {// dead zone
Vector3 axis = Vector3.Cross(rootDirection, moveDirection);
direction = Vector3.Angle(rootDirection, moveDirection) / 180.0f * (axis.y < 0 ? -1 : 1);
} else {
direction = 0.0f;
}
}
}
@toshikaz55
Copy link
Author

Standard Assets(Mobile)のJoystick.jsをStandardAssetsフォルダに入れればC#からも見られるようになり、コンパイルが通る

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment