|
在真实的宇宙中,小星球总是被大星球吸引过去,其实就是一种力的作用,在unity3d中如何来模拟这种效果呢?
1、在场景中建两个球体,当然,球的大小无所谓,为了区别,我们将之称为大球,小球。
2、给小球加上刚体组件,在属性面板中去掉重力选项。新建一“min”层,将小球添加到此层中。
3、新建c++代码文件,将到下代码拷贝其中,并将其附着到大球上,属性面板中即显示此代码组件,设置其引力层为“min”,设置其半径及引力大小。
4、进行游戏模式,移动大球至小球附近,小球即被慢慢吸走。引力效果实现。
[code=csharp]using UnityEngine;
using System.Collections;
public class Magnetic : MonoBehaviour
{
public LayerMask m_MagneticLayers;
public Vector3 m_Position;
public float m_Radius;
public float m_Force;
void FixedUpdate ()
{
Collider[] colliders;
Rigidbody rigidbody;
colliders = Physics.OverlapSphere (transform.position + m_Position, m_Radius, m_MagneticLayers);
foreach (Collider collider in colliders)
{
rigidbody = (Rigidbody) collider.gameObject.GetComponent (typeof (Rigidbody));
if (rigidbody == null)
{
continue;
}
rigidbody.AddExplosionForce (m_Force * -1, transform.position + m_Position, m_Radius);
}
}
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere (transform.position + m_Position, m_Radius);
}
}[/code] |
|