简体   繁体   中英

Unity 2D raycasting not going where expected

I have a player and an aim direction (represented as a normalized Vector2 where eg (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):

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM