Help with point position

Hello, can someone tell me why this doesn’t work like i expect?

I have two object. One’s transform “rotates” around the other in 2D based off of the angle from the center of the screen. However, when i walk around, in a straight line on say the X-Axis, it continually flips around the object multiple times. It’s even crazier when walking up and down. I’d expect it to stay in one location and then flip after the (0,0) point is crossed.

    private void Update() {
        if (isActiveAndEnabled){
            Vector2 center = mainCamera.WorldToScreenPoint(new Vector2((Screen.width/2f),(Screen.height/2f)));
            float angle = Vector2.SignedAngle(center, mainCamera.WorldToScreenPoint(MyChestTransform.position));
            Vector2 offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * 120f;
            transform.Find("Slots").position = ((Vector2)mainCamera.WorldToScreenPoint(MyChestTransform.position)) + offset;
        }
    }

I cannot reason about lines of code like the above without rewriting them to be “normal people code.”

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

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 break it up properly, 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 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.

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 or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

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.

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:

When in doubt, print it out!™

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

Thanks greatly for the links and advice! I’ve rewritten this a million times, so frustration has lead to it not being as tidy as it should be. Additionally, I did have debug lines but ripped them out here to try to make it less of a slog to read through, i seemed to have failed. :slight_smile:

I’ll break it apart and try to simplify it and come back if i’m still having issues. I have a feeling it’s a problem with determining the angles of the points and the Camera’s “WorldToScreenPoint” not quite doing what i expect.

If it’s any consolation to you, even after a decade of using Unity, I still seem to always end up re-learning how something as simple as WorldToScreenPoint() (and especially ScreenToWorldPoint) works every time I use it. :slight_smile:

Debug.Log() is my very best friend.

1 Like

The method SignedAngle returns an angle in degree while Mathf.Sin expects an angle in radians. Unity provides two conversion factors you can use. You need to multiply your angle by Mathf.Deg2Rad to get radians. Radians may be counter-intuitive as a full circle is 2*PI. However it’s actually much more natural in math. It’s the actual arc-length of a certain angle along the unit circle. That’s why all trigonometric functions work with radians. Unity’s methods like Quaternion.Euler however use angles in degree.

1 Like

BLAH. That was definitely part of the problem!!! Thanks so much! The other part was the darn WorldToScreenPoint causing some confusion with the transform’s final positioning since it’s on a UI canvas…

I revamped the code and took a step back and decided to base the locations off of my player and the chest, and not the center of the screen, additionally, i simplified it by using Atan2 to work out the angle. for anyone who may struggle with this in the future, here’s my working code. A lot of this i tried to pull out of update, but it’s required to be there so it can updated for the real time positional vector math. Not sure how performant this is in the long run…

    private void Update() {
        if (isActiveAndEnabled){
            Vector2 chestPos = mainCamera.WorldToScreenPoint(MyChestTransform.position);
            Vector2 playerPos = mainCamera.WorldToScreenPoint(Player.MyInstance.transform.position);
            Vector2 dir = chestPos - playerPos;
            float angle = Mathf.Atan2(dir.y, dir.x);
            Vector2 point = new((120f*Mathf.Cos(angle))+chestPos.x,(120f*Mathf.Sin(angle))+chestPos.y);
            transform.Find("Slots").position = point;
        }
    }

This is the beauty of breaking code up into one step at a time and printing it out: you would notice something is numerically funny if you had put known data in such as a 45-degree angle and somehow did not get 0.7071 back from both Sin and Cos.