- Home /
Question by
tobydedrick · Nov 11, 2020 at 06:18 PM ·
rigidbodyrigidbody.addforcerigidbody.velocity
How do I stop my Player (controlled by RigidBody) stopping after jumping?
When I jump using RigidBody.AddForce
, as soon as my player touches the ground plane (through detecting it with a raycast) its velocity is instantly made (0, 0, 0). I've no idea why this happens or if this is a common problem with rigidbody player movement. Does anyone know why this happens?
Below is the player's movement script:
[Header("Movement Settings")]
public float playerMovementForce;
public float playerSpeed;
public float jumpForce;
public float jumpHeight;
public float gravity;
[Header("Movement Monitoring")]
public Vector3 velocity;
public float vectorAdjustedVelocity;
public bool isGrounded;
[Header("Other")]
public Collider playerCollider;
public LayerMask groundCheckLayer;
private Rigidbody rb;
Vector3 x, z;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
Physics.gravity = new Vector3(0f, -gravity, 0f);
}
// Update is called once per frame
void Update()
{
x = transform.right * Input.GetAxisRaw("Horizontal");
z = transform.forward * Input.GetAxisRaw("Vertical");
velocity = rb.velocity;
}
void FixedUpdate()
{
Movement();
}
void Movement()
{
Vector3 moveBy = (x + z).normalized * playerMovementForce;
if (Mathf.Sqrt(
Mathf.Pow(rb.velocity.x, 2) +
Mathf.Pow(rb.velocity.z, 2)
) >= playerSpeed)
{
moveBy = new Vector3 (0f, 0f, 0f);
}
vectorAdjustedVelocity = Mathf.Sqrt(Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2));
rb.AddForce(moveBy);
Ray groundCheck = new Ray(transform.position, transform.TransformDirection(Vector3.down));
RaycastHit hitInfo;
if (Physics.Raycast(groundCheck, out hitInfo, jumpHeight, groundCheckLayer))
{
Debug.DrawLine(groundCheck.origin, hitInfo.point, Color.red);
isGrounded = true;
}
else
{
Debug.DrawLine(groundCheck.origin, groundCheck.origin + groundCheck.direction * jumpHeight, Color.green);
isGrounded = false;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(new Vector3(0f, jumpForce, 0f), ForceMode.Impulse);
}
}
Comment