# Angle to Direction

I am making a tennis game.
I am able to shoot the ball at the given target… but the ball is moving in a straight line …
I want the ball to move at certain angles… 30, 45, 60 so that I can make diffrent shots in my game … loop Shot, Power Shot etc etc

“Right now the ball is going in the direction of the target and I’ve also figured out the angles for the height of the shot but the ball doesn’t land exactly on the target.”

CODE UPTILL NOW:

``````Vector3 direction;

direction = (target.transform.localPosition - ball.transform.localPosition).normalized;

direction.y = Mathf.Sin(30 * Mathf.PI / 180);

``````

Doing what you ask for here is a pretty complicated calculation. There are several detailed answers on UA on projectile motion and targeting. Do a bit of searching and they will turn up along with (if I remember correctly) dense functions that implement the functionality. But if you make a couple of simplifications and look at this problem a bit differently, you can solve it in a few lines of code.

For projectile motion, typically the horizontal velocity is split from the vertical velocity. Instead of calculating an angle, I’m suggesting you define your different shots in terms of horizontal velocity. Horizontal velocity will define how long the ball will take to be over the target.

Given a horizontal velocity, you can calculate time it will take for the ball to be over the target. So the question is how much vertical velocity do you give the ball so that it hits at the same time the horizontal velocity places the ball over the target. If you assume/place the target at the same height as the balls initial height, then the velocity needed is easy to calculate:

``````-gravity  * time / 2.0;
``````

So here is a bit of source code to demonstrate. Before integrating the concept into your code, I encourage you to play with it in a clean scene:

• Start a new scene
• Create a plane at (0.0, -0.5, 0.0), and scaled up larger (20,20,20).
• Create a sphere and place it a the origin
• Add a rigidbody to the sphere
• Adjust the camera so that more can be seen: up on the ‘Y’, forward, and increase the angle of view.
• Put a game object somewhere on the plane to act as a target
• Add the following script to the ball
• Drag the target game object onto the ‘target’ variable in the script.
• Run the app and hit [Space] to launch the ball

``````#pragma strict

var target : Transform;
var speed = 5.0;

function Update () {

if (Input.GetKeyDown(KeyCode.Space)) {

var toTarget = target.position - transform.position;  // Ground vector to target
toTarget.y = 0.0;

var shotTime = toTarget.magnitude / speed;  // Time to reach target

var velocity = toTarget.normalized * speed; // Setup horizontal vector

velocity.y = -Physics.gravity.y * shotTime / 2.0;  // Upward velocity

rigidbody.velocity = velocity;
}
}
``````

While the script is running, you can adjust the speed and the target position and hit [Space] again to relaunch the ball.