Search Unity

Trying to make a backstab detection script, need help figuring it out.

Discussion in 'Scripting' started by BarbadosSlim, Nov 19, 2014.

  1. BarbadosSlim

    BarbadosSlim

    Joined:
    May 14, 2014
    Posts:
    5
    Hey there, I'm making a game where a backstab is crucial for stealthy gameplay.

    I'm having trouble understanding what exactly what I need to do script wise, any help is appreciated.

    Basically: if you are behind the enemy, within the 180 degrees behind the enemy, and 6 feet away, it will also play a separate animation. The damage is dealt if the knife collider hits the enemy hit box.

    It's just not clicking for me. How would I get the angle from both objects so I know that it's a backstab from at least 180-360, and closer than 6 feet, not a normal stab, and how would I translate that to doing more damage?

    I apologize if this is in the wrong forum, wasn't too sure where to post it. I posted it here because I wanted more substance to the replies :)
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    This is exactly the right forum!

    I think the easiest way to figure this is to get the position of the attacker in the defender's local coordinate system. Transform.InverseTransformPoint should do it. Then just look at the Z value; if Z < 0, the attacker is somewhere behind the defender, and if Z > 0, the attacker is somewhere ahead.
     
    BarbadosSlim likes this.
  3. BarbadosSlim

    BarbadosSlim

    Joined:
    May 14, 2014
    Posts:
    5
    Excellent, that's very helpful, thanks :)
     
  4. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    That's funny — I got about halfway typing out essentially that same solution (computing the angle between the forward vector of one and the vector from one to the other), but then realized that InverseTransformPoint was a simpler and probably easier-to-understand solution.

    The dot product is probably ever-so-slightly faster, though!
     
  6. BarbadosSlim

    BarbadosSlim

    Joined:
    May 14, 2014
    Posts:
    5
    Thanks none the less, I'm likely to use inverseTransformPoint with a distance detector to simply things. I doubt inversetransform is much slower.
     
  7. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    You'd be surprised. Some of those Inverse/Transform functions can be pricey.
     
  8. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Could go the route of a trigger on the back of the enemies as well... if the player is inside that trigger and attacks play your special animation
     
    JoeStrout likes this.