Calculating offset for rotation pivot of this boxcast

9261285--1295781--upload_2023-8-30_11-26-9.png

I’m currently using a boxcast to simulate something like a Laser effect. However, when I change the angle to match the z rotation the pivot isn’t adjusting. Here is the code I have so far:

    private void Fire(Vector2 originPos,float angle,float size, float range,LayerMask mask){
        Vector3 startPos = originPos + (Vector2.right * range/2);
        Vector2 boxSize = new Vector2(range,size);
        Gizmos.BoxCast(startPos,boxSize,angle,_direction,_distance); // Visualization

Rotating around any arbitrary point involves:

  • offset everything to that point
  • rotate
  • un-offset from that point

AFAIK there is no Gizmos.BoxCast() in Unity. If there is, I sure don’t see the docs for it. Therefore, look there first. It’s probably some random extension method. Is it written properly?

Cool, start printing out values, find out what is going on.

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.

The Gizmos.Boxcast method was taken from this thread:
https://discussions.unity.com/t/632862

I believe what I need to do is find a formula that modifies the Y position of the box based on the angle variable which is based on the z rotation of the sprite.

Hard to say from unformatted code.

I think the first thing you want to decide is:

  • is that boxcast visualization code correct

  • is your arrow rotator correct

Whatever it is, the same three steps apply:

  • offset
  • rotate
  • de-offset

Set up an ultra-simple demo with known numbers, find out!

I’m getting close, the offset is a bit far but the idea is there!

            Vector2 originPos = transform.right + transform.right * _range/2;

9261453--1295832--upload_2023-8-30_12-55-22.png

A boxcast start position is your origin, that’s it, don’t modify it, it’s where it starts. The box size itself is the size, not (range, size) but (size, size).

I’ve not used the gizmo code but they represent the exact same things you’d pass to the BoxCast method so I’m not sure why you’re not using those directly.

I cannot see the rest of your code but given the names of the gizmo args, it’s this:

private void Fire(Vector2 originPos,float angle,float size, float range, LayerMask mask)
{
    // No idea where "_direction" is coming from here.
    Gizmos.BoxCast(originPos, new Vector2(size, size), angle, _direction, range);
}

Oooh, good point: make sure you’re divorcing angle from direction… it appears that any arbitrary angle of rotated box may be cast out at any arbitrary vector direction.

eg, I could have a box unrotated and cast it up and to the right.

Not sure if the draw code takes that into consideration. To me it looks like it conflates those two, or ignores one.

Okay, I think I cracked the code for 2D boxcasting and visualization therein.

Run the enclosed scene, read the directions, and please update me if anything doesn’t line up. I get perfect results with what is actually being boxcasted in the Physics2D world.

(Would really love it if @MelvMay agreed or disagreed with this approach. :slight_smile: )

Code:

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

// @kurtdekker - To visualize BoxCast2Ds
//
// Test this with TestBoxCast2DGizmos scene / script.

public static class BoxCast2DGizmo
{
    public static void BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance = Mathf.Infinity)
    {
        // clockwise going around from lower left
        Vector2[] starts = new Vector2[4];

        float w = size.x / 2;
        float h = size.y / 2;

        starts[0] = new Vector2( -w, -h);
        starts[1] = new Vector2( -w, +h);
        starts[2] = new Vector2( +w, +h);
        starts[3] = new Vector2( +w, -h);

        Quaternion q = Quaternion.Euler( 0, 0, angle);

        // rotate and add offsets
        for (int i = 0; i < starts.Length; i++)
        {
            starts[i] = q * starts[i];

            starts[i] = starts[i] + origin;
        }

        // draw the origin box
        for (int i = 0; i < starts.Length; i++)
        {
            int j = (i + 1) % starts.Length;

            Gizmos.DrawLine( starts[i], starts[j]);
        }

        float castDistance = float.IsInfinity(distance) ? 1E+5f : distance;

        Vector2 offset = direction.normalized * castDistance;

        Vector2[] finishes = new Vector2[4];
        for (int i = 0; i < starts.Length; i++)
        {
            finishes[i] = starts[i] + offset;
        }

        // draw the destination box
        for (int i = 0; i < finishes.Length; i++)
        {
            int j = (i + 1) % finishes.Length;

            Gizmos.DrawLine( finishes[i], finishes[j]);
        }

        // streaks between them
        for (int i = 0; i < finishes.Length; i++)
        {
            Gizmos.DrawLine( starts[i], finishes[i]);
        }
    }
}

9261741–1295880–BoxCast2DGizmo.unitypackage (18.4 KB)

Downloading and checking, please hold. :wink:

Although fairly expensive, it brings the following asset store item to mind: [Released] Draw XXL

Yes, that pretty much is correct. A minor change is to ensure that when distance = infinity, it’s handled correctly in which case the actual cast distance is:

var castDistance = float.IsInfinity(distance) ? 1E+5f : distance;

And that is why we do code reviews! Thanks Melv… I have no idea what mayhem would come from multiplying a Vector3 by infinity… it would probably become all infinity, but who knows if it might unearth future edge cases, especially once it is handed further down into draw code. Clipping the distance at 100k is fairly reasonable for any world made of single precision floats.