【发布时间】:2021-08-16 04:31:14
【问题描述】:
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastControl : MonoBehaviour
{
LineRenderer line;
private Vector3 zeros;
public LayerMask EnemyLayer;
// Start is called before the first frame update
void Start()
{
line = GetComponent<LineRenderer>();
zeros = new Vector3(0f, 0f, 0f);
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Debug.Log("Detected the click");
Vector3 mouse = mouseToWorld(Input.mousePosition);
Ray ray = new Ray(zeros, mouse);
RaycastHit hitData;
if (Physics.Raycast(ray, 10000, EnemyLayer))
{
Vector3[] linePos = new Vector3[] { transform.position, mouse };
line.SetPositions(linePos);
Debug.Log("You've hit a Zomboid!");
}
}
}
public Vector3 mouseToWorld(Vector3 mousePos)
{
mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 mouse = Camera.main.ScreenToWorldPoint(mousePos);
mouse.z = 0f;
return mouse;
}
}
注意:我正在使用 Unity2d 我正在尝试使用 0,0,0 和鼠标的位置来投射从 0,0,0 开始并穿过鼠标位置到 if(physics.Raycast(ray,maxDistance) 中指定的最大距离的射线,敌人层))。但是,这不起作用。当我点击我创建的“僵尸”对象或其后面时,我没有检测到光线投射命中。
我已确保此脚本中设置的图层蒙版与 Zombie 对象中设置的图层蒙版相同。我的 Debug.Log("你已经做到了这一点!");行激活,所以我知道脚本在场景中并且正在被读取,但是 Physics.Raycast(ray,10000,EnemyLayer)) 永远不会返回 true,我们知道这一点是因为 Debug.Log("You've hit a Zomboid! ") 永远不会出现在控制台中。
注意:此脚本附加到的对象 Center 位于 0,0,0。它的 transform.position = 0,0,0
非常感谢您的帮助。
【问题讨论】:
-
你是在尝试撞上 Collider2D 吗?在这种情况下,您宁愿使用
Physics2D.Raycast! -
除上述之外,请记住
Physics/2D.Raycast接受LayerMask以选择性地忽略 层。如果 layerMask 中的所有位都打开,它将与所有碰撞器发生碰撞。如果 layerMask = 0,它将永远不会发现任何与射线的碰撞。 -
@derHugo 是对的。我应该一直使用 Physics.2D 作为 2d 盒子对撞机。我没有意识到它不能与 2d 盒子对撞机一起使用。感谢您的帮助!