Search Unity

Question AddForce to object

Discussion in '2D' started by Rachan, Oct 1, 2022.

  1. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    781
    Hi there!

    I really want to know how to properly push some 2D object with riggidbody2d move toward to specific position?

    actually I used to make a script like this
    Vecto3 direction = targetPosition - objectPosition;
    objectRig.AddForce(direction.normallize* force,Force)

    it should be push this object to targetPosition Right?

    But it just moving to that targetPosition and higher (Y) a bit I don’t know why…
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,497
    You cannot expect anyone to comment on this because it's not even valid code. If you have a script question then please post valid script using code-tags.

    Calculate the direction, normalise it, scale it by time or speed (if you wish) and manipulate the velocity by either indirectly adding as a force or setting the velocity directly. There is no "properly", there's only how you can/need to do it in your project given how your stuff needs to move/interact etc.

    Also, use Vector2 for 2D, not Vector3. If you normalise a Vector3 and it has a non-zero Z value, it'll be normalised along with that affecting the unit-normal produced.
     
    Rachan likes this.
  3. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    781
    Ok Thank you very much!
    and so sorry I thought I found the way to do it

    But I have another question, so I have to go to another post in the right place right?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,744
    You might want to review basic physics to understand the difference between force and velocity and position. Adding force changes velocity. Velocity changes position. Each is a derivative (or integral) of the next.

    If you just want a Rigidbody to move in a direction, just set its .velocity field. You can smoothly increase velocity over several frames, or decrease it, to smooth movement.

    If you want a Rigidbody to gain speed in a direction, you use AddForce(). If you do this the RB will continue accelerating faster and faster, slowed only by impacts or drag (friction).

    If you want to control velocity through force, you WILL need some kind of closed-loop controller, such as a PD or even PID controller, to adjust the force such that it targets a given velocity. For 99% of games this would be a silly approach that would needlessly complicate what could be accomplished simply by setting the .velocity directly.