# Question Making an object land directly on a position using Velocity.

Discussion in 'Physics' started by SuperiorJacob, May 10, 2020.

1. ### SuperiorJacob

Joined:
Apr 18, 2018
Posts:
2
So I am trying to get my monkey to throw the object to the location.
This works perfectly, but only for positions on the RIGHT side of the monkey.

The code I am currently using (I found it somewhere and wanted to test it)
Code (CSharp):
1.     public void Fire(Vector3 target)
2.     {
3.         var rigid = GetComponent<Rigidbody>();
4.
5.         Vector3 p = target;
6.
7.         float gravity = Physics.gravity.magnitude;
8.         // Selected angle in radians
9.         float angle = initialAngle * Mathf.Deg2Rad;
10.
11.         // Positions of this object and the target on the same plane
12.         Vector3 planarTarget = new Vector3(p.x, 0, p.z);
13.         Vector3 planarPostion = new Vector3(transform.position.x, 0, transform.position.z);
14.
15.         // Planar distance between objects
16.         float distance = Vector3.Distance(planarTarget, planarPostion);
17.         // Distance along the y axis between objects
18.         float yOffset = transform.position.y - p.y;
19.
20.         float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
21.
22.         Vector3 velocity = new Vector3(0, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));
23.
24.         // Rotate our velocity to match the direction between the two objects
25.         float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPostion);
26.         Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
27.
28.         // Fire!
29.         rigid.velocity = finalVelocity;
30.
31.         // Alternative way:
32.         // rigid.AddForce(finalVelocity * rigid.mass, ForceMode.Impulse);
33.     }
I don't know if there are better ways of doing this, probably is, but this way worked the best for me, just the issue only works on the right direction.

Gif of Issue (at the start, it shows how I can throw right perfectly, but when I throw left it either doesn't work or throws it to the right spot, but on the wrong side?)
https://i.gyazo.com/4aa00e4cb4d4c2361edd4ff862c65652.mp4

How would I go in fixing this?

Joined:
Apr 18, 2018
Posts:
2
Bump.

Joined:
May 20, 2009
Posts:
1,773