c#
// public's
public float speed;
public float jumpForce;
// private's
private Rigidbody rb;
private bool isJumping = false;
private bool isGrounded = true;
void Start()
{
transform.position = new Vector3(0,1,0);
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (!isJumping && isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
else
{
Move();
}
}
}
private void Move()
{
Vector3 direction = Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
direction += transform.forward;
}
if (Input.GetKey(KeyCode.S))
{
direction -= transform.forward;
}
if (Input.GetKey(KeyCode.D))
{
direction += transform.right;
}
if (Input.GetKey(KeyCode.A))
{
direction -= transform.right;
}
direction.Normalize();
if (Input.GetKey(KeyCode.LeftShift))
{
rb.velocity = direction * (speed * 2);
}
else
{
rb.velocity = direction * speed;
}
}
private void Jump()
{
if (isJumping == false)
{
isJumping = true;
rb.AddForce((Vector3.up+(rb.velocity/5)) * jumpForce, ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
if(isJumping == true)
{
isJumping= false;
}
}
private void OnCollisionExit(Collision collision)
{
isGrounded= false;
}
private void OnCollisionStay(Collision collision)
{
isGrounded= true;
}