Hi. I am currently trying to send a physics ball towards a specific target, simple and there are a lot of answers already here, so I found this script:
void SendToTarget(Vector3 target) {
Vector3 p = target;
float gravity = Physics.gravity.magnitude;
// Selected angle in radians
float initialAngle = 50;
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(_rigidbody.transform.position.x, 0, _rigidbody.transform.position.z);
// Planar distance between objects
float distance = Vector3.Distance(planarTarget, planarPostion);
// Distance along the y axis between objects
float yOffset = _rigidbody.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) * (p.x > _rigidbody.transform.position.x ? 1 : -1);
Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
// Fire!
_rigidbody.velocity = finalVelocity;
}
my ball never reaches the target because of 2 things:
a) its got a drag value of 1
b) its got a custom gravity script on it that will push the ball down all the time and even more when its falling (velocity.y < 0). here is the snippet for that:
sphere.velocity += Vector3.up * Physics.gravity.y * (gravity - 2) * Time.deltaTime;
if (sphere.velocity.y < 0) {
sphere.velocity += Vector3.up * Physics.gravity.y * (gravity - 1) * Time.deltaTime;
}
so my question now is: how can i send the ball with a drag of 1 and this custom gravity script towards a specific target using physics? thanks!