So Ive written some basic left/right movement object code, with some increase and decrease in speed, I’m having trouble trying to figure out how to maintain the speed of the object once it reaches maximum speed.
As it stands, the object reaches maximum speed then slows down because of the way my code is written.
I want the object to reach max and stay there until the key is released.
using UnityEngine;
using System.Collections;
public class move : MonoBehaviour
{
public float speed = 3.0f;
private float maxspeed = 4.0f;
private float minspeed = 3.0f;
void Update ()
{
if (Input.GetKey (KeyCode.LeftArrow) && (speed < maxspeed))
{
this.transform.Translate (new Vector3 (-speed * Time.deltaTime, 0, 0));
speed += Time.deltaTime; //increase speed until maximum speed
}
else if (Input.GetKey (KeyCode.RightArrow) && (speed < maxspeed))
{
this.transform.Translate (new Vector3 (speed * Time.deltaTime, 0, 0));
speed += Time.deltaTime;
}
else if (speed > minspeed ) {
speed -= Time.deltaTime; //reduce speed until minimum speed
}
}
}
Or you have to rearrange these if-else statements to exclude the case when you push the left/right keys but it’s already on top speed from the slow down section.
Okay, what’s your goal here, do you want to move the object all the time, regardless of the keypress with at least minimumspeed? Or do you want to stop moving the object if the key is released and the speed reached minspeed?
The goal is to make speed = maxspeed once maxspeed is hit, until the key is realeased. If that makes sense. Once maxspeed is reached, stay at that speed until realease
float h = Input.GetAxis("Horizontal");
if(h != 0) {
this.transform.Translate (new Vector3 (Mathf.Sign(h) * speed * Time.deltaTime, 0, 0));
speed += Time.deltaTime; //increase speed until maximum speed
}
else speed -= Time.deltaTime;
speed = Mathf.Clamp(speed, minspeed, maxspeed);
Edit: I wasn’t 100% sure if the translate should be happening when no key is pressed, at whatever the current speed is, or not. This only lowers the speed, but does not translate.
But when you release the button, it should slow down. Should it stop when it reach minspeed or maintain the movement with at least minspeed all the time?
velocity is for rigidbody movement. I think, generally speaking it’s good to know about both, because you might want one, the other, or both in a game. However, use the one that’s right for your situation.
Maybe for now: do what your doing, learn what velocity is and keep it in mind, if you ever need it?