lucid-super-dream/Assets/Player/MovePlayer.cs

65 lines
1.6 KiB
C#
Raw Normal View History

2021-01-04 17:49:48 +01:00
using System;
using Ktyl.Util;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using PlayerInput = Input.PlayerInput;
public class MovePlayer : MonoBehaviour
{
[SerializeField] private SerialFloat speed;
[SerializeField] private RectOffset extents;
2021-01-09 17:18:29 +01:00
[SerializeField] private float lerpAmount = 0.95f;
[SerializeField] private SerialFloat horizontalInput;
2021-01-04 17:49:48 +01:00
private PlayerInput _input;
private Vector2 _currentInput;
private Transform _transform;
2021-01-09 17:18:29 +01:00
2021-01-04 17:49:48 +01:00
private Rect _pos;
2021-01-09 17:18:29 +01:00
private float _yPos;
private float _zPos;
2021-01-04 17:49:48 +01:00
private void Awake()
{
_transform = transform;
2021-01-09 17:18:29 +01:00
_yPos = _transform.localPosition.y;
_zPos = _transform.localPosition.z;
2021-01-04 17:49:48 +01:00
}
private void OnEnable()
{
_input ??= new PlayerInput();
_input.Enable();
_input.Default.Move.performed += DoMove;
}
private void OnDisable()
{
_input.Disable();
_input.Default.Move.performed -= DoMove;
}
private void Update()
{
_transform.localPosition += (Vector3) _currentInput * speed * Time.deltaTime;
2021-01-09 17:18:29 +01:00
2021-01-04 17:49:48 +01:00
_transform.localPosition = new Vector3(
Mathf.Clamp(_transform.localPosition.x, extents.left, extents.right),
2021-01-09 17:18:29 +01:00
_yPos,
_zPos);
horizontalInput.Value = _currentInput.x;
2021-01-04 17:49:48 +01:00
}
private void DoMove(InputAction.CallbackContext context)
{
var value = context.ReadValue<Vector2>();
2021-01-09 17:18:29 +01:00
_currentInput = Vector2.Lerp(_currentInput, value, lerpAmount);
2021-01-04 17:49:48 +01:00
}
}