0
\$\begingroup\$

I want to create a black hole like gravity pull effect in Unity2D, and used that code for this:

using UnityEngine;

public class Attractor : MonoBehaviour
{
    public Transform player;
    private Rigidbody2D playerBody;
    public float influenceRange;
    public float intensity;

    void Start()
    {
        playerBody = player.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        float distanceToPlayer = Vector2.Distance(player.position, transform.position);
        
        if (distanceToPlayer <= influenceRange)
        {
            Vector2 pullForce = (player.position - transform.position).normalized * intensity;
            playerBody.AddForce(pullForce, ForceMode2D.Force);
        }
    }
}

Intensity is set to 5 and influenceRange to 4.

All references are set up correctly.

In the Unity Editor the pull effect seems much stronger than on android though.

Pull Effect on android:

Pull effect on android

I can't show pull effect in the editor because I'm not home now, but there the ball flies through the sky and gets attracted much stronger.

Any help is appreciated!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Try putting physics effects in FixedUpdate instead of in Update so they're not impacted by differences in rendering framerate. \$\endgroup\$
    – DMGregory
    Commented May 11 at 21:15
  • \$\begingroup\$ Are you looking for How to limit framerate in Unity? \$\endgroup\$
    – DMGregory
    Commented May 12 at 11:08

1 Answer 1

0
\$\begingroup\$

I have found a much more customizable and easy solution for this. I have just added a point effector 2d to the gameobject along with a circle collider with isTrigger and usedByEffector boxes checked.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .