为何选择Collider2D.Raycast& Collider.Raycast是如此不同?

时间:2018-04-23 04:19:32

标签: unity3d raycasting collider

Collider.Raycast - >施放雷,忽略除此之外的所有碰撞者。

Collider2D.Raycast - >将射线投射到场景中,从对撞机位置开始,忽略对撞机本身。

我想像Collider.Raycast一样使用它,它“忽略除了这个以外的所有”,但我现在正在使用Collider2D,我需要投射一个光线投射并检查它是否只用指定Collider2D命中,或者是否有任何更好的方法?

1 个答案:

答案 0 :(得分:-1)

对于2D中的Raycast,理想情况下应使用Physics2D.Raycast方法

(来自Unity Documentation

<!DOCTYPE html>
<html>

<head>

<script>    

function changePokemon() {
  let str = document.getElementById("inpStr").value;  
  let tempStr=parseInt(str)+1;

  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","get_id.php?q="+tempStr,true);
  xmlhttp.send();
}

</script>

</head>

<body>

<form>
First name: <input type="text" id="inpStr" onkeyup="changePokemon()">
</form>
<div id="txtHint"></div>

<a id="right-btn" onclick="changePokemon()"></a>

</body>

</html>

这应该为您提供所需的所有文档。 Physics2D类还有许多有用的相关函数,例如圆形投射,线条投射以及有关如何忽略光线投射中某些图层的信息。

为了节省您的时间,这里是完整的Physics2D.Raycast方法,包括可选变量。

RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

if (hit.collider != null) {
    float distance = Mathf.Abs(hit.point.y - transform.position.y);
    float heightError = floatHeight - distance;
    float force = liftForce * heightError - rb2D.velocity.y * damping;
    rb2D.AddForce(Vector3.up * force);
}

祝你的项目好运!