using UnityEngine; using UnityEngine.InputSystem; namespace InfiniteWorld { public class SimplePlayerInputMover : MonoBehaviour { [SerializeField] private float moveSpeed = 5f; private InputAction moveAction; private Rigidbody2D rb; private Vector2 moveInput; private void Awake() { rb = GetComponent(); if (rb == null) { rb = gameObject.AddComponent(); } ConfigurePhysics(); EnsureVisual(); moveAction = new InputAction("Move", InputActionType.Value); moveAction.AddCompositeBinding("2DVector") .With("Up", "/w") .With("Down", "/s") .With("Left", "/a") .With("Right", "/d"); moveAction.AddCompositeBinding("2DVector") .With("Up", "/upArrow") .With("Down", "/downArrow") .With("Left", "/leftArrow") .With("Right", "/rightArrow"); moveAction.AddBinding("/leftStick"); } private void OnEnable() { moveAction?.Enable(); } private void OnDisable() { moveAction?.Disable(); } private void OnDestroy() { moveAction?.Dispose(); } private void Update() { if (moveAction == null) { return; } moveInput = moveAction.ReadValue().normalized; if (moveInput.x != 0f) { Vector3 scale = transform.localScale; scale.x = Mathf.Abs(scale.x) * Mathf.Sign(moveInput.x); transform.localScale = scale; } } private void FixedUpdate() { if (rb == null) { return; } Vector2 target = rb.position + moveInput * (moveSpeed * Time.fixedDeltaTime); rb.MovePosition(target); } private void ConfigurePhysics() { rb.gravityScale = 0f; rb.freezeRotation = true; rb.interpolation = RigidbodyInterpolation2D.Interpolate; rb.collisionDetectionMode = CollisionDetectionMode2D.Continuous; CapsuleCollider2D collider = GetComponent(); if (collider == null) { collider = gameObject.AddComponent(); } collider.direction = CapsuleDirection2D.Vertical; collider.size = new Vector2(0.55f, 0.8f); collider.offset = new Vector2(0f, -0.05f); } private void EnsureVisual() { SpriteRenderer renderer = GetComponent(); if (renderer == null) { renderer = gameObject.AddComponent(); } renderer.sprite = ProceduralWorldArt.CreatePlayerSprite(); renderer.sortingOrder = 10; } } }