- Home /
Question by
EpicCrownKing · Sep 13, 2019 at 03:16 AM ·
2drigidbody2dvelocity
Getting the future position of a rigidbody2D with velocity
Hello, this is a question that's stumped me for quite a bit. I'm making a tower defense game, and I need the tower to shoot at the future position of an enemy. I tried getting the velocity but discovered that transform.translate and rb.addforce both don't give it a velocity. Rigidbody.MovePosition moves too fast, so I was wondering if there was any way to get its future position in x seconds and return a Vector2 to plug into my trigonomic formula. If there's somewhere else I should look for this, let me know.
Code: //Variables float alpha; float d1; float d2; GameObject enemy = rangeSight.GetComponent().target;
//Getting values
d1 = Vector2.Distance(transform.position, enemy.transform.position); //Getting the distance from the tower to the enemy, the first leg of the triangle
d2 = enemy.GetComponent<EnemyScript>().speed * shootSpeed * Time.deltaTime; //Getting the second leg of the triangle
Vector2 d2Vector //THIS IS WHAT I NEED TO FIND
alpha = Vector2.Angle(d2Vector, transform.position); //Getting the third angle of the triangle, <EFT
Debug.Log(alpha);
//Final formula
double finalAngle = Math.Asin((d2 * Math.Sin(alpha)) / d1); //PLugging in the variables and doing the trigonometry
//Shooting
float floatFinalAngle = (float)finalAngle; //Converting double to float
transform.eulerAngles = new Vector3(transform.rotation.x, transform.rotation.y, transform.rotation.z + floatFinalAngle); //Changing rotation
Instantiate(projectile, transform.position, transform.rotation); //Firing
If you have any questions, I'll answer them as soon as possible. Thanks, EpicCrownKing
Comment