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)
public void Fire(Vector3 target)
{
var rigid = GetComponent<Rigidbody>();
Vector3 p = target;
float gravity = Physics.gravity.magnitude;
// Selected angle in radians
float angle = initialAngle * Mathf.Deg2Rad;
// Positions of this object and the target on the same plane
Vector3 planarTarget = new Vector3(p.x, 0, p.z);
Vector3 planarPostion = new Vector3(transform.position.x, 0, transform.position.z);
// Planar distance between objects
float distance = Vector3.Distance(planarTarget, planarPostion);
// Distance along the y axis between objects
float yOffset = transform.position.y - p.y;
float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
Vector3 velocity = new Vector3(0, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));
// Rotate our velocity to match the direction between the two objects
float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPostion);
Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
// Fire!
rigid.velocity = finalVelocity;
// Alternative way:
// rigid.AddForce(finalVelocity * rigid.mass, ForceMode.Impulse);
}
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?)
How would I go in fixing this?