0
votes

I have a player and an aim direction (represented as a normalized Vector2 where e.g. (1.0, 0) means pointing straight right). I want to cast a ray from the player in the aim direction until it hits part of my wall layer. I'm not sure why, but right now that raycast is not being aimed in the right direction at all, as drawn by Debug.DrawRay. Here's my relevant code:

 private void Update() {
     SetAimDirection();
     DoRaycast();
 }
 private void DoRaycast() {
     if (Input.GetButtonDown("Cast")) {
         RaycastHit2D hit = Physics2D.Raycast(transform.position, aimDirection, groundLayer);
         if (hit.collider != null) {
             Debug.Log(hit.collider.tag + " " + hit.point + " aim: " + aimDirection);
             Debug.DrawRay(transform.position, hit.point);
         }
     }
 }

private void SetAimDirection() {
    Vector2 aim = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

    if (aim.magnitude == 0) {
        aim.x = facingRight ? 1 : -1;
    }

    aimDirection = aim.normalized;

    // Draw the reticle a constant radius from the player in aimDirection.
    Vector2 reticlePosition = new Vector2(body.position.x + (aimDirection.x * reticleRadius), body.position.y + (aimDirection.y * reticleRadius));
    crosshair.transform.position = new Vector3(reticlePosition.x, reticlePosition.y, 0);
  }

Here's a gif to illustrate the problem better (the white ray is meant to be passing through the red crosshair from the player's center, but isn't):

enter image description here

1
Without knowing how you calculate aimDirection is impossible to know what's happening. - Gusman
@Gusman added that part of the code. - IronWaffleMan
You are raycasting before computing the aim direction... - Gusman
Oops, fixed that. It was a bad copy/paste from my code, I was doing the aiming first. - IronWaffleMan
Is body.position the same as transform.position? - Gusman

1 Answers

0
votes

So it was my own debugging function's fault; I was using Debug.DrawRay instead of Debug.DrawLine. The difference being, DrawRay takes an origin and a direction, whereas I was giving it an origin and destination, completely messing up the result. Using DrawLine fixed my issue.