You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Driftology/Assets/Scripts/CarController.cs

76 lines
2.2 KiB
C#

using UnityEngine;
public class CarController : MonoBehaviour
{
public float baseSpeed = 10f;
public float turnSpeed = 50f;
public AnimationCurve driftCurve;
public Transform[] visualWheels;
private Rigidbody rb;
private float turnInput;
private Vector2 startTouchPos;
private Vector2 currentTouchPos;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = new Vector3(0, -0.5f, 0);
}
void Update()
{
// Touch input
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
startTouchPos = touch.position;
break;
case TouchPhase.Moved:
case TouchPhase.Stationary:
currentTouchPos = touch.position;
float horizontal = (currentTouchPos.x - startTouchPos.x) / Screen.width;
turnInput = Mathf.Clamp(horizontal, -1f, 1f);
break;
case TouchPhase.Ended:
turnInput = 0f;
break;
}
}
else
{
turnInput = 0f;
}
}
void FixedUpdate()
{
float speed = baseSpeed;
Vector3 forwardMove = transform.forward * speed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + forwardMove);
float turnAmount = turnInput * turnSpeed * Time.fixedDeltaTime;
Quaternion turnOffset = Quaternion.Euler(0, turnAmount, 0);
rb.MoveRotation(rb.rotation * turnOffset);
// Drift logic based on speed and angle
Vector3 velocity = rb.velocity;
float angle = Vector3.Angle(transform.forward, velocity);
float driftFactor = driftCurve.Evaluate(angle);
Vector3 driftDirection = Vector3.Lerp(velocity, transform.forward * velocity.magnitude, driftFactor);
rb.velocity = new Vector3(driftDirection.x, rb.velocity.y, driftDirection.z);
// Visual wheel rotation
foreach (var wheel in visualWheels)
{
float rotationAmount = rb.velocity.magnitude * 10f;
wheel.Rotate(Vector3.right, rotationAmount);
}
}
}