-1
\$\begingroup\$

I've made a very basic character controller using a CharacterController component. I'm still a beginner so I keep learning new things. My problem is how to optimize my controller script. Also, I would like to learn more about physics and things like this but I can't find any good tutorial or documentation, so if you know where I can find some interesting information (I'm not talking about Google here), I'd be glad if you share them with me.

My character falls way too slowly. Also, I can midair movement should be limited. My next problem is that my character levitates after hitting a platform or something with its head before reaching its max jump height. Another thing is that it can "levitate" next to platform just because it touches a collider, where normally it should just fall down.

So here's the code:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float moveSpeed = 9.5f;
public float jumpSpeed = 1.5f;
public float gravity = 7.0f;

CharacterController controller;
Vector3 currentMovement;

public Transform [] startPoint;

void Start () 
{
    controller = GetComponent<CharacterController>();
}


void Update () 
{
    currentMovement = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, currentMovement.y, Input.GetAxis("Vertical") * moveSpeed);

    if(!controller.isGrounded) // Można również zapisać jako if(controller.isGrounded == false)
        currentMovement -= new Vector3(0, gravity * Time.deltaTime, 0); // Można zapisać jako currentMovement.y -= new Vector3(0, -gravity * Time.deltaTime, 0)
    else
        currentMovement.y = 0;

    if(controller.isGrounded && Input.GetKey(KeyCode.Space))
    {
        currentMovement.y = jumpSpeed;
    }

    controller.Move(currentMovement * Time.deltaTime);

    if(Input.GetKeyDown(KeyCode.X))
    {
        gameObject.transform.position = startPoint[0].position;
    }

    if(Input.GetKeyDown(KeyCode.Escape))
    {
        Application.LoadLevel(0);
    }
}
}
\$\endgroup\$
1
  • \$\begingroup\$ I am not sure how the isGrounded is determined but if this returns true whenever your player touches a rigidbody then this would account for the levitating that you are seeing. This question has an example of how to write your own isGrounded function gamedev.stackexchange.com/questions/105399/… using raycasts \$\endgroup\$ Commented Dec 17, 2015 at 16:07

1 Answer 1

0
\$\begingroup\$

Your character falls too slowly because of these two lines:

currentMovement -= new Vector3(0, gravity * Time.deltaTime, 0); //multiply by deltaTime
controller.Move(currentMovement * Time.deltaTime); //multiply by delta time again
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.