You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.6 KiB

2 months ago
using UnityEngine;
public class PlayerController : MonoBehaviour
{
2 months ago
/**************************************************************************
* MOVEMENT VARIABLES
*************************************************************************/
2 months ago
[SerializeField] private int speed;
[SerializeField] private Animator anim;
[SerializeField] private SpriteRenderer playerSprite;
2 months ago
2 months ago
private PlayerControls playerControls;
private Rigidbody rb;
private Vector3 movement;
private const string IS_WALK_PARAM = "IsWalk";
2 months ago
/**************************************************************************
* BATTLE DETECTION VARIABLES
*************************************************************************/
[SerializeField] private LayerMask grassLayer;
[SerializeField] private int stepsInGrass;
private bool movingInGrass;
private float stepTimer;
private const float timePerStep = 0.5f;
2 months ago
private void Awake()
{
playerControls = new PlayerControls();
}
private void OnEnable()
{
playerControls.Enable();
}
private void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
private void Update()
{
float x = playerControls.Player.Move.ReadValue<Vector2>().x;
float z = playerControls.Player.Move.ReadValue<Vector2>().y;
movement = new Vector3(x, 0, z).normalized;
anim.SetBool(IS_WALK_PARAM, movement != Vector3.zero);
if(x != 0 && x < 0)
{
playerSprite.flipX = true;
}
if(x != 0 && x > 0)
{
playerSprite.flipX = false;
}
}
private void FixedUpdate()
{
if (movement != null)
{
2 months ago
rb.MovePosition
(
transform.position + movement * speed * Time.fixedDeltaTime
);
2 months ago
}
2 months ago
/***** BATTLE DETECTION *****/
// Battle occurs after a random number of steps in a grass collider
// https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Collider[] colliders = Physics.OverlapSphere(transform.position, 1, grassLayer);
movingInGrass = colliders.Length != 0 && movement != Vector3.zero;
if (movingInGrass == true)
{
stepTimer += Time.fixedDeltaTime;
if (stepTimer > timePerStep)
{
stepsInGrass++;
stepTimer = 0;
// check to see if we have reached an encounter
// ->change the scene
}
}
2 months ago
}
}