- Home /
C# let a character jump
Hello,
I´m trying to implement some basic movements like moving around and jumping but I have already a problem with letting my character jump.
I wrote a 'Move' function in which I let the character jump when I´m pressing the space key. The Code looks like that:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour {
public float speed = 10.0f;
public float jumpForce = 10.0f;
public float gravity = 10.0f;
public float rotateSpeed = 200;
private Vector3 motion = Vector3.zero;
private CharacterController controller
{
get
{
return GetComponent<CharacterController>();
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Move();
Rotate();
}
private void Move()
{
motion = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
motion *= speed;
motion = transform.TransformDirection(motion);
controller.Move (motion);
//controller.SimpleMove(motion);
//jump
if(Input.GetKeyDown (KeyCode.Space) & controller.isGrounded)
{
motion.y = jumpForce;
}
motion.y -= gravity * Time.deltaTime;
controller.Move(motion * Time.deltaTime);
}
private void Rotate()
{
transform.Rotate(0, Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime, 0);
Camera.mainCamera.transform.Rotate(-1 * Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime, 0, 0);
}
}
Unfortuatly the character is not jumping. He is jumping once and after it he is just stuck to the ground and not doing anything. The rest of the movements are working fine. Can anyone tell me what I´m doing wrong?
I also think I chose the gravity abit too high. What do you think?
Thank you in advance.
Answer by Nanashi91 · Sep 28, 2012 at 10:08 PM
I got it done. Now I use this method as my "move()"-Method and it is working. I think my mistake was that I called "controller.Move (motion);" in between already and not just at the end. But I´m not sure about that.
Anyway, thank you for trying to help me.
Answer by Sundar · Sep 28, 2012 at 04:10 PM
I have noticed that you have only one "&" in jump 'if statement' you need two "&&" like
//jump
if(Input.GetKeyDown (KeyCode.Space) && controller.isGrounded)
{
motion.y = jumpForce;
}
Change and see whether it is working.
I tried to change the "&" to "&&" but nothing changed. He is not jumping.