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

120 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using DG.Tweening.Plugins.Core.PathCore;
public class PlayerPathRunner : MonoBehaviour
{
[Header("Speed Settings")]
public float baseSpeed = 2f;
public float maxSpeed = 10f;
public float acceleration = 5f;
public float constantSpeed = 5f; // Speed to use when not in tap mode
[Header("Tap Speed Mode")]
public bool useTapToMove = true;
public float tapWindowSeconds = 0.5f;
[Header("Path Setup")]
public DOTweenPath pathSource;
[Header("Hurdle Setup")]
public List<Transform> hurdles; // Assign all hurdles here
private List<float> tapTimestamps = new();
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 DOTween path (we pause immediately)
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.");
}
// Initialize speed based on mode
if (!useTapToMove)
{
currentSpeed = constantSpeed;
}
}
void Update()
{
if (useTapToMove)
{
HandleInput();
UpdateSpeed();
}
else
{
// In constant mode, set speed directly without acceleration
currentSpeed = constantSpeed;
}
MoveOnPath();
}
void HandleInput()
{
if (Input.GetMouseButtonDown(0) || Input.touchCount > 0)
{
tapTimestamps.Add(Time.time);
}
}
void UpdateSpeed()
{
float cutoff = Time.time - tapWindowSeconds;
tapTimestamps.RemoveAll(t => t < cutoff);
float tps = tapTimestamps.Count / tapWindowSeconds;
float targetSpeed = Mathf.Clamp(baseSpeed + tps, baseSpeed, maxSpeed);
currentSpeed = Mathf.MoveTowards(currentSpeed, targetSpeed, acceleration * Time.deltaTime);
}
void MoveOnPath()
{
if (drawPoints == null || drawPoints.Length < 2) return;
float speed = currentSpeed / 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 GetCurrentSpeed()
{
return currentSpeed;
}
}