Hit moving target ?

Hi, my gun rotate to face enemy direction but because he "target" is moving, bullet can't hit him till he stop ? How to get solution for this fit my script ? I read some topics discuss this, but I couldn't translate their point in my script file. 

Script file

I need someone rescript my file.

  • Jonathan Gonzalez(jgonzalez) replied

    Well there are a few ways to approach it. Do you need to shoot and hit the target ahead of time like a sniper trying to time his shot? Or are you trying to create a homing bullet that when fired follows the target? 

    The first is more difficult and requires "predictive tracking". Meaning you need to store a value to where you expect the target to be at a specific time. Here are a few links that can help out with that: https://answers.unity.com/questions/898742/predict-next-rigidbody-position-based-on-velocity.html

    https://answers.unity.com/questions/50290/project-the-future-position-of-a-moving-rigidbody.html

    For a homing style bullet, I do have a fairly old course that covers the topic using a homing missile effect: 

    https://cgcookie.com/course/creating-a-locking-weapon-system

  • AeleaS Omer(aeleas) replied

    jgonzalez, Yes . I want to do the first thing.  I need to make a lot of maths to get it done. I you links are good and it shows where i should start but still I can't get it done. I have to replace target.position with velocity . Calculate the currently angle and new angle. then what ?

  • Jonathan Gonzalez(jgonzalez) replied

    aaeleas I haven't tested it, but velocity is a Vector3. If you look at the answer for the first link you'll see something like this:

    // to leave y-speed as it was:
     rigidbody2D.velocity.y = MOVE_SPEED;
     // or to make object move only to the right:
     rigidbody2D.velocity = Vector2.right * MOVE_SPEED;
     Vector2 predictedPoint = new Vector2(transform.position.x, transfomr.position.y) + rigidbody2D.velocity * Time.deltaTime;
  • AeleaS Omer(aeleas) replied

    jgonzalez, you mean something like this "rigidbody2D.velocity.y = MOVE_SPEED;". I will try do something similar to what in first. Thank you Jonathan.

  • Jonathan Gonzalez(jgonzalez) replied

    aaeleas Yes, I hit submit before the code snippet was added in. Basically up above he's using predictedPoint by taking the current position of the object and adding in the velocity. I'd have to test it out myself to really see how it works, but that's the gist of it.