proto_racer/Assets/Scripts/CarLogic.cs

85 lines
2.7 KiB
C#

using System;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody2D))]
public class CarLogic : MonoBehaviour
{
public InputAction steeringAction;
public InputAction accelerationAction;
public InputAction brakeAction;
public float accelerationAmount = 10;
[Tooltip("In degrees")]
public float steeringAnglePerSecond = 10;
public float maxAcceleration = 100;
private Rigidbody2D _rigidbody;
private Transform _transform;
private float _currentAcceleration;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
_transform = transform;
}
private void Start()
{
steeringAction.Enable();
accelerationAction.Enable();
brakeAction.Enable();
}
private void Update()
{
var steeringValue = steeringAction.ReadValue<float>();
var accelerationValue = accelerationAction.ReadValue<float>();
// TODO: The what that I changed this too I like a lot better, however I do want to eventually figure out what was wrong with this verbose approach.
// Vector2 velocityDir = _transform.up;
// var currentAngleRad = Mathf.Acos(Vector3.Dot(velocityDir, Vector3.up));
// var deltaAngleRad = steeringValue * steeringAnglePerSecond * Time.deltaTime * Mathf.Deg2Rad;
// var angleRad = deltaAngleRad + currentAngleRad;
//
// var angleCos = Mathf.Cos(angleRad);
// var angleSin = Mathf.Sin(angleRad);
// Vector2 nextVelocityDir;
// nextVelocityDir.x = angleCos * velocityDir.x -
// angleSin * velocityDir.y;
// nextVelocityDir.y = angleSin * velocityDir.x +
// angleCos * velocityDir.y;
//
// nextVelocityDir *= accelerationAmount * accelerationValue * Time.deltaTime;
// TODO: probably not correct... ODE or some other formula.
if (accelerationValue <= 0)
{
_currentAcceleration -= _rigidbody.drag * Time.deltaTime;
}
_currentAcceleration += accelerationValue * accelerationAmount * Time.deltaTime;
var newAngle = steeringValue * steeringAnglePerSecond * Time.deltaTime;
if (_currentAcceleration > 0.01)
{
_transform.Rotate(Vector3.forward, newAngle, Space.World);
}
// TODO: reverse logic.
if (_currentAcceleration < 0)
{
_currentAcceleration = 0;
}
if (_currentAcceleration > maxAcceleration)
{
_currentAcceleration = maxAcceleration;
}
Debug.Log(_currentAcceleration);
_rigidbody.velocity = _transform.up * _currentAcceleration;
}
}