this is currently my code. The object moves at the desired speed but using [rb.velocity = movement * speed] if it jump it remains glued to the ground. I can’t understand how I can fix things.
private Vector3 movement;
private float speed = 3;
public bool isGrounded;
void Start()
rb = GetComponent<Rigidbody>();
void Update()
{
float Horizontal = Input.GetAxis("Horizontal");
float Vertical = Input.GetAxis("Vertical");
movement = transform.right * Horizontal + transform.forward * Vertical;
float origMagnitude = movement.magnitude;
movement.y = 0.0f;
movement = movement.normalized * origMagnitude;
if(isGrounded && Input.GetKeyDown(KeyCode.Space))
rb.AddForce((Vector3.up + movement) * JumpForce, ForceMode.Impulse);
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, rayDistance, layer)) isGrounded = true;
else isGrounded = false;
}
private void FixedUpdate ()
{
rb.velocity = movement * speed;
}
By doing movement.y = 0.0f and passing the entire movement Vector3 to your rb.velocity, you are basically denying your rigidbody physics on Y axis, this is what you should do:
using UnityEngine;
public class pappaController : MonoBehaviour
{
public float speed = 10f;
public float jumpForce = 5f;
public float rayDistance = 5f;
public LayerMask WhatIsGround;
private Rigidbody rb;
private Vector3 movement;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float Horizontal = Input.GetAxis("Horizontal");
float Vertical = Input.GetAxis("Vertical");
movement = (transform.right * Horizontal + transform.forward * Vertical) * speed; // multiply by speed and you got your movement ready
// removed this part, don't know what was the point of it
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
RaycastHit hit;
isGrounded = Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, rayDistance, WhatIsGround);
}
private void FixedUpdate()
{
// y axis -> rb.velocity.y
rb.velocity = new Vector3(movement.x , rb.velocity.y, movement.z);
}
}