Answers for "Angle to Direction"
http://answers.unity.com/questions/556298/angle-to-direction.html
The latest answers for the question "Angle to Direction"Answer by robertbu
http://answers.unity.com/answers/558252/view.html
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)) {
transform.position = Vector3.zero; // Start with the ball at the origin
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.Fri, 18 Oct 2013 08:19:31 GMTrobertbu