Last active
February 19, 2020 17:42
-
-
Save dotaxis/97dade17bdb2c8d59ad4f2bc54374cf4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public static class InputHandler | |
{ | |
private static readonly Camera MainCam = Camera.main; | |
private static int _frameCount = -1; | |
private static Vector3 _lastPos = Vector3.zero; | |
private static Vector2 _delta = Vector2.zero; | |
public static Vector2 MouseDelta => _MouseDelta(); | |
private static Vector2 _MouseDelta() { | |
if (_frameCount == Time.frameCount) | |
return _delta / Time.unscaledDeltaTime; | |
if (Input.GetMouseButtonDown(0)) | |
_lastPos = MainCam.ScreenToViewportPoint(Input.mousePosition); | |
if (Input.GetMouseButton(0)) { | |
_delta = MainCam.ScreenToViewportPoint(Input.mousePosition) - | |
_lastPos; | |
_lastPos = MainCam.ScreenToViewportPoint(Input.mousePosition); | |
} | |
_frameCount = Time.frameCount; | |
return _delta / Time.unscaledDeltaTime; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using static InputHandler; | |
public class PlayerMovement : MonoBehaviour | |
{ | |
[SerializeField] private Vector2 sensitivity; | |
private float xMove, yMove; | |
private Rigidbody2D rb; | |
private void Start() { | |
rb = GetComponentInChildren<Rigidbody2D>(); | |
rb.centerOfMass = Vector2.zero; | |
rb.inertia = 1; | |
} | |
private void FixedUpdate() { | |
var angles = rb.transform.eulerAngles; | |
angles.z = Mathf.Clamp( | |
angles.z > 180 ? angles.z - 360 : angles.z, | |
-45, | |
45 | |
); | |
rb.transform.eulerAngles = angles; | |
rb.AddForce(new Vector2(xMove, yMove)); | |
rb.AddTorque(Mathf.Abs(xMove) > 0 ? xMove : -angles.z * 2f); | |
} | |
private void Update() { | |
if (Input.GetMouseButton(0)) { | |
xMove = MouseDelta.x * 10f * sensitivity.x; | |
yMove = MouseDelta.y * 16f * sensitivity.y; | |
} else | |
xMove = yMove = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment