Hi there!
I am trying to make a car accelerate to a maxSpeed when pushing a button and deAccelerate when letting go of the button.
My code worked beofore i added the “MinusAcceleration” in the way that the car accelerated slowly, but as soon as i let go of the acceleration-button it instantly stopped (which i tried to fix with the MinusAcceleration function)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Acceleration : MonoBehaviour
{
public float maxSpeed;
private float accelerationPower;
public float minSpeed;
private float minusAccelerationPower;
public float turnSpeed;
private Rigidbody rb;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
Forward();
InvokeRepeating("Accelerating", 0f, 2f);
InvokeRepeating("MinusAcceleration", 0f, 2f);
Turning();
}
void Accelerating()
{
if (accelerationPower > maxSpeed)
{
accelerationPower += 0.05f;
}
}
void MinusAcceleration()
{
if(minusAccelerationPower > minSpeed)
{
minusAccelerationPower -= 0.05f;
}
}
void Forward()
{
if(Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * accelerationPower * Time.deltaTime);
}
else
{
transform.Translate(Vector3.forward * minusAccelerationPower * Time.deltaTime);
}
}
void Turning()
{
transform.Rotate(0.0f, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0.0f);
}
}
Can this be fixed with a rigidbody instead? Or how?
I appreaciate all the help i can get, Thanks in advance!