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.
ReactRacetrack/Assets/Scripts/PlayerPathRunner.cs

107 lines
2.7 KiB
C#

using System;
using UnityEngine;
using DG.Tweening;
using System.Collections.Generic;
using DG.Tweening.Plugins.Core.PathCore;
public class PlayerPathRunner : MonoBehaviour
{
public float baseSpeed = 2f;
public float maxSpeed = 10f;
public float tapWindowSeconds = 0.5f;
public DOTweenPath pathSource; // Assign your DOTweenPath GameObject here
private List<float> tapTimestamps = new List<float>();
private float currentSpeed = 0f;
private float pathPosition = 0f;
private Vector3[] drawPoints;
private Path bakedPath;
private void Awake()
{
Application.targetFrameRate = 120;
}
void Start()
{
if (pathSource == null)
{
Debug.LogError("Path Source not assigned!");
return;
}
// Bake the path by creating a paused tween
transform.DOPath(pathSource.wps.ToArray(), 1f, pathSource.pathType, pathSource.pathMode)
.SetOptions(pathSource.isClosedPath)
.SetEase(Ease.Linear)
.SetLookAt(0)
.Pause();
drawPoints = pathSource.GetDrawPoints();
if (drawPoints == null || drawPoints.Length < 2)
{
Debug.LogError("Draw points not generated properly.");
}
}
void Update()
{
MoveOnPath(); // ← no input needed
}
void HandleInput()
{
if (Input.GetMouseButtonDown(0) || Input.touchCount > 0)
{
tapTimestamps.Add(Time.time);
}
}
private float targetSpeed = 0f;
public float acceleration = 5f; // How quickly speed adjusts (lower = smoother)
void UpdateSpeed()
{
float cutoff = Time.time - tapWindowSeconds;
tapTimestamps.RemoveAll(t => t < cutoff);
float tps = tapTimestamps.Count / tapWindowSeconds;
targetSpeed = Mathf.Clamp(baseSpeed + tps, baseSpeed, maxSpeed);
// Smoothly move currentSpeed toward targetSpeed
currentSpeed = Mathf.MoveTowards(currentSpeed, targetSpeed, acceleration * Time.deltaTime);
}
void MoveOnPath()
{
if (drawPoints == null || drawPoints.Length < 2) return;
float speed = baseSpeed / 50f;
pathPosition += speed * Time.deltaTime;
pathPosition %= 1f;
float floatIndex = pathPosition * (drawPoints.Length - 1);
int iA = Mathf.FloorToInt(floatIndex);
int iB = Mathf.Min(iA + 1, drawPoints.Length - 1);
float t = floatIndex - iA;
Vector3 pos = Vector3.Lerp(drawPoints[iA], drawPoints[iB], t);
transform.position = pos;
}
public float CurrentSpeedNormalized()
{
return Mathf.InverseLerp(baseSpeed, maxSpeed, currentSpeed);
}
public float GetPathPosition()
{
return pathPosition;
}
}