MiniGames/Assets/Scripts/ChaseOn/ChasePlayerController.cs

144 lines
4.1 KiB
C#
Raw Normal View History

2025-07-30 01:38:12 +05:00
using UnityEngine;
public class ChasePlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float laneDistance = 2.5f; // Distance between lanes
public float jumpForce = 7f;
public float laneSwitchSpeed = 10f;
private int currentLane = 1; // 0 = Left, 1 = Middle, 2 = Right
private Rigidbody rb;
private Animator animator;
private bool isGrounded = true;
private Vector3 targetPosition;
2025-08-06 19:14:48 +05:00
private Vector2 startTouchPosition;
private Vector2 endTouchPosition;
private bool swipeDetected = false;
private float minSwipeDistance = 50f; // Pixels
2025-07-30 01:38:12 +05:00
void Start()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
targetPosition = transform.position;
}
void Update()
{
HandleInput();
2025-08-06 19:14:48 +05:00
HandleSwipe(); // Add this
2025-07-30 01:38:12 +05:00
HandleLaneSwitch();
MoveForward();
}
void HandleInput()
{
2025-08-06 19:14:48 +05:00
// Keyboard controls (for testing in editor)
2025-07-30 01:38:12 +05:00
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if (currentLane > 0)
currentLane--;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
if (currentLane < 2)
currentLane++;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
2025-08-06 19:14:48 +05:00
Jump();
}
}
void HandleSwipe()
{
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
startTouchPosition = touch.position;
swipeDetected = true;
break;
case TouchPhase.Ended:
if (swipeDetected)
{
endTouchPosition = touch.position;
Vector2 swipe = endTouchPosition - startTouchPosition;
if (swipe.magnitude >= minSwipeDistance)
{
float x = swipe.x;
float y = swipe.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
// Horizontal swipe
if (x > 0)
{
// Swipe Right
if (currentLane < 2)
currentLane++;
}
else
{
// Swipe Left
if (currentLane > 0)
currentLane--;
}
}
else
{
// Vertical swipe
if (y > 0 && isGrounded)
{
// Swipe Up = Jump
Jump();
}
}
}
swipeDetected = false;
}
break;
}
2025-07-30 01:38:12 +05:00
}
}
2025-08-06 19:14:48 +05:00
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
if (animator != null) animator.SetTrigger("Jump");
}
2025-07-30 01:38:12 +05:00
void HandleLaneSwitch()
{
float targetX = (currentLane - 1) * laneDistance;
targetPosition = new Vector3(targetX, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, targetPosition, laneSwitchSpeed * Time.deltaTime);
}
void MoveForward()
{
transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
if (animator != null) animator.SetTrigger("Run");
}
}
}