I have a FPS movement script that I created that has a jump function that looks like this
public void Jump()
{
if (jumpAble && grounded)
{
jumpAble = false;
gameObject.GetComponent<Rigidbody>().velocity = (Vector3.up * jumpForce * Time.deltaTime);
}
}
For some reason, this does not make the player jump. However, replacing the .velocity =... to
gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce * Time.deltaTime, ForceMode.VelocityChange);
makes the player jump. Why is this? I'm under the impression that the two are essentially the same thing, but is there a slight difference?
Also, not sure if it affects the function, but this is the whole script
public class Player_Movement : MonoBehaviour
{ public Transform camera;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public bool grounded;
public GameObject joystick;
public bool isWalking = false;
public bool isRunning = false;
public float walkForce = 12f;
public float runForce = 30f;
public float jumpForce;
public bool jumpAble = true;
public GameObject playerRotationHandler;
public float cameraTouchSensitivity;
public Animator animator;
// Update is called once per frame
void Update()
{
grounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (grounded)
{
jumpAble = true;
}
Vector3 direction = joystick.GetComponent<Joystick>().inputDirection.x * transform.right + joystick.GetComponent<Joystick>().inputDirection.y * transform.forward;
if (isRunning)
{
gameObject.GetComponent<Rigidbody>().velocity = (direction * runForce * Time.deltaTime);
}
else if (isWalking)
{
gameObject.GetComponent<Rigidbody>().velocity = (direction * walkForce * Time.deltaTime);
}
else
{
gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
public void Jump()
{
if (jumpAble && grounded)
{
jumpAble = false;
gameObject.GetComponent<Rigidbody>().velocity = (Vector3.up * jumpForce * Time.deltaTime);
gameObject.GetComponent<Rigidbody>().AddForce (Vector3.up * jumpForce * Time.deltaTime, ForceMode.VelocityChange);
}
}
public void Rotate(float xMoveValue, float yMoveValue)
{
float xRotation = Mathf.Atan2(yMoveValue, cameraTouchSensitivity) * Mathf.Rad2Deg;
float yRotation = Mathf.Atan2(xMoveValue, cameraTouchSensitivity) * Mathf.Rad2Deg;
playerRotationHandler.transform.Rotate(xRotation, 0, 0);
transform.Rotate(0, yRotation, 0, Space.World);
if (playerRotationHandler.transform.localEulerAngles.x < 300 && playerRotationHandler.transform.localEulerAngles.x > 60)
{
if (xRotation < 0)
{
playerRotationHandler.transform.localEulerAngles = new Vector3(300, playerRotationHandler.transform.localEulerAngles.y, 0);
}
if (xRotation > 0)
{
playerRotationHandler.transform.localEulerAngles = new Vector3(60, playerRotationHandler.transform.localEulerAngles.y, 0);
}
}
}
}
velocity
or useAddForce
. The physics engine will do so automatically when changing the position by the current velocity. \$\endgroup\$