Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - Unity2D: Parabolic projectile not reaching the player

I have looked into this video and tried this post to create a projectile that follows a parabola to hit the player/ enemy. Either the player and the enemy might not be at the same level. But whenever I run the game, the projectile "bomb" is not reaching the player when thrown.

Here is the script I am using to launch the projectile and is attached to the projectile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GoblinBombScript : MonoBehaviour
{       
    // This script is attached to the "bomb" projectile that is spawned in the playspace and will launch the bomb as soon as it is spawned
    void Start()
    {        
        Vector2 player= FindObjectOfType<Player>().transform.position;
        float T = 1f;
        // transform.position is the position of the projectile in the game
        float xdistance = player.x - transform.position.x;
        float ydistance = player.y - transform.position.y;

        float throwAngle = Mathf.Atan((ydistance + 4.905f * (T * T)) / xdistance);
        float totalVelo = xdistance / (Mathf.Cos(throwAngle) * T);

        float xVelo = totalVelo * Mathf.Cos(throwAngle);
        float yVelo = totalVelo * Mathf.Sin(throwAngle); 
        // The rigidbody is that of the projectile "bomb" being launched:
        GetComponent<Rigidbody2D>().velocity = new Vector2(xVelo, xVelo);
        // GetComponent<Rigidbody2D>().AddForce(new Vector2(xVelo, yVelo), ForceMode2D.Impulse); 
    }
}

The GoblinBomb is attached to the Goblin and and the goblin throws this bomb(Instantiated in scene) when the player is in attack range.

Here is what the result looks like:

enter image description here

As you can see, the bomb projectile is dropping only after travelling a small lobbed distance.

I have attached a rigidbody2d(dynamic, mass = 1.0, gravity scale = 1) and a circle collider to the bomb projectile.

What am I missing so that the projectile hits the player along the parabolic path?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...