dima dima - 1 year ago 190
C# Question

How to make GameObject jump in Unity3D

I have a 2d game, where GameObject (GO) moves to the right side on the floor. I want to make it jump.

But when I add Character Controller to my GO and start simulation, it just fast move on the left side. Can't understand, what's wrong.

GO also contain Rigidbody and Box Collider

public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;

void Start ()
player = (GameObject)this.gameObject;

void Update ()
// Move
player.transform.position +=
player.transform.right * speed * Time.deltaTime;

// Jump
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0,
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;

moveDirection.y = jumpSpeed;

moveDirection.y -= gravity * Time.deltaTime;
controller.Move (moveDirection * Time.deltaTime);

Answer Source

This is old but came across this on a google search.

Character Controller is not designed to use the physics components. Remove the rigidbody and box collider. It uses a simulated capsule collider to do its detection.

Also remove the following from you code and the input should work like normal again.

player.transform.position += player.transform.right * speed * time.deltaTime;    

That piece of code is causing you to move inadvertently.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download