AddForce on RigidBody2D not working

Hi,
I’m trying to move a RigidBody2D using AddForce which is not working (body doesn’t move). Am I missing something?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Changes character on left mouse button
/// </summary>
public class MyClass: MonoBehaviour
{
    [SerializeField]
    GameObject prefabCharacter0;
    [SerializeField]
    GameObject prefabCharacter1;
    CircleCollider2D radius;
    // saved for efficiency
    float colliderHalfRadius;
    // need for location of new character
    GameObject currentCharacter;
    float xPosition = 0.0f;
    Rigidbody2D ship;

    public int Thrustforce = 5;

    Vector2 thrustDirection;
    /// <summary>
    /// Use this for initialization
    /// </summary>
    void Start()
    {
        radius = GetComponent<CircleCollider2D>();
        ship = GetComponent<Rigidbody2D>();

        currentCharacter = Instantiate<GameObject>(
            prefabCharacter0, Vector3.zero,
            Quaternion.identity);


        colliderHalfRadius = radius.radius / 2;


        thrustDirection = transform.position;
        thrustDirection.x = xPosition;
        thrustDirection.y = 0;
    }

    /// <summary>
    /// Update is called once per frame
    /// </summary>
    void Update()
    {
        // change character on left mouse button
        if (Input.GetAxis("Rotate") < 0 )
        {
            // save current position and destroy current character
            Vector3 position = currentCharacter.transform.position;
            Destroy(currentCharacter);

                currentCharacter = Instantiate(prefabCharacter0,
                    position, Quaternion.identity);
        }

        if (Input.GetAxis("Rotate") > 0)
        {
            // save current position and destroy current character
            Vector3 position = currentCharacter.transform.position;
            Destroy(currentCharacter);
                currentCharacter = Instantiate(prefabCharacter1,
                    position, Quaternion.identity);
        }
    }

    void FixedUpdate()
    {
        if (Input.GetAxis("Ship") > 0)
        {
            ship.AddForce(5 * thrustDirection, ForceMode2D.Impulse);
        }
    }
}

Did you ever solve this? I’m having the same issue.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

If the code is running, try hard-coding larger and larger values of movement and/or force in, going up by 10x each time. If you were adding force 12, try force 120, then 1200, then 12000

Try make an empty scene, put a cube in, remove the collider, add an RB2D and write a script to send it flying with a huge force. You’ll see it moves.

First of all, thanks so much for the prompt reply.
Secondly, yeah, that was the problem. The “real” issue is my raycast to see if I’m hitting the ground is not working. My game, Ninja Eggs, is a simple Angry Birds clone. My 9 year old grandson had an idea for a new level and he wanted a power up that would give the “egg” a Rocket Pack. While equipped, the egg would hover over the ground and a reticle will be projected in front of the egg which can be dragged and released to “launch” the egg at that target. This is to allow the player to hit targets from below which is the only way they can be hit on this level.

TL/DR

But I’m trying to implement the classic hover algorithm where you raycast to see if you’re approaching the desired hover distance and apply force to stay off the ground.

The background is on the Ignore Raycast layer and my ground (Grassy Ground) is on the default layer:

7474630--918860--upload_2021-9-5_18-56-55.png

7474630--918863--upload_2021-9-5_18-57-8.png

   private void Hover()
    {
        _rigidbody2D.freezeRotation = true; // don't allow egg to rotate while hovering
        Transform tf = rocketPack.transform;
        Debug.Log($"layerMask: {layerMask}");
        Debug.DrawRay(tf.position, -tf.up * 1, Color.red);
        RaycastHit2D hit = Physics2D.Raycast(tf.position, -tf.up * 1, hoverHeight, layerMask);
        if (hit.collider != null)
        {
            Debug.Log("Hover raycast hit.");
            float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
            Vector2 appliedHoverForce = transform.up * proportionalHeight * hoverForce * 1.05f;
            Debug.Log($"proporionalHeight({proportionalHeight}) = ({hoverHeight} = {hit.distance}) / {hoverHeight}. appliedHoverForce = {appliedHoverForce}.");
            _rigidbody2D.AddForce(appliedHoverForce);
        }
    }

I’m never getting inside the if (hit.collider != null) block.
If I take off the layer mask the egg gets launched up into space :slight_smile:

This is what the Debug.Log emits for the layerMask.
7474630--918875--upload_2021-9-5_19-4-10.png

I’ve tried switching it around and assigning Ignore Raycast to the layerMask SerializedField and passing ~layerMask to the RaycastHit2D call but that didn’t work either.

The Debug.DrawRay looks correct:
7474630--918866--upload_2021-9-5_19-1-29.png

I’m tempted to punt and just put an empty GameObject at the bottom of the egg with a box collider to hold it off the ground but I was hoping for a little “bounce” while it’s hovering.

BTW: Ninja Eggs is available for free on the Apple App Store and Google Play :slight_smile:

7474630--918875--upload_2021-9-5_19-4-10.png