Struggling with player/weapon flipping based on direction

Hi,

Please bare with me while I try to explain my issue, and also please note i’ve spend the past week and a half teaching myself unity so be gently with your replies :wink:

My goal is to create a 2D topdown shooter, i have a player game object which has an animated sprite attached to it. As part of my playermovement code, i’m flipping the character on it’s X axis depending on which way the player is moving. This works fine.

I have a seperate “Weapon” GameObject which has a sprite attached (no animation here, just an object with a sprite renderer). My Intent later down the line is to add additional weapons.

If the player rotates the right thumbstick on a gamepad, the weapon “orbits” around the player to reflect the aim direction, this works 100% as I want.

So the problem I have is how to attach the weapon to the player. I’ve tried two different approaches, both of which come with their own problems:

  1. ClickOps the weapon game object onto the player object (so the weapon becomes a child of the Player)

While this works as far as making the weapon move around with the player, the problem I now have is if the player changes direction (ie, moves to the left) the weapon is then flipped and the movement in that direction is inverted. This could be solved potentially via code but honestly i’ve spend hours on this today and my brain really is starting to ache trying to understand the math involved in doing the opposite of what i’ve already spent a day trying to achive in getting the weapon to rotate around the player)

  1. Leave the player and weapon as two seperate game objects, and inside the Weapon code (PlayerWeaponSlot.cs ← with intent to hold different weapons) update the positionof the weapon game object to match that of the player.

I had very strange experience with this where if i move around using the left thumbstick, all seems okay, meaning the weapon “attaches” to the player". However as soon as i aim (with right thumbstick) the weapon resets position to 0, 0, 0 and proceeds to rotate on the spot.

Ideally i would prefer assistance with number 2 since i feel in the long run it will enable better handling of multiple weapons down the line. Here’s some code the show how i’m getting the above results.

 private void Update()
{
     // Get the player position:
     playerPosition = playerRigidBody.transform.position;

     // Get the player Rotation:
     playerRotation = playerRigidBody.transform.rotation;

     // Attach the weapon to the player:
     weaponSprite.transform.position = new Vector3(playerPosition.x + weaponDistanceFromPlayer, playerPosition.y, playerPosition.z); // playerPosition;

     // Get the players aim direction
     aimDirection = playerAim.ReadValue<Vector2>();

     AimWeapon();
}

The line to note here is where i’m setting weaponSprite.transform.position. Also note that weaponDistanceFromPlayer is a float representing the distance from the orbits center (this basically gives the weapon distance from the player so it “orbits”)

So the way i understand it, since Update() is triggered every frame, surely my weaponSpride.transform.position should always match that of my playerPosition regardless of if i’m moving or aiming?

For context, here’s my aim method:

    private void AimWeapon()
    {
        if (aimDirection.y != 0 || aimDirection.x != 0)
        {
            // Flip the weapon into the direction it's aiming
            if (WeaponIsFacingRight())
            {
                weaponSprite.flipX = true;
                weaponSprite.flipY = false;
            }
            else
            {
                weaponSprite.flipX = true;
                weaponSprite.flipY = true;
            }



            // Get the x and y aim direction, times by the tick rate and player move speed
            float x = aimDirection.x * Time.deltaTime * moveSpeed;
            float y = aimDirection.y * Time.deltaTime * moveSpeed;

            //convert the input into an angle in radians, and convert that into degrees
            rads = Mathf.Atan2(y, x);

            float degrees = rads * Mathf.Rad2Deg;

            float weaponPositionX = Mathf.Cos(rads) * weaponDistanceFromPlayer;
            float weaponPositionY = Mathf.Sin(rads) * weaponDistanceFromPlayer;

            // Transform the weapon
            weaponSprite.transform.localPosition = new Vector3(weaponPositionX, weaponPositionY, 0);
            weaponSprite.transform.localEulerAngles = new Vector3(0, 0, degrees);
        }
    }

I really appreciate any assistance with this, if theres any more information i can provide or any questions i can answer please let me know

Thanks!

Anytime you write “Surely…” about your code, that is a tell that it is…

… Time to start debugging! 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

“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.

Thanks for the advice, I’m already aware of the basic Debug.Log(string.Format(“{0}”, variable); etc but wasn’t aware of the additional options you mentioned above so thanks for that. Especially the Break feature. Coming from dotnet core and being so used to being able to debug/step through/over line by line i was a little thrown off when breakpoints didn’t work in full fat visual studio and unity (i come from vscode/dotnet core on linux) (I know i can attach the debugger for this but haven’t properly explored it yet) so Debug.Break() will definetly be a great help going forward!

Turns out I was setting weaponSprite.Transform.position inside Update as well as inside AimWeapon() but setting different values. The line in AimWeapon() was left over from when I was coding the logic to allow the weapon the orbit the player, working through it step by step i wanted to solve the weapon orbiting first THEN figure out how to attach it to the player, having slept and possible consumption of alcohol over the weekend (bank holiday for us UK folk) i guess i forgot i was setting the position reletive to nothing. Now i’m setting the orbit relitive to where the player is inside AimWeapon() AND setting it as a 1:1 of the player.position inside Update() all is working as expected.

While your reply didn’t help directly with my issue i’ll for sure benefit from it in future having learned more about Debug so thanks for that!

Debugger is awesome for certain classes of problems but when you hit a breakpoint, Unity freezes and 100% of the Unity presentation surface is dead, no updates no nothing.

That’s why for interactive software debugging, especially for twitchy reaction style games, Debug.Log() and all the other variants of putting values up onscreen somewhere are generally far more useful.