How do I change a value over time, and then stop it from changing once it's the value I want?
I'm currently trying to make a player movement script for a school project I'm working on, but I can't seem to figure this out. I want the player to have a small buildup before they're moving at full speed, and then when the player lets go of the button, I want them to gradually slow down as well. I'm a bit new to this, so this may be simple, I don't know. But either way, I can't seem to get it working. And I've tried experimenting with something I know works from a previous project, and now it's reached a point were I cant get the player to move at all anymore. This is what I have so far:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
[SerializeField]
private float maxSpeed;
//[SerializeField]
//private float speed;
[SerializeField]
private float jumpForce;
[SerializeField]
private float rateOfIncrease;
[SerializeField]
private float groundLength;
[SerializeField]
private float speedUpTime;
private bool isGrounded;
private Rigidbody rb;
private bool jumping;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
HandleInput();
}
void FixedUpdate ()
{
float horizontal = Input.GetAxis("Horizontal");
HandleMovement(horizontal);
if (Physics.Raycast(transform.position, -transform.up, groundLength))
{
isGrounded = true;
}
ResetValues();
}
void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jumping = true;
}
}
void HandleMovement(float horizontal)
{
float move = Mathf.Lerp(0, maxSpeed, speedUpTime);
if (rb.velocity.x > -maxSpeed ^ rb.velocity.x < maxSpeed && Input.GetKeyDown("Horizontal"))
{
rb.velocity = new Vector3(horizontal *maxSpeed, rb.velocity.y, 0.0f);
}
if (isGrounded && jumping)
{
isGrounded = false;
rb.AddForce(new Vector3(0.0f, jumpForce, 0.0f));
}
}
void ResetValues()
{
jumping = false;
}
}
Answer by inkipinki · Jan 10, 2017 at 03:36 PM
If you want to control it from the code, then uncomment the "speed" variable first. Then change these lines
float horizontal = Input.GetAxis("Horizontal");
HandleMovement(horizontal);
to this:
float horizontal = Input.GetAxis("Horizontal");
speed = Mathf.Lerp(speed, Mathf.Sign(horizontal) * maxSpeed, Time.fixedDeltaTime * acceleration);
HandleMovement(speed);
where the acceleration variable should be added at the top, to the list of variables.
Now you can use this "speed" in the "HandleMovement()" function as the current speed the player will traverse.
If you want quick turning added to this, then this should be the code:
float horizontal = Input.GetAxis("Horizontal");
float sign = Mathf.Sign(horizontal);
if (sign != Mathf.Sign(speed))
{
speed = 0;
}
else
{
speed = Mathf.Lerp(speed, sign * maxSpeed, Time.fixedDeltaTime * acceleration);
}
HandleMovement(speed);
This will stop the player instantly first when changing direction.
Your answer
