I try to get an object to accelerate every frame a button is being pressed up to a maximum velocity, so that my object doesn't just snap into max velocity, same way I'd like to break down the speed. However, my speed is not being cumulated every frame, and also, my GetKeyUp is not being picked up. I tried many things, can't figure this out. Yes, very much a beginner with very little coding background :-)
void Move()
{
public float accelerateR = 0.9f;
public float accelerateL = -0.9f;
public float decelerateR = 1.3f;
public float decelerateL = 1.3f;
public Vector3 velocity;
//move or don't move right
if (Input.GetKeyDown(KeyCode.D))
{
XVel = XVel accelerateR;
if (XVel >= maxSpeed)
{
XVel = maxSpeed;
}
}
else if (Input.GetKeyUp(KeyCode.D))
{
if (XVel <= minSpeed)
{
XVel = minSpeed;
}
else
{
XVel = XVel - decelerateR;
}
}
CodePudding user response:
you could simplify to the following:
private void Update()
{
if(Input.GetKey(KeyCode.D))
{
Accelerate();
return;
}
Decelerate();
}
The problem with your input detection is that you are using GetKeyUp/Down and they only are true on that one frame when it happens. GetKey is true for as long as you press.
CodePudding user response:
GetKeyDown is called on the frame the key was pressed. You need to use GetKey instead and it will be called as long as the key is pressed
And you need to run the input in the Update function
void Update()
{
if (Input.GetKey(KeyCode.D))
{
XVel = XVel accelerateR;
if (XVel >= maxSpeed)
{
XVel = maxSpeed;
}
}
else if (Input.GetKey(KeyCode.D))
{
if (XVel <= minSpeed)
{
XVel = minSpeed;
}
else
{
XVel = XVel - decelerateR;
}
}
Regards,
Itzhak