- Home /
How do I make my character jump?
I'm not good at scripting, but I've managed to cobble together a script that works for 3d movement where the character rotates to face the direction of travel. However, I can't figure out how to make the character jump. Can anyone help?
Here's the script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Movement2 : MonoBehaviour { [SerializeField] private Rigidbody _rb;
[SerializeField] private float _speed = 5;
[SerializeField] private float _turnSpeed = 360;
private Vector3 _input;
public Animator animator;
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
GatherInput();
Look();
}
void FixedUpdate()
{
Move();
}
void GatherInput()
{
var velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
_input = velocity;
animator.SetFloat("Speed", velocity.magnitude);
}
void Look()
{
if (_input != Vector3.zero)
{
var relative = (transform.position + _input) - transform.position;
var rot = Quaternion.LookRotation(relative, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, _turnSpeed * Time.deltaTime);
}
}
void Move()
{
_rb.MovePosition(transform.position + (transform.forward*_input.magnitude)* _speed * Time.deltaTime);
}
}
Answer by rh_galaxy · May 07 at 10:35 AM
When you have a RigidBody, the best thing would be to control its movement indirectly with forces, that way the objects movement are calculated and moved by itself and sliding along colliders correctly. To jump you would do
_rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); //or do
_rb.AddForce(Vector3.up * jumpVelocity, ForceMode.VelocityChange);
But to get it like you want you have to adjust Drag, Mass, Gravity and the jumpForce/Velocity which can be tricky.
At least you should try to control the velocity, and not do MovePosition()
_rb.velocity = _input;
Rotation can be done the way you do it now for a walking player, but if you want physics to be simulated you need to use AddTorque(), and Angular Drag.
Your answer
Follow this Question
Related Questions
3D coyote time 1 Answer
Rigidbody Controller Jump 0 Answers
How can I add air control to my 3d platformer's Character Controller? 0 Answers
Walker Boys Mario Clone Issue 0 Answers
How to position the jump animation with the object's body? 1 Answer