我試圖有一個像物理學一樣的黑洞,它會吸引任何靠近它的物體,然后把它放入黑洞軌道,像一個漩渦一樣讓它到達中心并消失。
我最終得到了這樣的東西,但不起作用
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:通過添加一些阻力來解決它,如果有人試圖實作相同的目標,請隨意使用此腳本。
uj5u.com熱心網友回復:
你需要給物體一些啟動力,因為這會產生水平速度并形成軌道。為了使它向內盤旋,啟動力非常小,它會以一定的水平速度落向黑洞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483833.html
上一篇:蹲下時如何改變速度?