using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public bool smoothTransition = true;
public float transitionSpeed = 10f;
public float transitionRotationSpeed = 500f;
Vector3 targetGridPos;
Vector3 prevTargetGridPos;
Vector3 targetRotation;
public void RotateLeft()
{
if (AtRest)
{
targetRotation -= Vector3.up * 90f;
}
}
public void RotateRight()
{
if (AtRest)
{
targetRotation += Vector3.up * 90f;
}
}
public void MoveForward()
{
if (AtRest)
{
targetGridPos += transform.forward;
}
}
bool AtRest
{
get
{
bool res =
Vector3.Distance(transform.position, targetGridPos) < 0.05f
&& Vector3.Distance(transform.eulerAngles, targetRotation) < 0.05f;
Debug.Log("AtRest: " + res); // Changes from false to true in the middle of the transition
return res;
}
}
void Start()
{
targetGridPos = Vector3Int.RoundToInt(transform.position);
}
void Update()
{
MovePlayer();
}
void MovePlayer()
{
bool canMove = true;
if (canMove)
{
prevTargetGridPos = targetGridPos;
Vector3 targetPosition = targetGridPos;
if (targetRotation.y > 270f && targetPosition.y <= 360f)
{
targetRotation.y = 0f;
}
else if (targetPosition.y < 0f)
{
targetRotation.y = 270f;
}
// Smooth transition is true so go straight to else
if (!smoothTransition)
{
transform.position = targetPosition;
transform.eulerAngles = targetRotation;
}
else
{
// Prints only once
Debug.Log("AtRest: " + AtRest);
Debug.Log("transform.position: " + transform.position);
Debug.Log("targetGridPos: " + targetGridPos);
Debug.Log("targetPosition: " + targetPosition);
Debug.Log("transform.eulerAngles: " + transform.eulerAngles);
Debug.Log("targetRotation: " + targetRotation);
Debug.Log(
"Vector3.Distance(transform.eulerAngles, targetRotation): "
+ Vector3.Distance(transform.eulerAngles, targetRotation)
);
// Prints thousands of times, values change from 0.75 to 0.9, but they shrink and rise randomly
Debug.Log(
"Vector3.Distance(transform.position, targetGridPos): "
+ Vector3.Distance(transform.position, targetGridPos)
);
transform.position = Vector3.MoveTowards(
transform.position,
targetPosition,
Time.deltaTime * transitionSpeed
);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
Quaternion.Euler(targetRotation),
Time.deltaTime * transitionRotationSpeed
);
}
}
else
{
targetGridPos = prevTargetGridPos;
}
}
}