- Home /
how to not move on the x axis while not jumping
I'm just seriously tired of the simple fact that I can't stop my character controller from jumping ahead. I'm trying to make it not move on the x axis while it is jumping.
using UnityEngine;
using System.Collections;
public class ControllerScript : MonoBehaviour {
// Use this for initialization
CharacterController controller;
void Start () {
controller = GetComponent<CharacterController> ();
}
// Update is called once per frame
public float speed = 5.0f;
Vector3 movement = Vector3.zero;
public float jumpSpeed = 8.0f;
public float pushPower = 2.0f;
public float none = 0f;
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
if (body == null || body.isKinematic)
{
return;
}
if (hit.moveDirection.y < 0.3f)
{
return;
}
Vector3 pushDir = new Vector3 (hit.moveDirection.x, 0f, 0f);
body.velocity = pushDir * pushPower;
}
void Update () {
movement.x = Input.GetAxis ("Horizontal") * speed;
controller.Move (movement * Time.deltaTime);
if (controller.isGrounded == false) {
movement.y += Physics.gravity.y * Time.deltaTime;
}
controller.Move(movement * Time.deltaTime);
if (Input.GetButton ("Jump") && controller.isGrounded == true) {
movement.y = jumpSpeed;
}
if (controller.isGrounded == false) {
movement.x = 0f;
}
}
}
Answer by allenallenallen · Feb 19, 2016 at 09:13 AM
First of all, don't use (controller.isGrounded == false). Instead, use (!controller.isGrounded). Same for when it's true.
void Update () {
movement.x = Input.GetAxis ("Horizontal") * speed;
if (controller.isGrounded == false) {
movement.y += Physics.gravity.y * Time.deltaTime;
movement.x = 0f; // I moved your x cancellation here.
}
if (Input.GetButton ("Jump") && controller.isGrounded) {
movement.y = jumpSpeed;
}
controller.Move(movement * Time.deltaTime); // This should be the last thing that happens here when you're done with all the movement calculations.
}
Keep in mind that I might have broken some parts of your movements with this code so you'll have rearrange or recode some of the movements.
Answer by muhammadtahiriqbal · Feb 19, 2016 at 01:54 PM
you can also do that by freezing the rotation on y axis while the character jump
Your answer
Follow this Question
Related Questions
Move only x axis 3 Answers
FPC Moves itself 0 Answers
Charecter Controller like in Merry Bear game(Cube based game). 0 Answers
Stop animation when character controller hits walls 1 Answer