My guy is auto moving right

another version of this code used to work fine but after swapping out “transform.position =” with .MovePosition it keeps moving my main character to the right without touching anything. Can anyone spot the error? I can get rid of the clamps if it makes it easier


            gameObject.GetComponent<Rigidbody2D>().MovePosition(new Vector2(Mathf.Clamp(transform.position.x + 
            Joystick.GetComponent<UltimateJoystick>().GetHorizontalAxis() * Time.deltaTime *
            3f, CameraFollows.leftLimit + objectWidth, CameraFollows.rightLimit - objectWidth), 
            Mathf.Clamp(transform.position.y + Joystick.GetComponent<UltimateJoystick>().GetVerticalAxis() * 
            Time.deltaTime * 1.5f, CameraFollows.bottomLimit, CameraFollows.topLimit - objectHeight)));

Theres a lot going on in that, why not break it out, and add debug statements so you can check values

WOW! That is a spectacular tangle. As bugs suggested, rip it apart so you can debug it.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting lots of code on one line DOES NOT make it any faster. That’s not how compiled code works.

The longer your lines of code are, the harder they will be for you to understand them.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

Once you turn it into usable code it is time to start debugging!

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

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

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

Oof, that is some gnarly code. Not only is it hard to read and debug, it also follows bad performance practices. Here are some tips:

  1. Move many of the calculations to variables.
  2. Use self-documenting names for the variables. This will even help you (the author) understand your code better.
  3. Don’t call GetComponent multiple times for the same component in the same function
  4. Don’t call GetComponent at all in an Update or for user input. Use GetComponent in Start or Awake and store the return value for future usage.
  5. Put your code on multiple lines. This allows you to add breakpoints, or if you’re not familiar with a debugger, you can at least log output to the console easier.

Following that advice, here’s how I’d change the code:

private Rigidbody2D _rigidBody;
private UltimateJoystick _joystick;

private void Start() {
  _rigidBody = gameObject.GetComponent<Rigidbody2D>();
  _joystick = gameObject.GetComponent<UltimateJoystick>();
}

private void FixedUpdate() {
  var axes = new Vector2(
    _joystick.GetHorizontalAxis(),
    _joystick.GetVerticalAxis()
  );
  
  var minX = CameraFollows.leftLimit + objectWidth;
  var maxX = CameraFollows.rightLimit - objectWidth;
  var goalX = transform.position.x + axes.x * Time.deltaTime * 3f;
  var finalX = Mathf.Clamp(goalX, minX, maxX);
  
  var minY = CameraFollows.bottomLimit;
  var maxY = CameraFollows.topLimit - objectHeight;
  var goalY = transform.position.y + axes.y * Time.deltaTime * 1.5f;
  var finalY = Mathf.Clamp(goalY, minY, maxY);
  
  var finalPos = new Vector2(finalX, finalY);
  
  _rigidBody.MovePosition(finalPos);
}

When compiled, it results in nearly the same output as your code (assuming the compiler is doing it’s job). But, it’s much more readable.

Now that that’s done, you can start debugging individual lines of code. The best way is to add breakpoints to the lines you want to inspect. But if you’re not familiar with an integrated debugger, you can at least add logging to see what exactly is going on.

For example, here’s a way to get useful information from your code:

var sb = new StringBuilder();
sb.AppendLine("Debug RigidBody:");
sb.AppendLine($"Current position: {transform.position}");
sb.AppendLine($"axes: {axes}");
sb.AppendLine($"minX: {minX}");
sb.AppendLine($"maxX: {maxX}");
sb.AppendLine($"goalX: {goalX}");
sb.AppendLine($"finalX: {finalX}");
sb.AppendLine($"minY: {minY}");
sb.AppendLine($"maxY: {maxY}");
sb.AppendLine($"goalY: {goalY}");
sb.AppendLine($"finalY: {finalY}");
sb.AppendLine($"finalPos: {finalPos}");
Debug.Log(sb.ToString());

Put that right above the _rigidBody.MovePosition line. Play the game in the Editor. Then look at the console output. See if the values make sense

Aside from coding and debugging advice, here are a few thoughts:

  1. Is your code running in Update instead of FixedUpdate? You’ll want to use FixedUpdate for physics code.
  2. You’re using Time.deltaTime. This tells me something is wrong. Either your code in Update, or you’re using the wrong deltaTime. In FixedUpdate, you should be using Time.fixedDeltaTime
  3. Lastly, MovePosition follows the Physics2D interpolation settings. Instead of MovePosition, you could try _rigidBody.position = finalPos to “teleport” the object. Not recommended ultimately, but if this works better, it’ll give you some insight into what’s going wrong.

Best of luck to you

OK so I found out the problem isn’t anywhere in my code but because I checked the “Simulated” box on my rigidbody2d component. Now it doesn’t move at all but the animations work.

That doesn’t really make sense TBH, the problem has to be in your code.

The simulated option is on by default. Unchecking it means there’s nothing in the simulation so it’s pointless having the component there. I don’t see how that relates to “auto moving right”.

Calling MovePosition on a Rigidbody2D that’s not in the simulation will do nothing at all.

so you had code that was not working, you changed something else but the code is still not working, and that makes you conclude that the code is correct?

As already noted in my first reply above, start debugging.

You will know when you are finished debugging either when:

  • it works
  • or you can report the issue in these terms:

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual relevant Unity3D documentation you used to cross-check your work (CRITICAL!!!) (eg, “docs say this, I’m doing this, here’s the code, and it’s not working”)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?