Unity创建一个简易的弹簧(弹动)效果
参考文章:http://www.cnblogs.com/SkyD/archive/2008/09/05/1284778.html
主要依据胡克公式F=-k·x。这里k是倔度系数,可以理解为k值越大弹性越强。
实际运用不能照搬胡克公式,可以作为速率使用,具体看参考文章。
k值较低的效果:
k值较高的效果:
脚本:
using UnityEngine; using System.Collections; public class Spring : MonoBehaviour { public float k = 50f; public float fric = 24f; public float force = 1f; Vector3 mVelocity; Vector3 mOriginPosition; void Awake() { mOriginPosition = transform.position; } void Update() { var f = (mOriginPosition - transform.position) * k; mVelocity += f * Time.deltaTime; mVelocity = Vector3.Lerp(mVelocity, Vector3.zero, fric * Time.deltaTime); transform.position += mVelocity; } void OnTriggerEnter(Collider other) { mVelocity = (other.transform.position - transform.position).normalized * force; } }