I using CharacterController
and not using a Rigidbody
so I writing a script for downward velocity which is velocity=-9.81*(time) and I declare my initial velocity as 12. Supposing from this calculation, the max height it can reach from the equation is roughly 6.7891 unit on y axis. By using the formulae
distance travel=initial velocity*(time)-0.5g*(time)^2
,differentiate this w.r.t time, getting time=u/g=12/9.81=1.223
, then max distance travel=12*(1.223)-0.5*(-9.81)*(1.223)^2=7.339
but from the coordinate below, can clearly seen the max distance travel before falling down is 13.2803unit--0.5499unit=13.8302unit
? This is far exceed calculated value, wonder what went wrong?
Initial coordinate of y on ground=-0.5499
approximate final coordinate of y=13.2803
using UnityEngine;
public class NewPlayerMovement : MonoBehaviour
{
public CharacterController Controller;
//speed of the character
public float Speed = 12f;
// earth gravitational value
public float Gravity = -9.81f;
Vector3 velocity;
//hit point of character
float hp = 90;
bool Grounded = true;
public void OnControllerColliderHit(ControllerColliderHit hit)
{
Grounded = true;
hp -= velocity.magnitude;
velocity.y = 0;
Debug.Log(hp);
}
public void OnControllerColliderExit(ControllerColliderHit hit)
{
Grounded = false;
}
public void Checkstatus()
{
if(Grounded==false)
{
velocity.y += 0.5f * Gravity * Time.deltaTime;
}
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
Controller.Move(move * Speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && velocity.y == 0)
{
velocity.y = 12;
Grounded = false;
}
//check if it grounded
Checkstatus();
Controller.Move(velocity * Time.deltaTime);
}
}
v.y += g * dt
? I.e., without the0.5 *
(assuming g is negative). \$\endgroup\$0.5 g t^2
is for the travel. But withv.y += g * dt
you calculate the velocity. Thenvelocity * Time.deltaTime
is a travel again. Note that we are working with linear approximations and summing is not the same as integrating. The velocity is constant during a given time step in the game. So the velocity curve looks like stairs, not like a sequence of infinitesimal small triangles approximating a smooth curve where the 0.5 comes from (baseline * height / 2). \$\endgroup\$