wirm/Game/Assets/Scripts/Car.cs

75 lines
2.2 KiB
C#
Raw Normal View History

2025-02-11 00:36:43 +08:00
/*
2025-02-14 22:13:03 +08:00
* Author: Wai Lam
* Date: 10/2/2025
* Description: Car obstacle
2025-02-11 00:36:43 +08:00
*/
2025-02-14 22:13:03 +08:00
2025-02-11 00:36:43 +08:00
using UnityEngine;
public class Car : MonoBehaviour
{
2025-02-14 22:13:03 +08:00
public Transform playerRig; // Assign your XR Rig here
public Transform startPoint; // Assign the starting point here
2025-02-11 09:43:43 +08:00
2025-02-14 22:13:03 +08:00
public Transform[] waypoints; // List of waypoints
public float speed = 3.0f; // Speed of movement
public float rotationSpeed = 5.0f; // Smooth turning speed
public Vector3 rotationOffset = Vector3.zero;
2025-02-14 22:13:03 +08:00
private int _currentWaypointIndex; // Starting at the first waypoint
private void Update()
{
if (waypoints.Length == 0) return;
MoveTowardsWaypoint();
RotateTowardsWaypoint();
}
2025-02-11 00:36:43 +08:00
private void OnTriggerEnter(Collider other)
{
// Check if the collider belongs to the player
2025-02-14 22:13:03 +08:00
if (!other.CompareTag("Player")) return;
2025-02-14 22:19:28 +08:00
2025-02-14 22:13:03 +08:00
Debug.Log("Teleporting Player...");
TeleportPlayer();
2025-02-11 00:36:43 +08:00
}
private void TeleportPlayer()
{
2025-02-14 22:13:03 +08:00
if (Camera.main == null)
{
Debug.LogError("not teleporting player, no main camera found!");
return;
}
var offset = playerRig.position - Camera.main.transform.position;
2025-02-11 00:36:43 +08:00
playerRig.position = startPoint.position + offset;
playerRig.rotation = startPoint.rotation;
}
2025-02-11 09:43:43 +08:00
2025-02-14 22:13:03 +08:00
private void MoveTowardsWaypoint()
2025-02-11 09:43:43 +08:00
{
2025-02-14 22:13:03 +08:00
var target = waypoints[_currentWaypointIndex];
2025-02-11 09:43:43 +08:00
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
// Check if the object has reached the waypoint
if (Vector3.Distance(transform.position, target.position) < 0.1f)
// Move to the next waypoint in a loop
2025-02-14 22:13:03 +08:00
_currentWaypointIndex = (_currentWaypointIndex + 1) % waypoints.Length;
2025-02-11 09:43:43 +08:00
}
2025-02-14 22:13:03 +08:00
private void RotateTowardsWaypoint()
2025-02-11 09:43:43 +08:00
{
2025-02-14 22:13:03 +08:00
var target = waypoints[_currentWaypointIndex];
var direction = (target.position - transform.position).normalized;
2025-02-11 09:43:43 +08:00
if (direction != Vector3.zero)
{
// Apply rotation offset
2025-02-14 22:13:03 +08:00
var lookRotation = Quaternion.LookRotation(direction) * Quaternion.Euler(rotationOffset);
2025-02-11 09:43:43 +08:00
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, rotationSpeed * Time.deltaTime);
}
}
2025-02-14 22:13:03 +08:00
}