Title says it all :3
Thanks in advance
RaycastHit hitInfo;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo))
{
// Ray hit something in scene
Debug.Log("Ray hit : " + hitInfo.collider.gameObject.name);
}
How can i also Debug the ray? and can i limit the range?
Btw, itâs a 2d game, moving on x axis⌠so i donât need it to shoot behind or in front
Yes you can limit the range. You can set a max distance to cast to, and even specify a specific object Layer to check collisions against.
The docs are your friend! Unity - Scripting API: Physics.Raycast
By âDebug the rayâ, do you mean seeing the ray for debug purposes? Unity - Scripting API: Debug.DrawRay
static bool Raycast(Ray ray, RaycastHit hitInfo, float distance);
One possible overload which takes a distance as a parameter, so you can the code posted above and add a float value as a third parameter.
More information:
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
Ok, got everything working fine, but thereâs still one thing that doesnât seem to be right, is there a offset? because the ray is not aiming at the mouse and doesnât move at the same way/speedâŚ
Sometimes it appears to be the same for me but i think thatâs because itâs called every frame in this example.
Try to limit it to a KeyDown event and test whether itâs accurate or not.
I did the debug after a button is pressed, and still the same resultsâŚ
Iâm using this code tho
if (Physics.Raycast (transform.posistion, Input.mousePosition, hit, wepRange)) {
if(hit.collider.gameObject.layer != 3)
switch(hit.collider.gameObject.tag) {
case("Zombie"):
hit.collider.gameObject.GetComponent(HitBox).localDmg = totalDmg;
Instantiate(hitBlood, hit.point, transform.rotation);
break;
default:
return;
break;
}
}
'cause with this
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo))
It didnât dedect the zombie
and this is how off the ray can get,
(red dot is where the mouse was)
Youâre currently using a screen position vector (Input.mousePosition) as a direction vector for the ray. ie. youâre casting a ray from I presume the position of your running man, in the direction of something like Vector3( 60, 100, 0), which is why your ray is firing off up and right of your player.
You need to convert the mousePosition into a position relative to your game scene, using
Vector3 mouseScenePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Then find the direction vector from your running dude to that mouse scene position, and use it as the direction vector in your RayCast call.
// put the mouse click scene position to be the same z-depth as your character
mouseScenePosition = new Vector3(mouseScenePosition.x, mouseScenePosition.y, transform.position.z);
Vector3 shotDirectionVector = mouseScenePosition - transform.position;
if (Physics.Raycast (transform.position, shotDirectionVector, hit, wepRange)) {
}