Search Unity

Resolved AddForce not adding in the wanted direction

Discussion in 'Scripting' started by ArthurHaleta, Jun 12, 2022.

  1. ArthurHaleta

    ArthurHaleta

    Joined:
    Dec 24, 2021
    Posts:
    44
    I want this 'zombie' to move towards the player.
    Code (CSharp):
    1. private Vector2 plrPos;
    2.     private Vector2 direction;
    3.  
    4.     private void Awake()
    5.     {
    6.         plrPos = GameObject.FindGameObjectWithTag("plr").transform.position;
    7.  
    8.         transform.right = plrPos;
    9.         plrPos.Normalize();
    10.  
    11.         GetComponent<Rigidbody2D>().AddForce(plrPos * 100);
    12.     }
    But the zombie just moves down along the y axis. Here is a picture..
    I want to zombies to be moving towards the player. Thanks in advance. Screenshot (18).png
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,456
    Because your "force" comes from a GameObject position. A position in world-space is not a force. A force is something that is added to the velocity. You also change the Transform direction to be a position; again this is all wrong.

    The direction towards the player is "var dirToPlayer = (player.position - zombie.position).Normalize();"

    You can add a force using this direction, scaled by how much force you want.
     
    ArthurHaleta likes this.
  3. ArthurHaleta

    ArthurHaleta

    Joined:
    Dec 24, 2021
    Posts:
    44
    I used the position for direction, as in, direction towards the player. Instead of this, you are saying I should take zombie pos from player pos before using it as a direction? Aren't they both in the end Vector2 values?
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,456
    A Vector2 in the end is just a store of 2 numbers in X & Y. Their meaning is irrelevant. It can store a position, a direction or two speed values if you wanted. The name of the type doesn't indicate it's usage.

    I don't want to go over basic vector math here because TBH there are plenty of basic ones online you could use such as this one:


    Search "unity 2d vector math tutorial" for more choices.
     
  5. ArthurHaleta

    ArthurHaleta

    Joined:
    Dec 24, 2021
    Posts:
    44
    Thanks! The video is actually interesting.
     
    MelvMay likes this.