我正在嘗試制作輕飄飄的鳥,當鳥撞到“地板”時,我正在嘗試制作它,變數發生變化,然后運動腳本無法運行。我有點難以解釋,但這是我的代碼:
void Update()
{
void OnCollisionEnter2D(Collider2D col)
{
if (col.gameObject.tag == "floor") // || col.gameObject.tag == "Pipe")
{
active = 0;
}
}
if (active == 1)
if (Input.GetKeyDown("space"))
{
GetComponent<Rigidbody2D>().velocity = new Vector3(0, 10, 0);
}
}
那是我的代碼^請幫助:)
uj5u.com熱心網友回復:
void Update()
{
if (active == 1)
{
if (Input.GetKeyDown("space"))
{
GetComponent<Rigidbody2D>().velocity = new Vector3(0, 10, 0);
}
}
}
void OnCollisionEnter2D(Collider2D col)
{
if (col.gameObject.tag == "floor") // || col.gameObject.tag == "Pipe")
{
active = 0;
}
}
這段代碼對我來說很好,確保將 Rigidbody2d 添加到播放器 將盒子對撞機和標簽添加到地板
uj5u.com熱心網友回復:
首先,您將OnCollisionEnter2D嵌套在下面Update作為本地函式。Unity 不會以這種方式查找和呼叫它,它需要在類級別。
然后你設定
active = 0;
但檢查
active == 1
這似乎很奇怪。我希望您檢查相同的值。
一般來說,寧愿使用一個bool標志:
private bool active;
// reference via the Inspector if possible
[SerializeField] private Rigidbody2D _rigidbody;
private void Awake()
{
// as fallback get it ONCE on runtime
if(!_rigidbody) _rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (active)
{
if (Input.GetKeyDown("space"))
{
// only change the Y velocity, keep the rest
// that's needed e.g. if you are moving sideways currently
_rigidbody.velocity = new Vector3(_rigidbody.velocity.x, 10);
// immediately disable jumping
active = false;
}
}
}
private void OnCollisionEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("floor") || col.gameObject.CompareTag("Pipe"))
{
active = true;
}
}
// also disable jumping when exiting just in case
void OnCollisionExit2D(Collider2D col)
{
if (col.gameObject.CompareTag("floor") || col.gameObject.CompareTag("Pipe"))
{
active = false;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432336.html
