Want to create an arc for enemy projectile. What is wrong with my code

[SerializeField] Transform player;
    float alpha;
    float lenght;
    [SerializeField] float timeToHit = 1f;
    float acc;

    [SerializeField] GameObject bulletPrefab;


    private void Start() {
        acc = Physics2D.gravity.y;
        Debug.Log(acc);
        Shoot();

    }

    void Shoot(){
        GameObject bullet = Instantiate(bulletPrefab) as GameObject;
        bullet.transform.position = transform.position;
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();

        
        Vector2 diff = player.position - transform.position;
        alpha = Vector2.Angle(diff,new Vector2(1,0));  
        
        lenght = Mathf.Abs(Vector3.Magnitude(transform.position - player.position));
       
        float theta = (90 - alpha)/2; //Random relation that i think will feel fine


        alpha = alpha * Mathf.Deg2Rad;
        theta = theta * Mathf.Deg2Rad;
        float v_temp = (lenght - 0.5f * acc * Mathf.Sin(alpha) * Mathf.Pow(timeToHit,2))/timeToHit;
        
        float v_real = v_temp/Mathf.Cos(theta);
        
        
        
        rb.velocity = new Vector2(v_real*Mathf.Cos(theta + alpha), v_real*Mathf.Sin(theta+alpha));

    }

Hi,

What do you mean by wrong? Doesn’t your code work at all? Does it work but you are getting the wrong result? If so, what is the result?

It goes way too far away. But yes it arcs. And the angle is correct too. Like if the enemy and the player are on the same axis then the enemy throws the bomb at 45 degree angle but the velocity is just too much

And what is the expected result? From what I understood from your latest answer, 45 degree is a hard-coded angle. You have to define the turning point of your arc, which is (depending on your idea) at half the distance between the shooter and the target if the target is at the same y-position as your shooter. For the distance, you will have to take the gravity and the velocity of the bullet into consideration to calculate the “perfect” arc. Of course, the gravity and velocity don’t have to exist but you will have to simulate them anyway to get the desired result with 45 degree.

This tutorial might be interesting:

45 isnt hardcoded. Its a relative to the angle that the player position - enemy position makes with the x axis. So if they are on the same axis, the angle is 45. If they are right above one other the angle is 90-90/2 ie 0 and so on. The only thing that is hard-coded is the time in which I want my projectile to hit the player ie timeToHit variable in my code
I will take a look at the tutorial. thanks!

I got it actually thanks! My physics was just all wrong. I could specify only one thing out of the angle and time when i was doing both so it wasnt working

Good job! :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms