How to make a ball roll over slopes; could someone fix my code?

Hey everyone-

I have a hill terrain in unity 2d. I want a ball to be able to roll over the lumps as a key is pressed. The AddForce method doesn’t seem to work. How should I script this? With transforms?

I used the add force/thrust method:

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

public class BallSpeed1 : MonoBehaviour
{
    public Rigidbody2D rb;
    public float thrust = 1f;

    private void FixedUpdate()
    {
        rb.AddForce(transform.right * thrust);
    }
}

but once I turn up the thrust amount, the object (a ball) will make it up the hill but then start flying around in the air like a balloon when you let go of the knot.

Thanks to those who can help!

But you gotta admit… that’s a cool effect, especially if you mix it with a raspberry sound!!

So what you’re doing with this line:

takes into account the rotation of the ball. In other words, transform.right spins along with the ball (assuming this script is ON the ball)… just like a deflating spinning balloon’s thrust vector.

Perhaps you want to use Vector2.right instead??

In other news, I was playing around with a 2D “pump track” kinda thing and your question reminds me of it.

My code only pumps straight up and down, rider directly into the wheel axis.

Screenshot below, full package attached.

9583180--1357105--Screenshot-KurtGame-133498163096043420.png

9583180–1357108–Pumping.unitypackage (409 KB)

Your concept is helpful. I fixed my weird flying issue by just locking the rotation on the Z axes. But thanks for the help.

Hey Kurt-

I’m trying to make it so that the force can only be applied if the ball is touching the ground, but for some reason this code doesn’t work. Do you know why?

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

public class BallSpeed1 : MonoBehaviour
{
    public Rigidbody2D rb;
    public float thrust = 1f;
    public bool grounded;


    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            grounded = true;
        }
    }

    private void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            if (grounded == true)
            {
                rb.AddForce(Vector2.right * thrust);

            }
        }
    }
}

The ground object is tagged Ground.

This is a 3D method, not a 2D method :slight_smile:

If that isn’t it, well then it is…

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

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
  • you’re getting an error or warning and you haven’t noticed it in the console window

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 names of the GameObjects or Components involved?
  • 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 supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

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

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

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://discussions.unity.com/t/839300/3

If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

I have a feeling the problem is you’re using OnTriggerEnter. This method is for triggers, not collisions (also, as Kurt mentioned, it’s the 3D version). You provably want to use OnCollisionEnter2D instead.

That’s just a workaround because Transform right won’t be moving now. Use Vector2.right as Kurt suggested. Surely you want this thing to rotate anyway?

private void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            if (grounded == true)
            {
                rb.AddForce(Vector2.right * thrust);
            }
        }
    }

Doing this per-frame means that a faster frame-rate will mean you add more force. You don’t want this frame-rate dependent so either apply forces during the FixedUpdate based upon logic/input you gather during Update or apply as an impulse scaled by the Time.deltaTime.

1 Like