I have a space ship and some coins in my game. When I move my space ship towards the coins I want to have a magnetic effect so that the spaceship draws all the coins in. The code below does not work in my case. I have a circlecollider2d attached to a child of all my coins. The idea is when any coin comes nearer and nearer towards my spaceship the spaceship draws all of the coins in. But it’s not working. Any help, please?
I do something similar to my fuel drops for my ship.
This script is attached to your (coin) that has a rigidbody component. Obviously you might want to set your distance a bit closer in your case
public class gather : MonoBehaviour
{
Transform player;
public float distance;
Rigidbody move;
// Use this for initialization
void Start () {
move = GetComponent<Rigidbody>();
player = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update ()
{
distance = Vector3.Distance(transform.position, player.transform.position);
if (distance < 115900)
{
move.AddForce((player.transform.position - transform.position) * (16));
}
}
}
As written above, this would be my solution. You need a Collider2D set to trigger on the object you want this object to be attracted to and set its tag to “PlayerShipTag”. I would also suggest to store magnetStrength and magnetRange on the player, to avoid attracting objects differently, but that is a different topic.
public class MagnetAttractable : MonoBehaviour {
[SerializeField] private float magnetStrength;
[SerializeField] private float magnetRange;
private Rigidbody2D ownRigidbody;
private Transform attractedTo;
private void Awake () {
ownRigidbody = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "PlayerShipTag") {
attractedTo = other.transform;
}
}
private void OnTriggerExit2D (Collider2D other) {
if (other.gameObject.tag == "PlayerShipTag") {
attractedTo = null;
}
}
private void FixedUpdate () {
if (attractedTo != null) {
Vector3 direction = (attractedTo.position - transform.position).normalized;
float forceFactor = 1 - direction / magnetRange; // magnetism is actually inversely proportional to the square of distance, but this is good enough approximation
if (forceFactor > 0) {
ownRigidbody.AddForce(direction * magnetStrength, ForceMode2D.Force);
}
}
}
}