Saturday, July 9, 2022
HomeGame Developmentunity - Projectile arc velocity modifications relying on track x-axis place

unity – Projectile arc velocity modifications relying on track x-axis place


I’m making an attempt to create an enemy for a 2D platformer that launches a projectile in an arc on the participant place (assume throwing a grenade, launching an arrow model parabola).

All the things works as anticipated if the participant and enemy are roughly on the identical x-axis (or comparable, inside a number of items), however the additional the distinction on the x axis, the sooner the projectile strikes. This additionally occurs the nearer the goal will get (however provided that there’s a distinction within the x-axis).

I’ve included the code within the script that is hooked up to the projectile that strikes it as every little thing else (the collision, the precise launching of the projectile, and so on) works because it ought to.


GameObject goal; // The participant is the goal
float velX = 10; // Preliminary x velocity is understood
float velY; 

non-public void Begin()
{
    // Initialize the goal object
    goal = GameObject.FindGameObjectWithTag("Participant");
    // Reverse the x velocity relying on participant place
    velX = goal.remodel.place.x > remodel.place.x ? velX : -velX;
    // Calculate the time to affect
    float timeToImpact = (goal.remodel.place.x - remodel.place.x) / velX;
    // Calculate the preliminary y velocity
    // Add 2 to the goal place to goal on the high of the participant - it is 2 items tall
    velY = (goal.remodel.place.y + 2f - remodel.place.y + 0.5f * -Physics2D.gravity.y * (timeToImpact * timeToImpact)) / timeToImpact;
}

non-public void Replace()
{
    // Set the rigidbody velocity
    Vector2 vel = new Vector2(velX, velY);
    GetComponent<Rigidbody2D>().velocity = vel;
    // Gravity alters the y velocity over time
    velY += Physics2D.gravity.y * Time.deltaTime;
} 

I am certain that there is just a few worth that I have to divide or multiply one of many velocities or time by however I am unable to fairly wrap my head round it.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments