在给外围墙与墙添加BoxCollider2D,给角色添加了BoxCollider2D与刚体并按照课程编写了代码,角色依然会穿出围墙。
(使用的Unity版本为2019.2.8f1)
角色的监视面板如下:
围墙的监视面板如下:
相关代码:
//检测
collider.enabled = false; //先把自身collider禁用,避免与自身发生碰撞
RaycastHit2D hit = Physics2D.Linecast(targetPos, targetPos + new Vector2(h, v));
collider.enabled = true;
if(hit.transform == null)
{
targetPos += new Vector2(h, v);
restTimer = 0;
}
else
{
switch(hit.collider.tag)
{
case "OutWall":
break;
case "Wall":
break;
}
}
private Rigidbody2D rigidbody;
private BoxCollider2D collider;
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
}
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
同学你好,把刚体设置成Dynamic模式