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.
95 lines
2.6 KiB
95 lines
2.6 KiB
using UnityEngine; |
|
|
|
public class PlayerController : MonoBehaviour |
|
{ |
|
/************************************************************************** |
|
* MOVEMENT VARIABLES |
|
*************************************************************************/ |
|
[SerializeField] private int speed; |
|
[SerializeField] private Animator anim; |
|
[SerializeField] private SpriteRenderer playerSprite; |
|
|
|
private PlayerControls playerControls; |
|
private Rigidbody rb; |
|
private Vector3 movement; |
|
|
|
private const string IS_WALK_PARAM = "IsWalk"; |
|
|
|
/************************************************************************** |
|
* BATTLE DETECTION VARIABLES |
|
*************************************************************************/ |
|
[SerializeField] private LayerMask grassLayer; |
|
[SerializeField] private int stepsInGrass; |
|
|
|
private bool movingInGrass; |
|
private float stepTimer; |
|
|
|
private const float timePerStep = 0.5f; |
|
|
|
|
|
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) |
|
{ |
|
rb.MovePosition |
|
( |
|
transform.position + movement * speed * Time.fixedDeltaTime |
|
); |
|
} |
|
|
|
/***** 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 |
|
} |
|
} |
|
|
|
} |
|
}
|
|
|