Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to fire in front of enemy

Discussion in 'Scripting' started by Patrick2607, Nov 28, 2016.

  1. Patrick2607

    Patrick2607

    Joined:
    Nov 28, 2016
    Posts:
    2
    I'd like to fire in front of my enemy, but I can't seem to figure out how I can manage to do that.

    Here is my method:

    Code (csharp):
    1. private void FireInFrontOf(Transform target)
    2. {
    3.     // Set height to fire from
    4.     Vector3 position = HeadTransform.transform.position + new Vector3(0, FireHeight, 0);
    5.    
    6.     // Instantiate Projectile
    7.     GameObject projectileGO = (GameObject)Instantiate(ProjectilePrefab, position, HeadTransform.transform.rotation);
    8.  
    9.     // Retrieve Projectile
    10.     Projectile p = GetProjectile(projectileGO);
    11.     if (p == null) return;
    12.  
    13.     // Set Projectile attributes
    14.     p.Target = target;
    15.     p.Damage = Damage;
    16.     p.Radius = Radius;
    17. }
    I already found this:
    Code (csharp):
    1. target.forward*Time.deltaTime*DistanceUpFront;
    But if I apply that to the targets position parameter before setting the projectile properties, the target moves over my screen.

    Can anyone help me with this problem? Thank you!

    In the attached files is a quick sketch for clarification of what I want to achieve.
     

    Attached Files:

  2. MV10

    MV10

    Joined:
    Nov 6, 2015
    Posts:
    1,889
    In the code you posted, you wouldn't apply that position to the target, the target will continue moving normally. That calculation has some issues but it looks like somebody is trying to use it to predict where the target would be.

    You need to know the gun position, the target position and heading, the projectile speed, and the target speed. You're looking for the "intercept" -- the point at which your projectile's line intersects the target's line. This is called "leading" the target and the Interwebs are full of solutions. Here's one:

    http://wiki.unity3d.com/index.php?title=Calculating_Lead_For_Projectiles