unity script for player and new input system
unknown
csharp
4 years ago
1.6 kB
19
Indexable
using Game.Inputs;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Game.Logic.Entities.Player {
public class PlayerControl : MonoBehaviour {
[SerializeField] public float speed = 5;
private Rigidbody2D _rigidbody;
private Animator _animator;
private PlayerInputs _controls;
private InputAction _inputAction;
private Vector2 _movementPosition;
private void Awake() {
_controls = new PlayerInputs();
_rigidbody = GetComponent<Rigidbody2D>();
_animator = GetComponentInChildren<Animator>();
_inputAction = _controls.Player.Movement;
}
private void OnEnable() {
_controls.Enable();
_inputAction.performed += ctx => _movementPosition = ctx.ReadValue<Vector2>();
}
private void OnDisable() {
_controls.Disable();
}
private void Update() {
_animator.SetFloat("AxisHorizontal", _movementPosition.x);
_animator.SetFloat("AxisVertical", _movementPosition.y);
_animator.SetFloat("Speed", _movementPosition.SqrMagnitude());
}
protected void FixedUpdate() {
float h = _movementPosition.x;
float v = _movementPosition.y;
var targetInput = new Vector2(h, v);
moveThePlayer(targetInput);
}
private void moveThePlayer(Vector2 desiredDirection) {
var movement = transform.position * desiredDirection * Time.fixedDeltaTime * speed;
_rigidbody.MovePosition(movement);
}
}
}Editor is loading...