(Unity6 BRP)シンプルなカーレースゲームの作成(加速・減速)

(サンプルコード)

using UnityEngine;

public class CarController : MonoBehaviour
{
    private InputSystem_Actions isa;

    private Rigidbody rb;

    private float turnSpeed = 30f;
    private float maxSpeed = 10f;
    private float acceleration = 10f;
    private float deceleration = 3f;

    private float currentSpeed = 0;

    void Start()
    {
        isa = new InputSystem_Actions();
        isa.Enable();

        rb = GetComponent<Rigidbody>();
    }

    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);
    }

    private void OnDisable()
    {
        isa.Disable();
    }
}

(実行結果)

・WASDで前進・後退、左右の回転ができれば成功です。