Unity_lab3/Unity3_lab/Assets/Scripts/BallController.cs
vladislove d864f0db29 Merge remote-tracking branch 'malina/GOPA'
# Conflicts:
#	Unity3_lab/Assets/Scenes/MainScene.unity
#	Unity3_lab/Library/ArtifactDB
#	Unity3_lab/Library/Artifacts/0d/0dc5019e8ffbe484ffe49a45a97c3a47
#	Unity3_lab/Library/Artifacts/28/2891da42ed1baffa3184815f69419569
#	Unity3_lab/Library/Artifacts/76/76cfd87afc2516f8c733e007dee8ba8f
#	Unity3_lab/Library/Artifacts/9c/9cdc9440aa66116becd7b77038646ad6
#	Unity3_lab/Library/Artifacts/ac/ac9d5860e606d7678f19b61fe16a6182
#	Unity3_lab/Library/Artifacts/c5/c50c3275b8e1e75ea5343b31e0931ce7
#	Unity3_lab/Library/Bee/TundraBuildState.state
#	Unity3_lab/Library/Bee/TundraBuildState.state.map
#	Unity3_lab/Library/Bee/artifacts/2400b0aE.dag/Assembly-CSharp.dll
#	Unity3_lab/Library/Bee/artifacts/2400b0aE.dag/Assembly-CSharp.pdb
#	Unity3_lab/Library/Bee/artifacts/2400b0aE.dag/Assembly-CSharp.ref.dll
#	Unity3_lab/Library/Bee/artifacts/2400b0aE.dag/post-processed/Assembly-CSharp.dll
#	Unity3_lab/Library/Bee/artifacts/2400b0aE.dag/post-processed/Assembly-CSharp.pdb
#	Unity3_lab/Library/Bee/backend1.traceevents
#	Unity3_lab/Library/Bee/backend2.traceevents
#	Unity3_lab/Library/Bee/buildprogram0.traceevents
#	Unity3_lab/Library/Bee/fullprofile.json
#	Unity3_lab/Library/Bee/tundra.digestcache
#	Unity3_lab/Library/BurstCache/JIT/BurstCacheManifest.cm
#	Unity3_lab/Library/BurstCache/JIT/Hashes/8bd375117381c8f40ed1fc10f10e1697.bhc
#	Unity3_lab/Library/BurstCache/JIT/Hashes/a110ffe6b760e4b56cb86ae44bc7857d.bhc
#	Unity3_lab/Library/BurstCache/JIT/Hashes/eb5762c176c563408800b67be30a9bca.bhc
#	Unity3_lab/Library/InspectorExpandedItems.asset
#	Unity3_lab/Library/PreviousActionData.bin
#	Unity3_lab/Library/PreviousActionStack.bin
#	Unity3_lab/Library/SceneVisibilityState.asset
#	Unity3_lab/Library/ScriptAssemblies/Assembly-CSharp.dll
#	Unity3_lab/Library/ScriptAssemblies/Assembly-CSharp.pdb
#	Unity3_lab/Library/Search/98957a664bd18c47a3e41b2a0189ef53.33332.b.index
#	Unity3_lab/Library/Search/transactions.db
#	Unity3_lab/Library/ShaderCache.db
#	Unity3_lab/Library/ShaderCache/EditorEncounteredVariants
#	Unity3_lab/Library/SourceAssetDB
#	Unity3_lab/Library/StateCache/SceneView/8c/8cd7c613bf844de3b80696e27a479d5e.json
#	Unity3_lab/Library/UndoData.bin
#	Unity3_lab/Library/UndoStack.bin
#	Unity3_lab/Library/ilpp.pid
#	Unity3_lab/Logs/AssetImportWorker0-prev.log
#	Unity3_lab/Logs/AssetImportWorker0.log
#	Unity3_lab/Logs/AssetImportWorker1-prev.log
#	Unity3_lab/Logs/AssetImportWorker1.log
#	Unity3_lab/UserSettings/Layouts/default-6000.dwlt
#	Unity3_lab/obj/Debug/Assembly-CSharp.csproj.AssemblyReference.cache
2025-11-12 23:06:32 +03:00

166 lines
6.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
public class BallController : MonoBehaviour
{
[Header("Настройки Движения")]
[SerializeField] private float maxSpeed = 15f; // Максимальная скорость на земле
[SerializeField] private float accelerationRate = 200f; // Как быстро шарик разгоняется
[SerializeField] private float airControlSpeed = 5f; // Скорость управления в прыжке
[SerializeField] private float jumpForce = 7f; // Сила прыжка
[SerializeField] private float trampolineBounceForce = 1.5f; // Множитель для отскока от батута
[Header("Настройки Контроля")]
[Tooltip("Как быстро шарик останавливается (сила торможения). Должна быть высокой.")]
[SerializeField] private float decelerationRate = 200f; // Сила торможения
private Rigidbody rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
// УБЕДИСЬ, ЧТО ЭТА СТРОКА ЗАКОММЕНТИРОВАНА ИЛИ УДАЛЕНА!
// rb.freezeRotation = true;
}
void Update()
{
HandleJumpInput();
}
void FixedUpdate()
{
isGrounded = false;
HandleMovement();
}
public bool IsGrounded
{
get { return isGrounded; }
}
// --- Логика Управления Движением ---
private void HandleMovement()
{
// Используем GetAxisRaw для мгновенного отклика (1, 0, -1)
float moveX = Input.GetAxisRaw("Horizontal");
float moveZ = Input.GetAxisRaw("Vertical");
if (isGrounded)
{
Vector3 currentVel = rb.linearVelocity;
Vector3 currentAngularVel = rb.angularVelocity;
// --- Управление Осью X (A/D) ---
if (Mathf.Abs(moveX) > 0.01f)
{
// 1. Ускорение по X
if (Mathf.Abs(currentVel.x) < maxSpeed)
{
rb.AddForce(new Vector3(moveX, 0, 0) * accelerationRate, ForceMode.Acceleration);
}
}
else
{
// 2. Торможение по X (Линейное)
// Применяем силу против текущей скорости X
float brakeForceX = -currentVel.x;
rb.AddForce(new Vector3(brakeForceX, 0, 0) * decelerationRate, ForceMode.Acceleration);
// 2. Торможение по X (Угловое - качение по X = вращение по Z)
// Применяем крутящий момент против вращения по Z
float brakeTorqueZ = -currentAngularVel.z;
rb.AddTorque(new Vector3(0, 0, brakeTorqueZ) * decelerationRate, ForceMode.Acceleration);
}
// --- Управление Осью Z (W/S) ---
if (Mathf.Abs(moveZ) > 0.01f)
{
// 1. Ускорение по Z
if (Mathf.Abs(currentVel.z) < maxSpeed)
{
rb.AddForce(new Vector3(0, 0, moveZ) * accelerationRate, ForceMode.Acceleration);
}
}
else
{
// 2. Торможение по Z (Линейное)
// Применяем силу против текущей скорости Z
float brakeForceZ = -currentVel.z;
rb.AddForce(new Vector3(0, 0, brakeForceZ) * decelerationRate, ForceMode.Acceleration);
// 2. Торможение по Z (Угловое - качение по Z = вращение по X)
// Применяем крутящий момент против вращения по X
float brakeTorqueX = -currentAngularVel.x;
rb.AddTorque(new Vector3(brakeTorqueX, 0, 0) * decelerationRate, ForceMode.Acceleration);
}
// Ограничение максимальной скорости
Vector3 horizontalVel = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
if (horizontalVel.sqrMagnitude > maxSpeed * maxSpeed)
{
Vector3 clampedVel = horizontalVel.normalized * maxSpeed;
rb.linearVelocity = new Vector3(clampedVel.x, rb.linearVelocity.y, clampedVel.z);
}
}
else
{
// Управление в воздухе
Vector3 movement = new Vector3(moveX, 0.0f, moveZ).normalized;
rb.AddForce(movement * airControlSpeed, ForceMode.Acceleration);
}
}
private void HandleJumpInput()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
// --- Логика Взаимодействия и Тегирования ---
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Trampoline"))
{
HandleTrampolineBounce(collision);
return;
}
CheckIfGrounded(collision);
}
private void OnCollisionStay(Collision collision)
{
CheckIfGrounded(collision);
}
private void HandleTrampolineBounce(Collision collision)
{
Vector3 surfaceNormal = Vector3.up;
if (collision.contacts.Length > 0)
{
surfaceNormal = collision.contacts[0].normal;
}
rb.linearVelocity = Vector3.zero;
rb.AddForce(surfaceNormal * jumpForce * trampolineBounceForce, ForceMode.Impulse);
}
private void CheckIfGrounded(Collision collision)
{
if (isGrounded) return;
if (collision.contacts.Length > 0)
{
Vector3 normal = collision.contacts[0].normal;
if (normal.y > 0.7f) // ~45 градусов
{
isGrounded = true;
}
}
}
}