Home > other >  Problem in my jumping Script with characheter controller unity
Problem in my jumping Script with characheter controller unity

Time:09-27

So, I was testing my scripts and i wanted my player to jump with character controller and i am having a problem with it. Problem
```

public CharacterController control;

public float playerSpeed;
public float jumpSpeed;

void Start()
{
    playerSpeed = 6.0f;
    jumpSpeed = 50;
}

void Update()
{       

    float h = Input.GetAxisRaw("Horizontal");
    float v = Input.GetAxisRaw("Vertical");

    Vector3 move = new Vector3 (h, 0, v);
    Vector3 velocity = move * playerSpeed;

    if (control.isGrounded && Input.GetKey(KeyCode.Space))
    {
        velocity.y  = jumpSpeed; // velocity.y = jumpSpeed; tried both
    }
    else
    {
        velocity  = Physics.gravity * Time.deltaTime;
    }
        control.Move(velocity * Time.deltaTime);
}

}```


Here's my unity screen and code above.


The problem is when i press jump it does jump but it's position goes to 2.068, i.e it jumps to low and when gravity is activated it comes down to slow, it takes around 6 seconds to come to its initial position.

I even tried to add a parent object to it so that it may change, but it does the same to it.

CodePudding user response:

if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
    // first just try this
    velocity.y  = jumpSpeed * Time.deltaTime;
}
else
{
    velocity.y -= Physics.gravity * Time.deltaTime;
}

and if it is not working

Vector3 move = new Vector3 (h, 0, 0);
Vector3 jump = new Vector3 (0, 0, v);
Vector3 _velocityMove = move * playerSpeed;
Vector3 _velocityJump = jump* jumpSpeed;

 if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
    velocity.y  = _velocityJump ;//and you can add ' * Time.deltaTime '
}
else
{
    velocity  = Physics.gravity * Time.deltaTime;
}
    control.Move(_velocityMove * Time.deltaTime);

CodePudding user response:

ohk so I tweaked some of my code and instead of declaring velocity.y in the condition of if the player is grounded , i declared outside the condition and change the value of variable in condition.

velocity.y = jumpSpeed;

if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
    jumpSpeed = 10;
}
else
{
    jumpSpeed  = Physics.gravity.y * Time.deltaTime;
}

This seems to do the trick and my player can jump nicely.

  • Related