Unity'de Sert Cisim Mıknatısı Oluşturmak için C# Komut Dosyası

Aşağıda Unity: içindeki Katı cisimlere karşı mıknatıs benzeri davranışlar üreten komut dosyası bulunmaktadır.

Sharp Coder Video oynatıcı

Adımlar

  • yeni bir komut dosyası oluşturun, onu SC_RigidbodyMagnet olarak adlandırın ve içine aşağıdaki kodu yapıştırın:

SC_RigidbodyMagnet.cs

using System.Collections.Generic;
using UnityEngine;

public class SC_RigidbodyMagnet : MonoBehaviour
{
    public float magnetForce = 100;

    List<Rigidbody> caughtRigidbodies = new List<Rigidbody>();

    void FixedUpdate()
    {
        for (int i = 0; i < caughtRigidbodies.Count; i++)
        {
            caughtRigidbodies[i].velocity = (transform.position - (caughtRigidbodies[i].transform.position + caughtRigidbodies[i].centerOfMass)) * magnetForce * Time.deltaTime;
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if(!caughtRigidbodies.Contains(r))
            {
                //Add Rigidbody
                caughtRigidbodies.Add(r);
            }
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if (caughtRigidbodies.Contains(r))
            {
                //Remove Rigidbody
                caughtRigidbodies.Remove(r);
            }
        }
    }
}

  • Yeni bir GameObject oluşturun ve buna SC_RigidbodyMagnet betiğini atayın
  • Yeni oluşturulan bir nesneye bir Küre Çarpıştırıcısı ekleyin, onu Tetikleyici olarak işaretleyin ve yarıçapını artırın
  • Birkaç Küp oluşturun ve bunlara bir Sert Cisim bileşeni ekleyin

Oynat tuşlarına basın, ardından SC_RigidbodyMagnet komut dosyasına sahip Object'i Rigidbody'lerin üzerine taşıyın, Rigidbody'lerin nasıl içeri çekildiğine dikkat edin.

Önerilen Makaleler
Unity'nin Rigidbody Bileşeniyle Çalışmak
Unity'de Fizik Tabanlı Bir Yarış Oyunu Oluşturmak
Unity Fare İmlecini Kullanarak Sert Cisim Nasıl Sürüklenir
Unity'e Zıplayan Top Fiziği Ekleme
Unity Oyununda Madencilik Mekaniklerini Uygulamak
DestroyIt - İmha Sistemi - Unity Asset Store Paket İncelemesi
Unity'de Roketatar Oluşturma