2017-04-18 74 views
1

我在Unity中制作了2D墙,但我的角色可以穿过它。怎么了?我的角色有Rigibody2D和BoxCollider2D,墙上有箱子对撞机。 代码字符的运动:碰撞在2D中不起作用

Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical")); 
    moveVec = moveVec * moveForce; 
    transform.Translate (moveVec); 
+0

你的角色是否有BoxCollider2D(注意最后的2D)。你的墙也一样。 –

+0

是的,它有BoxCollider2D – Sleeper

+0

尝试使用rigidbody.MovePosition而不是transform.Translate。还要检查碰撞蒙版和物体图层 –

回答

2

我的性格有Rigibody2D和BoxCollider

如果使用Rigibody2D,还必须使用BoxCollider2DBoxCollider。确保墙壁也有BoxCollider2D

transform.Translatetransform.position用于移动对象时没有发生碰撞。如果您的GameObject附带有Rigidbody2D ,则必须将其移动到Rigidbody2D.velocity,Rigidbody2D.AddForceRigidbody2D.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); 
} 

如果速度太快/太慢,您可以随时减小/增加速度。

+1

您应该使用Time.fixedDeltaTime; –

+0

@JuanBayonaBeriso没错。感谢您的高举。 – Programmer

+0

谢谢。 update和fixedupdate有什么区别? – Sleeper