Hey there,
So I’m an amateur (and I stress amateur) trying to make a simple first-person controller for future game projects in C#. Unfortunately, because of my lack of any skills outside a beginner level, I’ve gone with pretty much the basics. Here is my script:
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
public float jumpVel = 10.0f;
public float distanceToTheGround;
void Start ()
{
distanceToTheGround = collider.bounds.extents.y;
}
bool IsGrounded ()
{
return Physics.Raycast(transform.position, -Vector3.up, distanceToTheGround + 0.1f);
}
void Update ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
float moveJump = Input.GetAxis ("Jump");
Vector3 forwardVel = transform.forward * speed * moveVertical;
Vector3 horizontalVel = transform.right * speed * moveHorizontal;
Vector3 jump = Vector3.up * jumpVel * moveJump;
if (IsGrounded ())
{
rigidbody.velocity = forwardVel + horizontalVel + jump;
}
else
{
rigidbody.velocity = forwardVel + horizontalVel;
}
}
}
But there are a lot of bugs here, most of which involve jumping. Basically, I’m not jumping at all and I can’t work out why. On top of that, because of the fact I’m using transform.forward & transform.right for the movement planes, facing up or down (I have a seperate mouselook script that works fine) causes the player to ‘fly’. I’ve tried using RigidbodyConstraints.FreezePositionY, but of course that prevents me from jumping even further, even if I try removing the constraint when space (the jump key) is pressed.
Is anyone able to tell me why these are occurring, and how to fix them?