我在尝试像黑洞那样的物理,吸引任何靠近它的物体,然后把它放入黑洞轨道,像漩涡一样让它进入黑洞中心,然后消失。
我结束了这样的东西,但不工作
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[DisallowMultipleComponent]
[ExecuteInEditMode]
[RequireComponent(typeof(CircleCollider2D))]
[RequireComponent(typeof(SpriteRenderer))]
public class BlackHole : MonoBehaviour
{
/// <summary> </summary>
public const float GRAVITY_PULL = 7000.0f;
/// <summary> </summary>
private const float SWIRLSTRENGTH = 5f;
// ------------------------------------------------
/// <summary> </summary>
private float _gravityRadius = 7.0f;
/// <summary> </summary>
private List<Rigidbody2D> _rigidBodies = new List<Rigidbody2D>();
// ------------------------------------------------
#if UNITY_EDITOR
void Update()
{
if( Application.isPlaying == false )
{
_gravityRadius =
GetComponent<CircleCollider2D>().radius;
}
}
#endif
private void LateUpdate()
{
UpdateBlackHole();
}
/// <summary>
/// Attract objects towards an area when they come within the bounds of a collider.
/// This function is on the physics timer so it won't necessarily run every frame.
/// </summary>
/// <param name="in_other">Any object within reach of gravity's collider</param>
void OnTriggerEnter2D(
Collider2D in_other
)
{
if ( in_other.attachedRigidbody != null
&& _rigidBodies != null )
{
//to get them nice and swirly, use the perpendicular to the direction to the vortex
Vector3 direction =
transform.position - in_other.attachedRigidbody.transform.position;
var tangent =
Vector3.Cross(direction, Vector3.forward).normalized * SWIRLSTRENGTH;
in_other.attachedRigidbody.velocity =
tangent;
_rigidBodies.Add( in_other.attachedRigidbody );
}
}
private void UpdateBlackHole()
{
if( _rigidBodies != null )
{
for (int i = 0; i < _rigidBodies.Count; i++)
{
if( _rigidBodies[i] != null )
{
CalculateMovement( _rigidBodies[i] );
}
}
}
}
private void CalculateMovement(
Rigidbody2D in_rb
)
{
float distance =
Vector3.Distance(
transform.position,
in_rb.transform.position
);
float gravityIntensity =
distance
/ _gravityRadius;
in_rb.AddForce(
(transform.position - in_rb.transform.position)
* gravityIntensity
* in_rb.mass
* GRAVITY_PULL
* Time.deltaTime);
in_rb.drag += 0.0001f;
Debug.DrawRay(
in_rb.transform.position,
transform.position - in_rb.transform.position
);
if( distance <= 0.1f )
{
_rigidBodies.Remove( in_rb );
Destroy( in_rb.gameObject );
}
}
}
这将使物体从黑洞中心上下移动并增加它的速度这是我想要的但不是上下移动,我想让它绕着它运行然后在一段时间内靠近黑洞中心。
帮忙吗?
更新1:通过在开始时添加一个小的力,我能够使它围绕黑洞旋转,但它不会落到黑洞的中心
更新2:通过添加一些拖动来解决它,如果有人试图实现同样的事情,请随意使用这个脚本。
你需要给物体一些起始力,因为这会产生水平速度并形成轨道。为了使它向内螺旋,使起始力非常小,它将以一定的水平速度落向黑洞。