Skip to content

Instantly share code, notes, and snippets.

@junaid109
Created February 23, 2023 10:59
Show Gist options
  • Save junaid109/4634c3e23c0087eb315db41488990161 to your computer and use it in GitHub Desktop.
Save junaid109/4634c3e23c0087eb315db41488990161 to your computer and use it in GitHub Desktop.
Simple Joystick Script Unity
using UnityEngine;
public class JoystickCameraController : MonoBehaviour
{
public float joystickSensitivity = 0.1f;
public float rotationSpeed = 5f;
public float zoomSpeed = 2f;
private Vector2 joystickInput;
private Transform cameraTransform;
private void Start()
{
cameraTransform = Camera.main.transform;
}
private void Update()
{
joystickInput.x = Input.GetAxisRaw("Horizontal");
joystickInput.y = Input.GetAxisRaw("Vertical");
if (joystickInput.magnitude > joystickSensitivity)
{
float angle = Mathf.Atan2(joystickInput.x, joystickInput.y) * Mathf.Rad2Deg;
// Round angle to the nearest 15 degrees
angle = Mathf.Round(angle / 15f) * 15f;
// Apply rotation
Vector3 eulerAngles = cameraTransform.eulerAngles;
eulerAngles.y += angle * rotationSpeed * Time.deltaTime;
cameraTransform.eulerAngles = eulerAngles;
}
// Zoom in/out with the joystick's vertical axis
float zoomAmount = Input.GetAxis("Mouse ScrollWheel") + Input.GetAxisRaw("Vertical");
cameraTransform.position += cameraTransform.forward * zoomAmount * zoomSpeed * Time.deltaTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment