繁体   English   中英

Raycast 未检测到对撞机

[英]Raycast not detecting colliders

所以我正在开发一个自上而下的视角小游戏,并想添加一个战斗系统。 我将它设置为发射光线投射,如果它击中敌人,他们会受到伤害,但光线投射没有返回任何东西。

Vector3 mouse_pos = Input.mousePosition;
mouse_pos.z = 5.23f;

Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
mouse_pos.x = mouse_pos.x - objectPos.x
mouse_pos.y = mouse_pos.y - objectPos.y

if (Input.GetMouseButtonDown(0))
{
    Raycast hit;
    print(Physics.Raycast(transform.position, mouse_pos, out hit));
    if (Physics.Raycast(transform.position, mouse_pos, out hit))
    {
        if (hit.collider.gameObject.name.Contains("enemy"))
        {
            hit.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
        }
    }
}

即使那里有游戏对象,打印也会返回 false。 这可能是一个简单的问题,但我不知道该怎么办大声笑。

我给你改了代码,因为我对ray不是很熟悉,谢谢,希望对你有帮助。

   void update(){
        if (Input.GetMouseButtonDown(0))
      {
        // When the left mouse button is pressed, emit a ray to the screen 
         position where the mouse is located
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hitInfo;  
       if (Physics.Raycast(ray,out hitInfo))
       {
            // When the ray collides with the object, draw the ray in the scene view
            Debug.DrawLine(ray.origin, hitInfo.point, Color.red);  
        
        if (hitInfo.collider.gameObject.name.Contains("enemy"))
        {
            hitInfo.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
          }
      }
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM