I am trying to simulate magnetism. Each of my particles is a monopole, and has a bool called positive. I am trying to make it so that if two objects have the same value for the bool, they will repel each other, but otherwise they attract. However, everything I’ve tried always ends up either attracting no matter what, or repelling no matter what. This is my most recent attempt (I have removed excess code that would only make it confusing to figure out the problem and is irrelevant to my question):
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
public class Magnetic : MonoBehaviour
{
public static List<Magnetic> Mags;
public float magneticStrength;
public bool positive;
public Rigidbody rb;
void FixedUpdate()
{
foreach (Magnetic Mag in Mags)
{
if (Mag != this)
{
Magnetize(Mag);
}
}
}
void OnEnable()
{
if (Mags == null)
Mags = new List<Magnetic>();
Mags.Add(this);
}
void OnDisable()
{
Mags.Remove(this);
}
void Magnetize(Magnetic magneticTarget)
{
Rigidbody rb2 = magneticTarget.rb;
Vector3 direction = rb.position - rb2.position;
float distance = direction.magnitude;
var magTar = gameObject.GetComponent<Magnetic>();
var pos = Convert.ToSingle(positive);
var pos2 = Convert.ToSingle(magTar.positive);
if (distance == 0f)
return;
else if (distance >= (Particle.instance.particleSize * 4f))
return;
else
{
float f = 10 * (magneticStrength * magTar.magneticStrength) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * f;
var x = 2 * (pos - pos2) * (pos2 - pos) + 1;
rb2.AddForce(force * x);
}
}
}