- Home /
Character Won't Jump
Hi. I'm a complete beginner to Unity3D, C# and programming, so I'm using this video as guidance. https://www.youtube.com/watch?v=QvbZYKcpjkY . My only problem is that his character is jumping, while mine is not. Our scripts are identical so I don't know what's wrong. Can anyone help?
using UnityEngine;
using System.Collections;
public class SimpleCharacter : MonoBehaviour
{
public CharacterController MyController;
// Update is called once per frame
public float Speed = 3f;
public float GravityStrenght = 5f;
public float JumpSpeed = 10f;
public Transform CameraTransform;
void Update ()
{
Vector3 myVector = new Vector3(0,0,0);
//get input from the player
myVector.x = Input.GetAxis("Horizontal");
myVector.z = Input.GetAxis("Vertical");
myVector = myVector * Speed*Time.deltaTime;
myVector = CameraTransform.rotation * myVector; //rotate input by direction of camera
//how do we get the jump button?
float verticalVelocity = MyController.velocity.y - GravityStrenght*Time.deltaTime;
if (Input.GetButtonDown("Jump"))
{
//add jumpspeed to vertical velocity
verticalVelocity +=JumpSpeed;
}
myVector.y = verticalVelocity*Time.deltaTime; //add new speed, to old speed, for acceleration
//use input to move the character
MyController.Move(myVector);
}
}
Answer by IceEnry__lol · Oct 07, 2016 at 04:56 PM
I tried to see the script, but I'm not very good with unity because I'm quite new too, so try this :D https://docs.unity3d.com/ScriptReference/CharacterController.Move.html ( you need to attach to your player the character controller) anyway the script is this (it's the same from the Unity scriptreference)
using UnityEngine; using System.Collections;
public class SimpleCharacter : MonoBehaviour { //Variables public float speed = 6.0F; public float jumpSpeed = 8.0F; public float gravity = 20.0F; private Vector2 moveDirection = Vector2.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
// is the controller on the ground?
if (controller.isGrounded) {
//Feed moveDirection with input.
moveDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
//Multiply it by speed.
moveDirection *= speed;
//Jumping
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
//Applying gravity to the controller
moveDirection.y -= gravity * Time.deltaTime;
//Making the character move
controller.Move(moveDirection * Time.deltaTime);
}
}