using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour
{
bool grounded;
Vector3 moveDir, sideDir;
public float desiredHeightAboveGround;
private Vector3 previousPosition;
void Start()
{
}
private void Gravity()
{
transform.Translate(0, -.2f, 0);
}
private void isGrounded()
{
if (Physics.Raycast(transform.position, Vector3.down, 1.7f))
{
grounded = true;
}
else
{
grounded = false;
}
}
private void maintainHeight()
{
RaycastHit hit;
if(Physics.Raycast(transform.position, Vector3.down, out hit, Mathf.Infinity))
{
float currentHeightAboveGround = transform.position.y - hit.point.y;
float heightDifference = desiredHeightAboveGround - currentHeightAboveGround;
transform.Translate(0, heightDifference, 0);
}
}
public float GetVelocity()
{
Vector3 velocity = (transform.position - previousPosition) / Time.deltaTime;
return velocity.magnitude;
}
void Update()
{
previousPosition = transform.position;
isGrounded();
if (grounded == false)
{
Gravity();
}
else
{
maintainHeight();
}
moveDir = transform.forward;
sideDir = transform.right;
if (Input.GetKey(KeyCode.W))
{
transform.Translate(moveDir * .02f);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(-moveDir * .02f);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(sideDir * .02f);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(-sideDir * .02f);
}
print(Mathf.Round(GetVelocity()));
}
}
I switched from using rigidbodies to just manipulating the transform directly myself. It’s a bit of a hassle getting the transfrom to recognize it’s on ground, but I managed to do it. One thing I noticed however was that the transform goes a bit faster when traveling diagonal than straight. I’m a little embarrassed to admit it, but I went to ChatGPT for help, but its code didn’t help. Any suggestions on what I can do to fix this?