Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Raycast shoots wrong way.

Discussion in 'Scripting' started by kevtv278, Sep 25, 2021.

  1. kevtv278

    kevtv278

    Joined:
    Aug 14, 2020
    Posts:
    13
    Hey i have a bot thats shoot when he sees the player but why does he shot like that:

    Raycast.JPG


    Code (CSharp):
    1. if (Physics.Raycast(gunPosition.transform.position, player.transform.position, out Hit))
    2.                 {
    3.                     Debug.DrawRay(gunPosition.transform.position, player.position, Color.green, 5);
    4.  
    5.                     if (Hit.collider.CompareTag("Player"))
    6.                     {
    7.                         Debug.Log("Hit");
    8.                     }
    9.  
    10.                     Debug.Log("Nothing");
    11.                 }
     
  2. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    The only thing that comes to mind is maybe you have accidentally got a different gameobject with the player tag and it's automatically raycasting to that rather than your player gameobject. Did you by any chance do some duplicating with these capsules? That copies everything including your what tag they're set to, that would be the first thing I'd check. You should also see that the debug.drawray isn't leading you astray and pay more attention to the actual result of your code through the debug.log, his "Hit" even initiating when the game is started?
     
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    This looks like the source of your problem:
    Code (CSharp):
    1. Physics.Raycast(gunPosition.transform.position, player.transform.position, out Hit)
    IIRC most if not all raycast method overloads want an origin position and a direction.

    Here it seems like you gave two positions, as if those were end points of a line. You'll most likely want a direction from bot to player (player.position - bot.position).

    Then optionally normalize that and use it as your shooting direction, and start/origin point of ray is the bot position.
     
    Kredjjang and Lethn like this.
  4. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Now you've pointed that out @eses yes it seems like this is more just a general maths problem than something a raycast should be used for unless @kevtv278 is trying to do something specific but we'll let them elaborate on that.
     
  5. kevtv278

    kevtv278

    Joined:
    Aug 14, 2020
    Posts:
    13
    thx @eses i changed it to if (Physics.Raycast(gunPosition.position, transform.TransformDirection(Vector3.forward), out Hit)) and it worked
     
    Lethn likes this.