- Home /
Player jump only on the Y axis and ignore other axis velocity
Hello, i have some problem with a script im writing, when i press the jump button, even if im going forward, backward etc.... the player will lose all velocity and jump only on the y axis, i would like him to keep other axis velocity so you can run then jump and the player will continue his initial motion while jumping. i use a rigidbody. here is my code: using UnityEngine; using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6.0f;
public float jumpSpeed = 5.0f;
public float SlopeAngle = 45;
private Vector3 moveDirection = Vector3.zero;
private Vector3 desiredDirection;
private bool isGrounded = false;
private bool isJumping = false;
private bool Sliding = false;
private Rigidbody rigidBody;
private CapsuleCollider capsule;
void Start()
{
rigidBody = GetComponent<Rigidbody>();
capsule = GetComponent<CapsuleCollider>();
}
void FixedUpdate()
{
Debug.Log(isGrounded);
Grounding();
Movement();
}
void Movement()
{
if (isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal") * 0.7f, 0, Input.GetAxis("Vertical"));
if (moveDirection.z <= 0f) { moveDirection.z = Input.GetAxis("Vertical") * 0.7f; }
moveDirection *= speed;
desiredDirection = transform.localRotation * moveDirection;
rigidBody.AddForce(desiredDirection, ForceMode.Impulse);
}
if (Input.GetButton("Jump") && isGrounded == true)
{
rigidBody.AddForce(Vector3.up * jumpSpeed, ForceMode.VelocityChange);
isGrounded = false;
isJumping = true;
}
}
void Grounding()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, 0.1f ))
{
float angle = Vector3.Angle(Vector3.up, hit.normal);
if(angle > SlopeAngle)
{
isGrounded = true;
Sliding = true;
}
else
{
isGrounded = true;
Sliding = false;
}
}
}
}
Comment
Answer by jeffbori · May 14, 2019 at 08:56 PM
even if i change ForceMode.VelocityChange to ForceMode.Impulse, the player still jump staight up ignoring the direction i was going