Oyun Kütüphanesi

Rigidbody ile Yüzme Sistemi

Hareket Sistemleri Unity C# 2
RigidbodyileYüzmeSistemi .cs
C#
using UnityEngine;
public class SwimmingController : MonoBehaviour
{
    public float swimSpeed = 3f;
    public float gravity = -5f;
    public bool inWater = false;

    private CharacterController cc;
    private Vector3 velocity;

    void Start() => cc = GetComponent<CharacterController>();

    void Update()
    {
        if (inWater)
        {
            float v = Input.GetAxis("Vertical");
            float h = Input.GetAxis("Horizontal");
            float up = Input.GetKey(KeyCode.Space) ? 1f :
                       Input.GetKey(KeyCode.LeftControl) ? -1f : 0f;

            Vector3 dir = transform.forward * v + transform.right * h + Vector3.up * up;
            cc.Move(dir * swimSpeed * Time.deltaTime);
        }
        else
        {
            velocity.y += gravity * Time.deltaTime;
            cc.Move(velocity * Time.deltaTime);
        }
    }

    void OnTriggerEnter(Collider other)
    { if (other.CompareTag("Water")) inWater = true; }

    void OnTriggerExit(Collider other)
    { if (other.CompareTag("Water")) { inWater = false; velocity = Vector3.zero; } }
}

Açıklama

Oyuncu suya girdiğinde hareket modunu değiştiren, yavaşlayan ve yüzmeye geçen sistem.

Etiketler

Rigidbody Yüzme Su Buoyancy

Nasıl Kullanılır?

1. Su objesine Box Collider ekle, Is Trigger = true yap.

2. Su objesine 'Water' tag'i ver.

3. Bu scripti CharacterController'lı Player'a ekle.

4. Space = yukarı yüz | Ctrl = aşağı dal.

5. Su trigger'ına girince yüzme moduna geçer.

Unity 2022+ ve Unity 6 ile uyumludur.

MonoBehaviour tabanlı scriptleri Assets klasörüne .cs olarak kaydedin.