[英]Collision not working in 2D
我在Unity中制作了2D牆,但是我的角色可以穿過它。 怎么了? 我的角色有Rigibody2D和BoxCollider2D,牆上有盒子對撞機。 角色移動代碼:
Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical"));
moveVec = moveVec * moveForce;
transform.Translate (moveVec);
我的角色有Rigibody2D和BoxCollider
如果使用Rigibody2D
,則還必須使用BoxCollider2D
而不是BoxCollider
。 確保牆上也有BoxCollider2D
。
當transform.Translate
或transform.position
用於移動對象時,不會發生碰撞。 如果您的GameObject附加了Rigidbody2D,則必須使用Rigidbody2D.velocity
, Rigidbody2D.AddForce
( Rigidbody2D.AddXXX
)或Rigidbody2D.MovePosition
進行移動。
最好在FixedUpdate()
函數中執行此特定操作。 另外,我覺得GetAxisRaw
應該用來代替GetAxis
讓玩家將立即停止鍵/手指被釋放。
public float speed = 2f;
Rigidbody2D rg2d;
void Start()
{
rg2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
float v = CrossPlatformInputManager.GetAxisRaw("Vertical");
Vector2 tempVect = new Vector2(h, v);
tempVect = tempVect.normalized * speed * Time.fixedDeltaTime;
rg2d.MovePosition((Vector2)transform.position + tempVect);
}
如果速度太快/太慢,您始終可以降低/提高速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.