(サンプルコード)
using UnityEngine;
public class CarController : MonoBehaviour
{
private InputSystem_Actions isa;
private Rigidbody rb;
private float turnSpeed = 30f;
private float maxSpeed = 15f;
private float acceleration = 10f;
private float deceleration = 3f;
private float currentSpeed = 0;
// ★スキッド音
private AudioSource audioS;
private float skidThreshold = 0.5f; // この値以上の横入力で再生
private float minSpeedForSkid = 5f; // ある程度スピードが出てないとスキッドしない
void Start()
{
isa = new InputSystem_Actions();
isa.Enable();
rb = GetComponent<Rigidbody>();
// ★スキッド音
audioS = GetComponent<AudioSource>();
}
void Update()
{
Vector2 movement2 = isa.Player.Move.ReadValue<Vector2>();
float forwardInput = movement2.y;
float turnInput = movement2.x;
if(Mathf.Abs(forwardInput) > 0.1f)
{
currentSpeed += forwardInput * acceleration * Time.deltaTime;
}
else
{
currentSpeed = Mathf.MoveTowards(currentSpeed, 0, deceleration * Time.deltaTime);
}
currentSpeed = Mathf.Clamp(currentSpeed, -maxSpeed, maxSpeed);
Vector3 move = transform.forward * currentSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + move);
float rotationAmount = turnInput * Time.fixedDeltaTime * turnSpeed;
Quaternion turn = Quaternion.Euler(0, rotationAmount, 0);
rb.MoveRotation(rb.rotation * turn);
// ★スキッド音
if (Mathf.Abs(turnInput) > skidThreshold && Mathf.Abs(currentSpeed) > minSpeedForSkid)
{
if (!audioS.isPlaying)
{
audioS.Play();
}
}
else
{
if (audioS.isPlaying)
{
audioS.Stop();
}
}
}
private void OnDisable()
{
isa.Disable();
}
}