Projectile firing directions affected by player position in world

,

I have a few example gifs shown below. I am not sure exactly why this is happening but hopefully they help. My code is below the gifs.

Thanks in advance for any help that can be provided!!! I’m also happy to answer any questions.

  1. Here you can see how the speed of my projectiles increase as I aim further away from the player.
    8579659--1149274--1.gif

  2. When I move my player away from (0, 0) on the map, the projectiles stop flying towards my cursor the further I aim to the left of right, but still move correctly if I aim exactly up or down.
    8579659--1149277--2.gif

  3. Finally, if I move to the corner of my map so neither coordinate is 0, the projectiles are strongly biased towards my direction relative to the map center. They only fly straight when my “aim” vector lines up with my “player-map” vector.
    8579659--1149325--3.gif

Script to aim the wand towards the player mouse:

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

public class PlayerAimWand : MonoBehaviour
{
    public event EventHandler<OnShootEventArgs> OnShoot;
    public class OnShootEventArgs : EventArgs {
        public Vector3 wandEndpointPosition;
        public Vector3 shootPosition;
    }

    public Transform aimTransform;
    public Animator wandAnimator;
    public SpriteRenderer wandRenderer;
    private Transform aimWandEndPointTransform;


    private void Awake() {
        aimWandEndPointTransform = aimTransform.Find("WandEndPoint");
        wandAnimator = wandRenderer.GetComponent<Animator>();
    }

    void Update()
    {
        HandleAiming();  
        HandleShooting(); 
    }


    private void SetWandLayerOrder(float angle) {
        if (angle >=0) {
            wandRenderer.GetComponent<SpriteRenderer>().sortingOrder = 0;
        } else  {
            wandRenderer.GetComponent<Renderer>().sortingOrder = 2;
        }
    }

    private void HandleAiming() {
        float angle = Utils.GetMouseAngle(transform) * Mathf.Rad2Deg;
        aimTransform.eulerAngles = new Vector3(0, 0, angle);
        SetWandLayerOrder(angle);
    }

    private void HandleShooting() {
        if (Input.GetMouseButtonDown(0)) {
            Vector3 mousePosition = Utils.GetMouseWorldPosition();
            // Shoot!

            wandAnimator.SetTrigger("Shoot");
            OnShoot?.Invoke(this, new OnShootEventArgs {
                wandEndpointPosition = aimWandEndPointTransform.position,
                shootPosition = mousePosition,
            });
        }
    }
}

Script to fire the projectile:

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

public class PlayerShootProjectiles : MonoBehaviour
{

    [SerializeField] private Transform pfBullet;

    private void Awake() {
        GetComponent<PlayerAimWand>().OnShoot += PlayerAimWand_OnShoot;
    }

    private void PlayerAimWand_OnShoot(object sender, PlayerAimWand.OnShootEventArgs e) {
        Transform spellTransform = Instantiate(pfBullet, e.wandEndpointPosition, Quaternion.identity);
        Vector3 shootDir = e.shootPosition - e.wandEndpointPosition.normalized;
        spellTransform.GetComponent<Projectile>().Setup(shootDir);
    }
}

Script to instantiate a projectile instance:

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

public class Projectile : MonoBehaviour
{
    public float projectileSpeed = 1f;
    public float lifetime = 6f;
    private Vector3 shootDir;
    public void Setup(Vector3 shootDir) {
        this.shootDir = shootDir;
        transform.eulerAngles = new Vector3(0, 0, Utils.GetAngleFromVectorFloat(shootDir));
        Debug.Log(Utils.GetAngleFromVectorFloat(shootDir));
    }
  
    private void Awake () {
        Destroy(gameObject, lifetime);
     }

    private void Update() {
        Debug.Log("shootdir: " + shootDir);
        //Debug.Log("Time.deltaTime: " + Time.deltaTime);
        Debug.Log("projectileSpeed: " + projectileSpeed);
        transform.position += shootDir * Time.deltaTime * projectileSpeed;
    }
}

Edit: One additional script I forgot to include that I use here is how I get my mouse position:

    // Get Mouse Position in World with Z = 0f
    public static Vector3 GetMouseWorldPosition() {
        Vector3 vec = GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
        vec.z = 0f;
        return vec;
    }
    public static Vector3 GetMouseWorldPositionWithZ() {
        return GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
    }
    public static Vector3 GetMouseWorldPositionWithZ(Camera worldCamera) {
        return GetMouseWorldPositionWithZ(Input.mousePosition, worldCamera);
    }
    public static Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, Camera worldCamera) {
        Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
        return worldPosition;
    }

Sounds like an awesome little bug… I’ll just guess you’re inadvertently either assuming (0,0,0) somewhere, or you have the position fed into the shot velocity, or the shot offset, or something like that.

Here’s how to track it down and fix it:

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.

The sketchiest thing I see is line 52 and 53 in your first code block… seems you’re passing a mouse position (screen coords) in along with a world position (transform.position). That seems like a good first place to investigate.

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.

I would also seriously expand this code out vertically, do far fewer things each step and use lots of local variables that you can debug.

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

1 Like

@Kurt-Dekker Thank you so much for this!! I will work my way through all your suggestions here to try and dubug my way to the core cause. I’ll follow up once I’ve figured things out or if I run into a dead end!

1 Like

@Kurt-Dekker It took me quite a bit of troubleshooting, but I finally realized the issue was in this little bit of code!
Vector3 shootDir = e.shootPosition - e.wandEndpointPosition.normalized;

When I was grabbing my shoot direction from my mouse (shootPosition) and the end of my character’s wand I was accidentally normalizing ONLY the wandEndpointPosition instead of the whole difference like I’m showing below.
Vector3 shootDir = (e.shootPosition - e.wandEndpointPosition).normalized;

Its a bit annoying that the cause was pretty much just a trivial typo, but I appreciated this opportunity to learn a bit more about unity debugging! Using the Debug.DrawRay() function really let me figure out the issue was in my original shootDir calculation before ever instantiating a projectile.

Again, thank you so much! I really appreciate this kind of help!

1 Like

YAY! You got it… some of the funnest bugs are little typos, sometimes even more trivial than the one above.

For example, keep a look out for this gem:

if (Input.GetKeyDown( KeyCode.Space));
{
  Debug.Log( "Fire bullet... how come my bullets are CONSTANTLY FIRING even when I don't press space?!!!");
}

(When you see it, you will place your face in your palm…)

2 Likes

It still suprises me that code-editors (obviously not the compiler) do not provide a hint here that something might be incorrect. A conditional with no statement or statement block is a red flag! :wink:

1 Like

It’s getting slightly off topic, sorry about continuing that.

There is already warning CS0642 for that https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0642 and you should see that unless you are ignoring warnings.

8587915--1151137--upload_2022-11-15_17-19-34.png

1 Like

I would never ignore warnings except that in practice, if you use any third-party or Asset Store stuff (required to do just about anything “interesting” or money-making), these packages are generally given zero love and are completely riddled with random warnings, making it impossible to keep your project warning-free.

What Unity needs is a non-source-code way to ignore specific warnings in specific pieces of code. I say non-source-code ways because I am not going to go start adding pragma calls into third party code, even if I could. I should be able to tell Unity, “I acknowledge this warning and I can do nothing about it, stop showing it to me.”

Same goes for the Google Play store: for five years they have been surveying me about how to make the experience better, and every single time I write back “Let me permanently acknowledge your useless warnings (such as “omg this app uses native code!” and “omg your symbols are missing!”) and NEVER AGAIN SHOW IT TO ME!”.

Maddening. It’s literally pure noise that drowns out a potentially-interesting signal.

I guess because I never do this, I never see it!