Raycast going in completely the wrong direction

Hi there,

I’m quite new to C# and trying to create a basic 2D raycast “gun” for a robot sentry in my game. When the robot detects the player using a separate FOV script, I want it wait for a small delay, then shoot a ray at the player to deal damage. I’ve calculated the direction between the robot and the player in the way that all the docs and forums say (destination - origin) but for some reason the raycast is flying off in a (seemingly) random direction.

Can anyone please help me work out what is going wrong here? (the raycast method is at the bottom of the script)

Many thanks in Advance

[RequireComponent(typeof(FOV))]
public class RobotSentry : MonoBehaviour
{

private FOV fov;
protected GameObject hitObject;
public float damageDelay = 0.2f;
public float damage = 1f;
[SerializeField] private GameObject Player;

void Start()
{
fov = GetComponent<FOV>();
}

void Update()
{
if (fov.targetAquired) {
///// DO Damage after time
Invoke("doDamage", damageDelay);


}
}

protected void doDamage()
{

if (fov.targetAquired)
{
RaycastHit2D hit2D;
hitObject = null;
Vector2 targetDirection = (Player.transform.position - transform.position).normalized;
hit2D = Physics2D.Raycast (transform.position, targetDirection, 100f, fov.targetMask);
Debug.DrawRay(transform.position, targetDirection * 100f, Color.red);
if (hit2D)
{
Debug.Log("Hit2D");
hitObject = hit2D.collider.gameObject;
Health health = hitObject.GetComponent<Health>();
Vector2 damageDirection = (hitObject.transform.position - this.transform.position).normalized;
health.Damage(damage, this.gameObject, 1f, 0f, damageDirection);
}
else
{
hitObject = null;
}
}
}
}

P.S. I’m sure there are probably other things wrong with this code, I just haven’t been able to test them without getting the raycast to hit the player!

Pluck out the variables and do things one line at a time so you can print numerics out of the vectors.

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.” - Star Manta on the Unity3D forums

Always use named arguments with Physics(2D).Raycast() because it contains many poorly-designed overloads:

After you sort out the values and their order, if it still doesn’t work, start here:

You must find a way to get the information you need in order to reason about what the problem is.

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:

Also make sure which transform you’re using: the player, the target, or this script, or what you hit… it will make a huge difference. :slight_smile:

Wow, thank you for the incredibly detailed response. You make a really good point about not making it harder than it needs to be!

There is a lot of really good info here. I will be studying this tonight lol!

thanks again

This was exactly what I needed to hear, thank you. The player gameobject wasn’t initialized… Your methods helped me find that quickly.

AWESOME!

And if you’re worried about more lines of code being slower, surprisingly sometimes it can be faster to do one thing at a time because you may give the compiler a better view into your data flows and coverage and it might just do a better job of optimizing.

Remember the CPU is really only doing one thing at a time, at least related to any given single problem it is processing.

Plus code that has been teased apart into separate tiny steps is always easier to maintain and change.

1 Like