- Home /
Character jumping but also moving +1 in Z, why?
Hey guys! So I'm learning Unity and trying to make, as practice, a Robot Unicorn kind of game (side scroller on rails etc). I'm getting something wrong and I can't figure out what it is. Here's what happens:
I've made a simple auto-move forward and jump script. They're working kinda fine... Except that when I press jump, the character also moves in Z by +1. I have no idea why. And being a 2d game, moving in Z is not welcome at all. Anyway, here's the code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
CharacterController controller;
public float speed = 50;
public float jumpSpeed = 30;
public float gravity = -0.05f;
float velocityY = 0;
void Start () {
controller = GetComponent<CharacterController>();
}
void Update () {
Vector3 direction = new Vector3 (Input.GetAxis("Horizontal")*speed, velocityY, 0);
if (controller.isGrounded && Input.GetButton("Jump")) {
velocityY = jumpSpeed*Time.deltaTime;
direction.z = -1;
}
else {
velocityY += gravity*Time.deltaTime;
}
direction = transform.TransformDirection(direction);
controller.Move(direction*Time.deltaTime);
}
}
(The movement in X is set to Horizontal just for testing)
Comment