Hi all I'm new to Unity as well as programming in C# (about 3 weeks in). I've been searching for over a week now and trying different things that I can think of to no avail. I'm making a tower defense style game and I'm stuck on getting the projectile for my catapult to work how I intent. The idea is I have a catapult positioned about 20 units up in the Y direction on top of a building and the enemy is moving straight towards the building at ground level (Y=0). The enemy is moving at a constant speed with a simple transform.translate for now. When the enemy hits the collider I have setup that means the enemy is in range and the catapult begins to fire on it. I want the projectile to make a nice arc and hit the enemy every time no matter the speed the enemy is traveling at because different enemies will move at different speeds. The best example I can give is the catapults in Plants Vs. Zombies on the roof level. At first I thought adding a force and letting unity's physics take care of it would make a nice arc for the projectile, but I found this code here on unity answers that deals with velocity and thought it would be what I was looking for... (modified for C# and the way my project is setup)
void Start()
{
rigidbody.velocity = BallisticVel(myTarget);
}
Vector3 BallisticVel(Transform target)
{
dir = target.position - transform.position; // get target direction
h = dir.y; // get height difference
dir.y = 0; // retain only the horizontal direction
dist = dir.magnitude ; // get horizontal distance
dir.y = dist; // set elevation to 45 degrees
dist += h; // correct for different heights
vel = Mathf.Sqrt(dist * Physics.gravity.magnitude);
return vel * dir.normalized; // returns Vector3 velocity
}
So what happens is the catapult will instantiate the projectile at a location of an empty game object when the enemy collides with the catapult trigger. I attached this code to my projectile and it has no errors and is super close, however given that my catapult is a higher elevation then the enemy and the enemy is moving constantly towards the building the projectile will only hit the enemy if the enemy is moving very slow (.5). Anything with a speed of 1 or higher the projectile will overshoot the enemy and land where the enemy was at the time the projectile was created and not where its going to be. I figure somehow I have to incorporate the speed the enemy is moving into my code, and I passed the speed of the enemy to the projectile but I'm not sure how to incorporate that or if that is even the best way to go about this. Any options would be greatly appreciated. Sorry the post is long I wanted to make what I was trying to accomplish as clear as possible.
↧