I am trying to play the sound of a car accelerating while a user has a certain button pressed, however, the audio clip isn't playing until after that button is released. Can anyone explain to me where I'm going wrong?
C#
using UnityEngine;
using System.Collections;
public class MoveCar:MonoBehaviour{
//Car's idle speed
private float idleSpeed = 0.0f;
//Car's current speed
private float speed = 0.0f;
//Car's top speed
public float topSpeed = 165.0f;
//Car's acceleration rate
public float acceleration = 10.0f;
//Car's braking power
public float deceleration = 15.0f;
private Rigidbody playerCar;
void Start(){
playerCar = GetComponent<Rigidbody>();
}
void Update(){
if(Input.GetKey(KeyCode.W)){
AudioSource accelerate = playerCar.GetComponent<AudioSource>();
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if(speed <= topSpeed){
accelerate.Play();
speed = speed + (acceleration * Time.deltaTime);
Vector3 movement = new Vector3(vertical, 0.0f, horizontal);
playerCar.AddForce(movement * Mathf.Clamp(speed, idleSpeed, topSpeed));
Debug.Log(Mathf.Clamp(speed, idleSpeed, topSpeed));
}
else{
speed = topSpeed;
Debug.Log(Mathf.Clamp(speed, idleSpeed, topSpeed));
}
}
}
}
