93 lines
2.8 KiB
C#
93 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
namespace Player
|
|
{
|
|
[RequireComponent(typeof(Rigidbody2D))]
|
|
public class Movement : MonoBehaviour
|
|
{
|
|
[SerializeField] private float runSpeed;
|
|
[SerializeField] private float springPower;
|
|
[SerializeField] private SpriteRenderer spriteRenderer;
|
|
[SerializeField] private float turnDelay;
|
|
[SerializeField] private InputActionReference interactReference;
|
|
|
|
private bool _onSpring;
|
|
private Rigidbody2D _rb;
|
|
private bool _grounded = true;
|
|
private bool _facingLeft;
|
|
private float _turnDelayTimer;
|
|
private bool _interact;
|
|
|
|
private void Awake()
|
|
{
|
|
_rb = GetComponent<Rigidbody2D>();
|
|
InputSystem.actions.FindActionMap("UI").Disable();
|
|
InputSystem.actions.FindActionMap("Player").Enable();
|
|
interactReference.action.performed += HandleInteraction;
|
|
interactReference.action.canceled += HandleInteraction;
|
|
}
|
|
|
|
private void HandleInteraction(InputAction.CallbackContext obj)
|
|
{
|
|
_interact = obj.ReadValueAsButton();
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
_turnDelayTimer += Time.deltaTime;
|
|
spriteRenderer.flipX = !_facingLeft;
|
|
Debug.Log($"{_onSpring} {_interact}");
|
|
if (_onSpring && _interact)
|
|
{
|
|
_onSpring = false;
|
|
_grounded = false;
|
|
_rb.linearVelocityX = 0;
|
|
_rb.AddForce(Vector2.up * springPower, ForceMode2D.Impulse);
|
|
}
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
if (_grounded)
|
|
{
|
|
_rb.linearVelocityX = _facingLeft ? -runSpeed : runSpeed;
|
|
}
|
|
}
|
|
|
|
private void OnTriggerEnter2D(Collider2D other)
|
|
{
|
|
if (other.gameObject.layer == LayerMask.NameToLayer("Spring"))
|
|
_onSpring = true;
|
|
}
|
|
|
|
private void OnTriggerExit2D(Collider2D other)
|
|
{
|
|
if (other.gameObject.layer == LayerMask.NameToLayer("Spring"))
|
|
{
|
|
_onSpring = false;
|
|
}
|
|
}
|
|
|
|
private void OnCollisionStay2D(Collision2D other)
|
|
{
|
|
if (_turnDelayTimer < turnDelay) return;
|
|
if (other.gameObject.layer == LayerMask.NameToLayer("Spring")) return;
|
|
var contacts = new List<ContactPoint2D>();
|
|
other.GetContacts(contacts);
|
|
foreach(var c in contacts)
|
|
{
|
|
var x = c.normal.x;
|
|
if (Mathf.Abs(x) > 0.1f)
|
|
{
|
|
_facingLeft = !_facingLeft;
|
|
_turnDelayTimer = 0f;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|