Search Unity

My magnetic effect breaks if I add an Impulse force in Start

Discussion in 'Physics' started by mrCharli3, Jan 11, 2019.

  1. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    976
    So I create a magnetic effect, where objects are sucked to my player.
    It works great.

    Now I want those same objects to get a little Impulse force when they spawn. This has somehow reversed my magnetic effect? The objects are now pushed away from the player...

    All I did was add this Line in Start():

    _rb.AddForce(_forwardThrust, _upThrust, _forwardThrust, ForceMode.Impulse);


    Full Script here:

    Code (CSharp):
    1. public class RandomMagneticForce : MonoBehaviour
    2. {
    3.     private bool _inside;
    4.     private Transform _magnet;
    5.     private Rigidbody _rb;
    6.     private SphereCollider _sphere;
    7.     float radius = 5f;
    8.     [SerializeField]
    9.     private float _delay;
    10.     [SerializeField]
    11.     private float _force = 70;
    12.     [SerializeField]
    13.     private float _upThrust, _forwardThrust;
    14.  
    15.     void Start()
    16.     {
    17.         _magnet = GameManager.instance.ActivePlayer.gameObject.transform;
    18.         _rb = GetComponent<Rigidbody>();
    19.         _sphere = GetComponent<SphereCollider>();
    20.         _inside = false;
    21.         _rb.AddForce(Random.Range(-_forwardThrust, _forwardThrust), _upThrust, Random.Range(-_forwardThrust, _forwardThrust), ForceMode.Impulse);
    22.     }
    23.  
    24.     void OnTriggerEnter(Collider other)
    25.     {
    26.         if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
    27.         {
    28.             _inside = true;
    29.         }
    30.     }
    31.     void OnTriggerExit(Collider other)
    32.     {
    33.         if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
    34.         {
    35.             _inside = false;
    36.         }
    37.     }
    38.  
    39.     private void Update()
    40.     {
    41.         if (_delay > 0)
    42.             _delay -= Time.deltaTime;
    43.  
    44.         if (_inside)
    45.         {
    46.             if (_delay <= 0)
    47.             {
    48.                 Vector3 magnetField = _magnet.position - transform.position;
    49.                 float index = (radius - magnetField.magnitude) / radius;
    50.                 _rb.AddForce(_force * magnetField * index);
    51.             }
    52.         }
    53.     }
    54. }