I made a rigidbody character with the goal to have it “bounce” off of certain objects (basically deflect based on the angle of incidence and gravity). Someone on the forums gave me a small code to apply to the bounce object (a plane), which is as follows:
var player : Transform;
var bounceForce : float = 10;
function OnCollisionEnter(other : Collision)
{
player.rigidbody.AddRelativeForce(Vector3.up * 10, ForceMode.VelocityChange);
}
I noticed my character would be reflected only vertically, no matter what angle the object is. From some testing, I think the issue is that my character has rigidbody.FreezeRotation turned on, for obvious reasons.
Could anyone explain a way around this issue, either fixing the character end (rigidbody.FreezeRotation) or the bounce script? I have thought about using vector-based physics formulas to calculate the angle of reflection, velocity, etc. but at the moment I am not familiar enough to implement such a bounce script.
Thanks
I tried a rigidbody with freezed rotation and collider material set to Bouncy. When falling on some rigidbody, it didn’t bounce at all. If falling on a collider without rigidbody, however, it bounced so endlessly that I had to define a damping factor in its script:
var damping:float = 0.7;
function OnCollisionEnter(){
rigidbody.velocity.y *= damping;
}
It worked fine - at least for the bouncing effect. Hope it can solve your problem
EDITED: Applied damping only to the Y velocity component. This allows easy control of how much the player bounce in different objects by altering the damping factor.
NOTE: damping is actually an energy conservation factor - it ranges from 0 (total damping) to 1 (no damping at all).
Edit 2: Solved with the kind help of [yakoma44][1]. Instead of moving the character using velocity and AddForce, I used MovePosition. So far, I haven’t found any problems and the character doesn’t seem to be doing any funky physics behaviors (fingers crossed).
Here are the code changes sampled from my character script:
Original
var velocity = rigidbody.velocity;
var velocityChange = (targetVelocity - velocity);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
Fixed:
rigidbody.MovePosition(rigidbody.position + targetVelocity * Time.deltaTime);
The actual bounce force is applied on the bouncing collider:
var bounceForce : float = 10;
function OnCollisionEnter(other : Collision)
{
other.rigidbody.velocity = transform.up * bounceForce;
}
Nota bene: AddForce or AddRelativeForce also work in the OnCollisionEnter, though the above is the shortest to write out.
[1]: http://www.youtube.com/user/yakoma44[yakoma44][1]