unity3D 吸铁石效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Magnetic : MonoBehaviour
{
public LayerMask m_MagneticLayers;//作用的层
public Vector3 m_Position;//磁铁在物体的相对位置
public float m_Radius; //磁铁作用的范围
public float m_Force;//定义物体的力
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
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);
}
Vector3 player = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if (player != Vector3.zero)
{
transform.position += -player * 5 * Time.deltaTime;
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position + m_Position, m_Radius);//绘制一个球(有利于我们的观察)
}
}
注意点
物体需要加上刚体