- Home /
HOW DO I MAKE MY CHARACTER GAIN SPEED GRADUALLY 3D
I am making a 3D platformer based around speed like sonic the hedgehog. But my problem is that I can't get my character to gain speed gradually. Instead it just goes at top speed all the time. I need help please. PS: I'm using Character Controller not the RigidBody
Answer by Masterio · Oct 30, 2017 at 09:17 AM
private float _speed = 0f;
const float MAX_SPEED = 4f;
const float ACCELERATION = 2f;
const float DRAG = 6f;
void Update()
{
if(rightPressed)
_speed = Mathf.MoveTowards(_speed, MAX_SPEED, Time.deltaTime * ACCELERATION);
else if(leftPressed)
_speed = Mathf.MoveTowards(_speed, -MAX_SPEED, Time.deltaTime * ACCELERATION);
else
_speed = Mathf.MoveTowards(_speed, 0f, Time.deltaTime * DRAG);
}
The speed keeps current speed value it should goes to the MAX_SPEED value when you hold the right button, it should goes to the -MAX_SPEED when hold the left button, it should goes to the 0 when hold no move buttons.
*rightPressed and leftPressed are example variables you must put here button detection conditions.
Answer by djibrilkande009 · Oct 30, 2017 at 09:37 PM
When i use the code the character doesn't move. Sorry if it bothers you i'm new to unity: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
private float _speed = 0f;
const float MAX_SPEED = 4f;
const float ACCELERATION = 2f;
const float DRAG = 6f;
public CharacterController CT;
// Use this for initialization
void Start () {
CT = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("right"))
_speed = Mathf.MoveTowards(_speed, MAX_SPEED, Time.deltaTime * ACCELERATION);
else if (Input.GetKeyDown("left"))
_speed = Mathf.MoveTowards(_speed, -MAX_SPEED, Time.deltaTime * ACCELERATION);
else
_speed = Mathf.MoveTowards(_speed, 0f, Time.deltaTime * DRAG);
}
}
You should put update code inside the CharacterController class and the _speed variable is just a speed mod for your current speed. You should multiply your character current speed by this value.
Or show me the character controller class. i cant say nothing more now.
@$$anonymous$$asterio if i understand I should multiply each of the _speed statements by a speed variable?
No you must multiply all speed variables by the _speed.
Your answer
Follow this Question
Related Questions
How to get smooth 4 directional movement in top down without diagonal movement? 2 Answers
How to create an eight point 3d character controller in unity with rigidbody enabled 0 Answers
How to tell if the player is turning? 2 Answers
How does the premade FPSController handle character physics? 1 Answer