using UnityEngine;
public class ElasticMaterial : MonoBehaviour
{
public float BounceForce = 25;//弹力
public float FrictionQuotiety = 0.988f;//摩擦系数
Rigidbody2D m_rigidbody;
void Start()
{
gameObject.AddMissingComponent<Rigidbody2D>();
m_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
m_rigidbody.velocity = m_rigidbody.velocity * FrictionQuotiety;//增加摩擦系数以免无限反弹
if (m_rigidbody.velocity.sqrMagnitude < 0.01f) m_rigidbody.velocity = Vector3.zero;//速度过小则停止
}
void OnCollisionStay2D(Collision2D collision)
{
if (m_rigidbody == default(Rigidbody2D)) return;
for (var i = 0; i < collision.contacts.Length; i++)
{
var contact = collision.contacts[i];
m_rigidbody.AddForce(contact.normal * BounceForce, ForceMode2D.Force);
Debug.DrawRay(contact.point, contact.normal, Color.blue);//绘制法线,用于测试参考
}
}
}