I'm surprised that this issue is nowhere to be found on these forums... Well at least when I searched. So, on my setup I have created a cube and applied a Rigidbody to the object with the following C# script:
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
Rigidbody movement;
float distToGround;
bool doubleJump=false;
void Start() {
movement = GetComponent<Rigidbody>();//Initialize movement as their rigidbody
distToGround = GetComponent<Collider>().bounds.extents.y;//Get the distance from the user to the ground
}
void Update() {
/*If they aren't moving the horizontal or vertical axes, cancel out their velocity.*/
if(Input.GetAxis("Horizontal")==0&&isGrounded()) movement.velocity = new Vector3(0, movement.velocity.y, movement.velocity.z);
if(Input.GetAxis("Vertical")==0&&isGrounded()) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, 0);
/*Horizontal Movement*/
if(Input.GetAxis("Horizontal")>0) movement.velocity = new Vector3(5, movement.velocity.y, movement.velocity.z);
if(Input.GetAxis("Horizontal")<0) movement.velocity = new Vector3(-5, movement.velocity.y, movement.velocity.z);
/*Vertical Movement*/
if(Input.GetAxis("Vertical")>0) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, 5);
if(Input.GetAxis("Vertical")<0) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, -5);
/*Jumping and Falling*/
if(Input.GetButtonDown("Jump")&&isGrounded()) Jump();//For jumping
if(!isGrounded()) {//If they are in the air
Gravity();//They're free... free falling!
if(Input.GetButtonDown("Jump")&&doubleJump) {//If they jumped once
if(Input.GetAxis("Horizontal")==0&&Input.GetAxis("Vertical")==0) {//And they aren't moving
Jump(); doubleJump=false;//Double Jump
}
else if(Input.GetAxis("Horizontal")>0) {//Otherwise, if they're trying to dodge right...
movement.AddForce(10, 0, 0, ForceMode.Impulse); doubleJump=false;//Dodge Right!
print("Dodged!");
}
}
}
if(isGrounded()) doubleJump=true;//Reset Double Jump bool
}
void Gravity() {
movement.AddForce(movement.velocity.x, -20, movement.velocity.z);//Simply push them down consistently
}
void Jump() {
movement.velocity = Vector3.zero;
movement.velocity = new Vector3(movement.velocity.x, 15, movement.velocity.z);//Simply push them up consistently
}
bool isGrounded() {
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1f);//returns whether or not the object is grounded
}
}
Everything works fine in this code except for the code that allows them to dodge mid-air. Whenever I perform a jump successfully and jump again without pressing an arrow key, it double jumps as expected.
Whenever I dodge right, I noticed that the object seemed to "teleport" or "skip" in the direction a bit instead of actually applying the force. The more force I apply, the more it skips.
Why is my code executing it in this way? Is it a glitch with Rigidbody or is it a problem with my code that I'm not realizing?