[英]Raycast not detecting colliders
So I'm working on a little top-down perspective game and wanted to add a combat system.所以我正在开发一个自上而下的视角小游戏,并想添加一个战斗系统。 I set it up so that it'll shoot a raycast and if it hits an enemy they'll take damage but the raycast is returning nothing.我将它设置为发射光线投射,如果它击中敌人,他们会受到伤害,但光线投射没有返回任何东西。
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;
}
}
}
The print returns false even when there's a gameobject there.即使那里有游戏对象,打印也会返回 false。 It's probably a simple problem but I don't know what to do lol.这可能是一个简单的问题,但我不知道该怎么办大声笑。
I changed the code for you, because I am not very familiar with the ray, thank you and hope it can help you.我给你改了代码,因为我对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.