射线投射甚至没有给Debug.Log("it hit something
,而Debug.DrawRay
确实在敌人和玩家之间划了一条线。
使用以下脚本的敌人位于“忽略射线广播”层,而试图击中的玩家位于“默认”层。
void FixedUpdate() {
RaycastHit hit;
Vector2 diff = PlayerMovement.playerTransform.position - transform.position;
Ray raycastToPlayer = new Ray(transform.position, diff);
Debug.Log(raycastToPlayer);
Debug.DrawRay(transform.position, diff, Color.white, 0.01f, true);
if (Physics.Raycast(raycastToPlayer, out hit)) {
Debug.Log("it hit something");
if (hit.collider != null) {
Debug.Log(hit.collider.gameObject.name);
if (hit.transform.tag == "Player"){
float rotZ = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ);
}
}
}
}
答案 0 :(得分:2)
对于您使用的Ray构造函数,方向应为Vector3:
https://docs.unity3d.com/ScriptReference/Ray.html
但是在您的代码中,您正在传递Vector2。如果是2D游戏,则应使用其他构造函数:
https://docs.unity3d.com/ScriptReference/Ray2D-ctor.html
除此之外,正如他们已经在注释中指出的那样,您将需要传递Physics.Raycast Ray的maxDistance参数:
如果要使用图层,则需要额外的参数表:
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
答案 1 :(得分:2)
您使用的是Vector2
位置,因此我假设您的游戏为2D模式。如果是这样,我认为您需要使用Physics
类的2D版本(请参见HERE):
void FixedUpdate() {
Vector2 diff = (PlayerMovement.playerTransform.position - transform.position).Normalized;
RaycastHit2D hit = Physics2D.Raycast(transform.position, diff);
Debug.DrawRay(transform.position, diff, Color.white, 0.01f, true);
if (hit.collider != null) {
Debug.Log("Raycast hit: " + hit.collider.gameObject.name);
if (hit.transform.tag == "Player") {
float rotZ = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ);
}
}
}