Simple Ball Controller with Jump Multiplier – How to correctly use Update and FixedUpdate


using UnityEngine;
[RequireComponent(typeof(Rigidbody))]

public class Mover : MonoBehaviour
{

[SerializeField] private float _moveSpeed = 10f;
[SerializeField] private float _jumpMultiplier = 100f;

private Rigidbody _rigidbody;

private Vector3 _movementForce;
private bool _jump;

void Awake() {_rigidbody = GetComponent<Rigidbody>();}

//Update is called once per frame
void Update()
{
	float horizontal = Input.GetAxis("Horizontal");
	float vertical = Input.GetAxis("Vertical");

	_movementForce = new Vector3(horizontal, 0f, vertical);
	
	if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
	{
		_jump = true;
	}
}

//how to check grounding will vary dramatically by game/project
//here we just assume you are (usually raycasts or sometimes colliders/other methods
private bool IsGrounded() => true;

//update is called every x milliseconds (adjustable in project settings)
private void FixedUpdate()
{
	Move();
	Jump();
}

private void Move()
{
	_rigidbody.AddForce(_movementForce * _moveSpeed);
}

private void Jump()
{
	if (_jump)
	{
		_rigidbody.AddForce(Vector3.up * _jumpMultiplier);
		_jump = false;
	}
}
}