I am just learning the basics of physics simulation with rigidbodies. I am trying to simulate some basic real world functions like kicking a ball.
Let's say I have a simple capsule mesh/collider as my player and a sphere as a ball. I want when the player comes close enough to the sphere for them to be able to "kick" the ball, exerting a velocity on the ball along the vector from the player's front face towards the ball.
I am new to all the angle systems of rigidbodies so I'm having a bit of difficulty.
The best I could come up with was to add this code to the control of the player capsule:
if (Input.GetKeyDown(KeyCode.B)) {
Collider[] hitColliders = Physics.OverlapSphere(playerGO.transform.position, 1f);
foreach (var hitCollider in hitColliders) {
if (hitCollider.gameObject.GetComponent<Rigidbody>()) {
//if (objectWithinFrontRangeOfPlayer) { // use playerGO.transform.forward
Vector3 positionDiff = hitCollider.transform.position - playerGO.transform.position;
Quaternion angleOfImpact = Quaternion.LookRotation(positionDiff);
hitCollider.GetComponent<Rigidbody>().velocity = new Vector3(angleOfImpact.x, angleOfImpact.y, angleOfImpact.z) * 30f;
//}
}
}
}
So the steps I see are:
- Upon player pressing "kick" button (B), check for any colliders in the area, then check for which have rigidbodies.
- If rigidbody is found within kicking range, I should ideally then check if it is within a certain angle tolerance like +/- 60 degrees of the
playerGO.transform.forward
direction (one can usually only kick effectively things in front of how you are facing). I am not sure how to do this. - I then need to calculate the angle/vector at which the velocity should be applied to the sphere. I tried using
Quaternion.LookRotation(hitCollider.transform.position - playerGO.transform.position);
but then I don't know what to do with the Quaternion. If I had it as a normalized unit vector I could do what's written above and multiply the intended velocity from the kick to each axis. But as a Quaternion, while what I wrote above certainly "kicks" the back, the vector is not correct.
Any tips on how to fix this code and make it work roughly correctly?
Thanks a bunch.